4

I would like to have Stockfish to selfplay 10 games starting from a given position. Game should end after 10 moves. From the python-chess documentation there is an example of playing only one such game, starting from the initial position. Thanks in advance.

import chess
import chess.engine

engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish")

board = chess.Board()
while not board.is_game_over():
    result = engine.play(board, chess.engine.Limit(time=0.1))
    board.push(result.move)

engine.quit()
3

This should get you started, up to you to add extra features based on your objective (such as saving the games and moves, etc.)

import chess
import chess.engine
import os
import sys

arguments = sys.argv
pondertime = float(arguments[1]) #first argument: ponder time in sec
maxmoves = int(arguments[2]) #2nd argument: max number of desired moves
gamecount = int(arguments[3]) #3rd argument: max number of games to play
#here we assume the engine file is in same folder as our python script
path = os.getcwd()
#Now make sure you give the correct location for your stockfish engine file
#...in the line that follows by correctly defining path
engine = chess.engine.SimpleEngine.popen_uci(path+'/'+'stockfish-10-64')

dictsidetomove = {True:'white',False:'black'}
notationdict = {True:'.', False:'...'}

for i in range(gamecount):
    board = chess.Board() #give whatever starting position here
    while not board.is_game_over() and board.fullmove_number<=maxmoves:
        result = engine.play(board,chess.engine.Limit(time=pondertime))
        print(dictsidetomove[board.turn]+' played '+str(board.fullmove_number)+notationdict[board.turn]+str(board.san(result.move)))
        board.push(result.move)
    print('Iteration '+str(i+1)+'-----')
    print(board)
    print('Final position FEN: ',board.fen())
    print('-----')

engine.quit()

Here's an example running it for engine time of 0.1 sec, 10 move game, and 1 game to be played only:

python selfplay.py 0.1 10 1

Printed output:

white played 1.e4
black played 1...d5
white played 2.exd5
black played 2...Qxd5
white played 3.Nf3
black played 3...Nf6
white played 4.Nc3
black played 4...Qd6
white played 5.d4
black played 5...a6
white played 6.Bd3
black played 6...Nc6
white played 7.O-O
black played 7...Bg4
white played 8.Ne4
black played 8...Nxe4
white played 9.Bxe4
black played 9...O-O-O
white played 10.Be3
black played 10...g6
Iteration 1-----
. . k r . b . r
. p p . p p . p
p . n q . . p .
. . . . . . . .
. . . P B . b .
. . . . B N . .
P P P . . P P P
R . . Q . R K .
Final position FEN:  2kr1b1r/1pp1pp1p/p1nq2p1/8/3PB1b1/4BN2/PPP2PPP/R2Q1RK1 w - - 0 11
-----
  • Brilliant! Thank you so much. – Arturo Jan 31 '20 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.