chessengineimpl.java

来自「chess 一个beguanyu国际象棋的一个Java源码」· Java 代码 · 共 1,221 行 · 第 1/3 页

JAVA
1,221
字号
		return true;                      // ply, it seems to be valid.	    }	}	// The computer could not compute the ply, the user has made,	// so we assume, that it is not valid.	System.out.println( "Invalid move " + ply.toString());	System.out.println( "Piecetype on source square " + ( getBoard().getPiece( ply.getSource()) == null ? "null" : "" + getBoard().getPiece( ply.getSource()).getType()));	System.out.println( "Piecetype on destination square " + ( getBoard().getPiece( ply.getDestination()) == null ? "null" : "" + getBoard().getPiece( ply.getDestination()).getType()));	System.out.println( "Valid moves are:");	for( int p = 0; p < plies.length; p++) {  // For each ply	    System.out.print( plies[p].toString() + " ");	}	System.out.println();	return false;    }    /**     * Start the computations of the permanent brain.     */    public final void startPermanentBrain() {	// If the permanent brain is active.	if( usePermanentBrain()) {	    getPermanentBrain().startComputation();	} else {	    // Since the permanent brain cannot reset the counter,	    // I do it here.	    setAnalyzedBoards( 0L);	}    }    /**     * Stop the computations of the permanent brain.     */    public final void stopPermanentBrain() {	getPermanentBrain().stopComputation();    }    /**     * Set the the stop flag for the search.     *     * @param stopFlag The flag to stop the search engine.     */    public final void setSearchStop( boolean stopFlag) {	_stopSearch = stopFlag;    }    /**     * Check, if a search should be stopped.     *     * @return true, if the search should be stopped.     */    public final boolean isSearchStop() {	return _stopSearch;    }    /**     * Get the number of analyzed boards.     *     * @return The number of analyzed boards.     */    public final long getAnalyzedBoards() {	return _analyzedBoards;    }    /**     * Set the number of analyzed boards.     *     * @param analyzedBoards The new number of analyzed boards.     */    public final void setAnalyzedBoards( long analyzedBoards) {	_analyzedBoards = analyzedBoards;    }    /**     * Increase the number of analyzed boards by 1.     */    public final void increaseAnalyzedBoards() {	_analyzedBoards++;    }    /**     * Get the current search depth.     *     * @return The current search depth.     */    public final int getSearchDepth() {	return _searchDepth;    }    /**     * Set a new search depth.     *     * @param searchDepth The new search depth.     */    public final void setSearchDepth( int searchDepth) {	_searchDepth = searchDepth;    }    /**     * Increase the search depth by 1.     */    public final void increaseSearchDepth() {	_searchDepth++;    }    /**     * Decrease the search depth by 1.     */    public final void decreaseSearchDepth() {	_searchDepth--;    }    /**     * Return a menu from the chess engine, where the user     * can change the settings.     *     * @return A menu for the engine settings.     */    public final JMenu getMenu() {	// Create a new menu.	JMenu engineMenu = new JMenu( "Engine");	// Add a toggle item for to the permanent brain.	engineMenu.add( _permanentBrainMenuItem = new JCheckBoxMenuItem( "Use permanent brain", usePermanentBrain()));	_permanentBrainMenuItem.addActionListener( this);	// Add a menu for the maximum search time	JMenu searchTimeMenu = new JMenu( "Search time");	// Add a sub-menu for fixed time.	JMenu searchTimeSubMenuFix = new JMenu( "Fixed time");	// Add a sub-menu for average time.	JMenu searchTimeSubMenuAv = new JMenu( "Average time");	// Add various options for the fixed search time	// (maybe a user defined search time should be added, too).	buttonGroupSearchTime = new ButtonGroup();	_fixSearchTimeMenuItem = new JRadioButtonMenuItem[ _searchTime.length ];	for( int st = 0; st < _searchTime.length; st++) {	    _fixSearchTimeMenuItem[ st ] = new JRadioButtonMenuItem( "" + _searchTime[ st ] + " seconds");	    _fixSearchTimeMenuItem[ st ].addActionListener( this );	    if ( _searchTime[ st ] == 5 )		{ // set initially 5 sec max search time:		    _fixSearchTimeMenuItem[ st ].setSelected( true );		    this.setMaximumSearchTime( 5000 );		}	    buttonGroupSearchTime.add(_fixSearchTimeMenuItem[st]);	    // Add the current search time menu item to it's menu.	    searchTimeSubMenuFix.add( _fixSearchTimeMenuItem[ st ] );	}	// Add various options for the average search time	_avSearchTimeMenuItem = new JRadioButtonMenuItem[ _searchTime.length ];	for( int st = 0; st < _searchTime.length; st++) {	    _avSearchTimeMenuItem[ st ] = new JRadioButtonMenuItem( "" + _searchTime[ st ] + " seconds");	    _avSearchTimeMenuItem[ st ].addActionListener( this );	    // Add the current search time menu item to it's menu.	    searchTimeSubMenuAv.add( _avSearchTimeMenuItem[ st ]);	    buttonGroupSearchTime.add(_avSearchTimeMenuItem[st]);	}	searchTimeMenu.add( searchTimeSubMenuFix );	searchTimeMenu.add( searchTimeSubMenuAv );	// Add the search time menu to the main engine menu.	engineMenu.add( searchTimeMenu);	// Add a menu for the hashtable size.	JMenu hashtableSizeMenu = new JMenu( "Hashtable size");	// Add various options for the hashtable size.	this.buttonGroupHashSize = new ButtonGroup();	_hashtableSizeMenuItem = new JRadioButtonMenuItem[ _hashtableSizes.length];	for( int hts = 0; hts < _hashtableSizes.length; hts++) {	    _hashtableSizeMenuItem[ hts ] = new JRadioButtonMenuItem( "" + _hashtableSizes[ hts ] + " entries");	    _hashtableSizeMenuItem[ hts ].addActionListener( this);	    if ( _hashtableSizes[ hts ] == 10000 )		{		    _hashtableSizeMenuItem[ hts ].setSelected( true );		    getHashtable().setMaximumSize( _hashtableSizes[ hts ]);		}	    // Add the current search time menu item to it's menu.	    hashtableSizeMenu.add( _hashtableSizeMenuItem[hts]);	    this.buttonGroupHashSize.add( _hashtableSizeMenuItem[ hts ] );	}	// Add the search time menu to the main engine menu.	engineMenu.add( hashtableSizeMenu);	// Add a menu item to read openings from PGN files.	engineMenu.addSeparator();	engineMenu.add( new LoadOpeningsAction( getOpeningBook()));	// Return the engine menu.	return engineMenu;    }    /**     * Perform a action (could be a menu related action).     *     * @param actionEvent The event.     */    public final void actionPerformed(ActionEvent actionEvent)    {				// Check, if the user (de-)activated the permanent brain.	if( actionEvent.getSource().equals( _permanentBrainMenuItem)) {	    activatePermanentBrain( _permanentBrainMenuItem.isSelected());	    this.notifyListeners();	    return;	}				// Check if the user has requested a new search time	for( int st = 0; st < _searchTime.length; st++)	    {		if( actionEvent.getSource().equals( _avSearchTimeMenuItem[ st])) {		    setMaximumSearchTime( _searchTime[ st] * 1000);		    this.bFixedTime = false;		}		if( actionEvent.getSource().equals( _fixSearchTimeMenuItem[ st ])) {		    setMaximumSearchTime( _searchTime[ st ] * 1000);		    this.bFixedTime = true;		}	    }				// Check, if the user has requested a different hashtable size.	for( int hts = 0; hts < _hashtableSizes.length; hts++)	    {		if( actionEvent.getSource().equals( _hashtableSizeMenuItem[ hts]))		    {			getHashtable().setMaximumSize( _hashtableSizes[ hts ]);		    }	    }	this.notifyListeners();    }    /**     * Sets the EnginePanel to be able to output in the panel and not only with     * System.out.println(...)     *     * @param panel The EnginePanel to set     */    public void setEnginePanel(EnginePanel panel) {	this._enginePanel = panel;    }    /**     * Get the current game state.     *     * @param white True, if the state of the white player is requested.     *     * @return The current game state.     */    public final byte getCurrentGameState( boolean white) {	// Test if the given player is in check.	boolean inCheck = _analyzer.isInCheck( (BitBoard)getBoard(), white);	// Test if the player has valid plies available.	// The following computation of the available plies is not really efficient,	// since they are done anyway (either to compute the next computer ply or to	// check if a user ply is valid). So maybe the plygenerator or the engine should	// cache the computed plies.	boolean validPliesAvailable = ( _plyGenerator.getPliesForColor( (BitBoard)getBoard(), white).length > 0);	if( inCheck) {	    return validPliesAvailable ? GameState.CHECK : GameState.CHECKMATE;	} else {	    return validPliesAvailable ? GameState.ONGOING : GameState.DRAW;	}    }    public void setStatusPanel(StatusPanel myPanel) {	if ( this._statusPanel != myPanel )	    this._statusPanel = myPanel;    }    /**     * Initially create a logfile     */    private void createLogFile()    {	File homedir = new File(System.getProperty("user.home"));	f = new File(homedir, LOG_FILENAME );	try{	    FileWriter fileWriter = new FileWriter(f);	    PrintWriter printWriter = new PrintWriter( fileWriter );	    printWriter.println( "## Java-Chess Engine Logfile, do not edit! ##" );	    printWriter.println( "## For internal use only! ##" );	    printWriter.close();	}	catch (IOException e) {}    }    /**     * Ads a log entry into the JavaChess logfile     *     * @param text The text to append     */    private void addLogEntry(String text)    {	if ( f != null )	    {		try{		    // First read the existing lines into vBuffer		    BufferedReader bfrIniFile = new BufferedReader( new FileReader( f ) );		    String strOrgLine = bfrIniFile.readLine();		    vBuffer = new Vector();		    String strLine;		    while( strOrgLine != null )			{			    strLine = strOrgLine.trim();			    this.vBuffer.addElement( strLine );			    strOrgLine = bfrIniFile.readLine();			}		    // now create file new but with same filename		    FileWriter fileWriter = new FileWriter(f);		    PrintWriter printWriter = new PrintWriter(fileWriter);		    // insert former existing text:		    String strWrite[] = new String[vBuffer.size()];		    vBuffer.copyInto( strWrite );		    for( int i=0; i < vBuffer.size(); i++ )			{			    printWriter.println( strWrite[i] );			}		    // add the new text now:		    printWriter.println( text );		    printWriter.close();		}		catch (Exception e) {}	    }    }    /**     * Returns whether the search time is fixed or not.     *     * @return Is the search time fixed?     */    public boolean isFixedTime() {	return ( this.bFixedTime );    }    /**     * Returns the hash size     *     * @return The hashsize     */    public int getHashSize() {	return ( this.getHashtable().getMaximumSize() );    }    /**     * Returns the status string to display in status bar     */    public String getStatusDisplayString()    {	String retString = "HashSize: " + this.getHashSize() + " entries; "	    + "Search time: " + this.getMaximumSearchTime()/1000 + "sec";	if ( this.isFixedTime() )	    {		retString += " fix";	    }	else{	    retString += " average";	}	return ( retString );    }    /**     * Registers an object for notification.     * @param listener The object to be registered.     */    public void addEngineStatusListener(EngineStatusListener listener) {	listeners.add(listener);    }    /**     * Notifies all registered listeners that the engine has taken a change.     */    public void notifyListeners()    {	Iterator iterator = listeners.iterator();	while (iterator.hasNext())	    {		EngineStatusListener listener = (EngineStatusListener)iterator.next();		listener.engineStatusChanged( this );	    }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?