Search code examples
inputinfinite-loopchess

Check for input while searching (Python chess engine)


I am making a chess engine in Python.

It can receive UCI commands via the console.

Currently, when I input "go", it will start searching. And when I input "stop", it will stop searching.

But the problem is, it searches one depth by a time, so for example, if I input "go" and it searches to depth 10, and I input "stop", it will only receive and process the command when it reaches depth 11.

Currently, I have a uci.py which runs this in an infinite loop:

while True:
    # process commands
    if command == "go":
        search(...)
    elif command == "stop":
        # do something to stop the search

Is there a way to instantly stop the search when I type the stop command?

I tried to add a stop_search() function but that does not work since the search() function need to complete before the commands are even processed.


Solution

  • Yes, you need to do this inside your UCI code and in your AI search code.

    In the UCI code you need to set searcher to stop search when you receieve stop (and quit?) command:

    if command == "stop":
        searcher.stopped = true
    

    Then in your AI searcher code you need to check if this has occured. You don't have to do this all the time, but e.g. at every 2 000th node you search. Check this right after you have unmade the move from AI Search and then return something like 0 or null (depends on your implementation):

    # Check every 2000 nodes
    if not self.nodes % 2000:
        if self.stopped:
            return 0
    

    This is at the same place where you would check for time out, where the engine has used up the given time.

    Be sure to save results from previous searches so that you always give a move back as a result. If you stop early you don't want to give the LATEST result back as move (and score), you want to give the latest which is not equal to 0 (or null or whatever).