예제 #1
0
def run_game(white: Player,
             black: Player,
             visualize: bool = False,
             fps: int = DEFAULT_FPS) -> tuple[str, list[str]]:
    """Run a Minichess game between the two given players.

    Return the winner and list of moves made in the game.
    """
    game = MinichessGame()

    move_sequence = []
    previous_move = None
    current_player = white
    while game.get_winner() is None:

        previous_move = current_player.make_move(game, previous_move)
        game.make_move(previous_move)
        move_sequence.append(previous_move)

        if visualize:
            display.update(game.get_fen(), game.get_winner())
            time.sleep(1 / fps)

        if current_player is white:
            current_player = black
        else:
            current_player = white

    if visualize:
        # Give slightly more time to the victory visualization
        time.sleep(4 / fps)

    return game.get_winner(), move_sequence
예제 #2
0
def playpgn(pgn):
    display.start()
    board = chess.Board()
    for move in pgn:
        board.push(move)
        display.update(board.fen())
        input()
예제 #3
0
파일: main.py 프로젝트: taaha-khan/chess-ai
def run(agents, show_display = True):

	board = chess.Board()
	display.start()

	player = 0

	while not display.checkForQuit():

		display.update(board.fen())

		if not board.is_game_over():

			obs = lambda: None
			obs.board = board.fen()
			obs.mark = board.turn

			config = lambda: None
			config.actTimeout = 1

			active = agents[player]
			agent_move = active(obs, config)

			board.push(agent_move)
			player = -(player - 1)

	display.terminate()
예제 #4
0
def playGame(pauseTime,
             player,
             algorithms,
             showDisplay=False,
             playYourself=False):
    if showDisplay:
        display.start()
    board = chess.Board()
    pgn = []

    print("player is:" + str(player))
    while True:
        #generating moves based on the turn
        if board.turn == bool(player + 1):
            move = algorithms[0].generateMoves(board.fen(), board.turn, player)
        else:
            if not playYourself:

                #move = movesToList(board.legal_moves)[random.randint(0,len(movesToList(board.legal_moves))-1)]
                move = algorithms[1].generateMoves(board.fen(), board.turn,
                                                   -player)
            else:
                while True:
                    moveInput = input("enter your move:")
                    try:
                        move = chess.Move.from_uci(moveInput)
                        print(move)
                        if move in board.legal_moves:
                            break
                        else:
                            print("please enter a legal move!")
                    except ValueError:
                        print("Please enter a real move!")
        #moving, displaying, checking if the game has ended
        time.sleep(pauseTime)
        pgn.append(move)
        board.push(move)
        if showDisplay:
            display.update(board.fen())
        if board.is_checkmate():
            if board.turn == bool(player + 1):
                print("loss")
                return False, pgn, board.fen()

            else:
                print("win")
                return True, pgn, board.fen()

        if board.is_stalemate() or board.is_insufficient_material(
        ) or board.can_claim_threefold_repetition(
        ) or board.is_seventyfive_moves() or board.can_claim_fifty_moves():
            print("No one")
            return None, pgn, board.fen()
예제 #5
0
def lets_play_chess(player_color='white', previous_moves=None, fancy_display=False):
    if player_color == 'white':
        player_color = True
    elif player_color == 'black':
        player_color = False
    else:
        player_color = None
    if fancy_display:
        display.start()
    board = chess.Board()
    game_so_far = '<#endofdoc#>'
    tries = 0
    turn_counter = 1
    while not board.is_game_over():
        if board.turn and game_so_far[-1] != '.':
            game_so_far += f' {board.fullmove_number}.'
        if board.turn == player_color:
            proposed_move = input(f'{"White" if player_color else "Black"}\'s turn: ')
            try:
                move_san = board.parse_san(proposed_move)
            except:
                print('that is not a legal move. Try again')
                continue
            if board.is_legal(move_san):
                board.push_san(proposed_move)
                game_so_far += ' ' + str(proposed_move)
                print(board.unicode(borders=True, empty_square=' '))
                if fancy_display:
                    display.update(board.fen())

            else:
                print('that is not a legal move. Try again')
                continue
        else:
            proposed_move, tries = predict_next_move(game_so_far, tries)
            try:
                move_san = board.parse_san(proposed_move)
                board.push_san(proposed_move)
                game_so_far += ' ' + str(proposed_move)
                print(f'The computer succeeded on attempt number {tries} to make a legal move.')
                print(board.unicode(borders=True, empty_square=' '))
                if fancy_display:
                    display.update(board.fen())

                tries = 0
            except:
                print(f'try #{tries}: {proposed_move}')
                if tries > 10:
                    print('Looks like I need a little help... lets move randomly and move on')
                    random_moves = random.sample(board.legal_moves.__str__().split(' ')[3:], 1)[0]
                    random_moves = random_moves.replace('(', '').replace(')', '').replace('>', '').replace(',', '')
                    board.push_san(random_moves)
                    game_so_far += ' ' + str(proposed_move)
                    print(board.unicode(borders=True, empty_square=' '))
                    if fancy_display:
                        display.update(board.fen())
                    tries = 0
                else:
                    continue
            # if board.is_legal(move_san):
            #
            # else:

        print(game_so_far)
        if board.fullmove_number > 40:
            lets_play_chess(None)
            break
        if fancy_display:
            display.checkForQuit()
    print(f'the game is over! congrats to {"white" if board.result() == "1-0" else "black" if board.result() == "0-1" else "both on the tie"}')
    if fancy_display:
        display.terminate()
예제 #6
0
#!usr/bin/env python
"""stockfishDemo.py: quick engine demo to A)show stockfish works B) create new python REPO"""

import chess
import chess.engine

from chessboard import display
from time import sleep

def start(fen=''):
	global gameboard


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

board = chess.Board()
display.start(board.fen())

while not board.is_game_over():
	result = engine.play(board,chess.engine.Limit(time=1.01))
	board.push(result.move)
	print(board.peek())
	print(board.fen)
	print("test")
	display.update(board.board_fen())

engine.quit()
display.terminate()