def test_alpha_beta_agent_policy(): """How does the agent handle naive examples.""" agent = AlphaBetaAgent(color='black', depth=2) game = Game(current_color='white') game.move((7, 1), (1, 1)) move = agent.policy(game) assert move == ((0, 2), (1, 1)), ( f"Agent should take horse with bishop. But it's policy is {move}, " f"with actions values:\n{str(agent)}\n{game}" )
def move(): """ Player Move """ try: game = Game(request.json['field'], { 'turn': request.json['turn'], 'eaten': request.json['eaten'], 'check': request.json['check'], }) game.move(request.json['move']) return jsonify(game.to_json()) except Exception as e: # traceback.print_exception(e) return jsonify({'error': str(e)})
class Console: def __init__(self, state): self.game = Game() if state == 'yes': self.game.load() else: self.game.create() def chess_setup(self): for figure in self.game.figures: self.game.board[figure.x][figure.y] += 1 def start(self): self.chess_setup() while True: if self.game.whomoves % 2 == 0: print("White's turn") else: print("Black's turn") start = input( 'Figure on which positions do you wanna move?' + '\n' + 'If you want to save your game, type save, if quit, type quit.\n' ) if start == 'save': name = input( 'Type name of file in which you wanna save the game.\n') name += '.txt' self.game.save(name) start = input('Figure on which positions do you wanna move?\n') if start == 'quit': quit() startx = self.positions(start) startx = start.split() dest = input('Where do you wanna move it?\n') destx = self.positions(dest) move = self.game.move(startx[0], startx[1], destx[0], destx[1]) if move != 0: if move == 1: print("Whites are Winners") if move == 2: print("Blacks are Winners") return def positions(self, position): return int(position.split()[0]), int(position.split()[1])
class Visualizer: def __init__(self, square, state): self.game = Game() if state == 'yes' or state == 'Yes': self.game.load() else: self.game.create() self.main = Tk() self.w = Canvas(self.main, width=square, height=square + square / 8) self.w.pack() self.w.bind('<Button-3>', self.first_click) self.w.bind('<Button-1>', self.second_click) self.square = square self.small_square = square / 8 self.weak_reference = [] self.quit = False def create_chess(self): for i in range(8): for j in range(8): if (i + j) % 2 == 0: m = "saddle brown" else: m = "wheat" self.w.create_rectangle(i * self.small_square, j * self.small_square, (i + 1) * self.small_square, (j + 1) * self.small_square, fill=m) self.w.create_rectangle(0, self.square, self.square / 2, self.square + self.square / 8, fill='orange2') self.w.create_text(self.square / 4, self.square + self.square / 16, fill='white', font=('Purisa', 50), text="Save") self.w.create_rectangle(self.square / 2, self.square, self.square, self.square + self.square / 8, fill='gray1') self.w.create_text(self.square - self.square / 4, self.square + self.square / 16, fill='white', font=('Purisa', 50), text="Quit") def chess_setup(self): for figure in self.game.figures: figure.image = figure.image.resize( (int(self.small_square), int(self.small_square)), Image.ANTIALIAS) photo = ImageTk.PhotoImage(figure.image) self.weak_reference.append(photo) self.w.create_image( (figure.x * self.small_square) + self.small_square / 2, (figure.y * self.small_square) + self.small_square / 2, image=photo) self.game.board[figure.x][figure.y] = 1 def visualize_valid_moves(self, startx, starty, color): for i in range(8): for j in range(8): if self.game.control(startx, starty, i, j): if self.game.board[i][j] == 1: for figure in self.game.figures: if figure.x == i and figure.y == j: if figure.color == color: if (i + j) % 2 == 0: m = "saddle brown" else: m = "wheat" else: m = "red" break else: m = "green yellow" else: if (i + j) % 2 == 0: m = "saddle brown" else: m = "wheat" self.w.create_rectangle(i * self.small_square, j * self.small_square, (i + 1) * self.small_square, (j + 1) * self.small_square, fill=m) self.chess_setup() def first_click(self, event): if self.quit: quit() self.startx = int(event.x / self.small_square) self.starty = int(event.y / self.small_square) if self.starty == 8: if 0 <= self.startx <= 3: self.save() else: quit() chosen_figure = [ val for val in self.game.figures if (self.startx == val.x and self.starty == val.y) ] self.visualize_valid_moves(self.startx, self.starty, chosen_figure[0].color) def second_click(self, event): if self.quit: quit() self.destx = int(event.x / self.small_square) self.desty = int(event.y / self.small_square) if self.desty == 8: if 0 <= self.destx <= 3: self.save() else: quit() else: move = self.game.move(self.startx, self.starty, self.destx, self.desty) if move != 0: if move == 1 or move == 2: if move == 1: m = 'white' else: m = 'black' self.w.create_text(self.square / 2, self.square / 2, fill=m, font=('Purisa', 100), text="Winner") self.quit = True return self.redraw() def delete_stoogles(self): for figure in self.game.figures: self.w.delete("all") self.game.board[figure.x][figure.y] = 0 self.weak_reference = [] def redraw(self): self.delete_stoogles() self.create_chess() self.chess_setup() def start(self): self.redraw() self.main.mainloop() def save(self): name = input("Type name of file in which you wanna save the game:\n") name += '.txt' self.game.save(name)
class GameLoop(): """ Control player input """ def __init__(self, ai=None, fen=None, fps=30): """ Initialises game loop """ self.chess_game = Game(fen=fen) self.ai = ai self.FPS = fps self.fpsClock = pygame.time.Clock() self.start() def start(self): Screen.start_screen() Screen.load_all_chessmen() Screen.draw_checkered_board() Screen.draw_all_chessmen(self.chess_game.board.BOARD) self.chess_game.start_turn() move_from = None move_to = None b_possible_moves = None # Game loop while True: if self.chess_game.gameover: Screen.draw_btm_bar() Screen.display_btm_info(self.chess_game.gameover) Screen.draw_top_bar() Screen.display_top_info("Press SPACE to play again") elif self.chess_game.claim_draw: Screen.draw_btm_bar() Screen.display_btm_info("Accept draw? (press y to accept)") # Computer AI plays black elif not self.chess_game.white_to_move(): if self.ai: ai_move = self.chess_game.get_random_move() if self.chess_game.move(ai_move) == PROMOTE: self.chess_game.move(ai_move, promote="Q") Screen.draw_checkered_board() Screen.draw_all_chessmen(self.chess_game.board.BOARD) Screen.draw_top_bar() self.chess_game.start_turn() else: Screen.draw_btm_bar() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN and not self.chess_game.gameover: if event.key == K_y and self.chess_game.claim_draw: self.chess_game.gameover = DRAW self.chess_game.start_turn() break elif event.type == pygame.KEYDOWN and self.chess_game.gameover: if event.key == K_SPACE: self.chess_game = Game(fen=self.chess_game.fen) GameLoop.draw_whole_screen(self.chess_game.board.BOARD) self.chess_game.start_turn() elif event.type == pygame.MOUSEBUTTONDOWN and not self.chess_game.gameover: # If already clicked on a piece if move_from: # Next click = move_to square move_to = GameLoop.get_clicked_square(event.pos) if move_to: try_move = self.chess_game.move(move_from + move_to) else: try_move = None # If move_to is a legal move if try_move == PROMOTE: Screen.display_top_info( "Choose promotion piece (press Q, R, B, or N)") Screen.update() promote_piece = None while not promote_piece: promote_piece = GameLoop.choose_promotion_piece( ) self.chess_game.move(move_from + move_to, promote=promote_piece) Screen.draw_checkered_board() Screen.draw_all_chessmen( self.chess_game.board.BOARD) Screen.draw_top_bar() self.chess_game.start_turn() move_from = None move_to = None break elif try_move: move_from = None move_to = None Screen.draw_checkered_board() Screen.draw_all_chessmen( self.chess_game.board.BOARD) self.chess_game.start_turn() break # If clicked same square elif move_to == move_from: Screen.draw_checkered_board() Screen.draw_all_chessmen( self.chess_game.board.BOARD) move_from = None move_to = None break # If move_to_square has legal moves, make that the move_from square elif self.chess_game.get_possible_squares( square=move_to): move_from = move_to move_to = None # If move_to is not a legal move, reset cicked squares else: move_from = None move_to = None Screen.draw_checkered_board() Screen.draw_all_chessmen( self.chess_game.board.BOARD) break # If no piece selected move_from = GameLoop.get_clicked_square(event.pos) Screen.draw_checkered_board() Screen.draw_all_chessmen(self.chess_game.board.BOARD) legal_moves = self.chess_game.get_possible_squares( square=move_from) if legal_moves: for sq in legal_moves: Screen.draw_dot_on_square(sq) break pygame.display.update() self.fpsClock.tick(self.FPS) @staticmethod def draw_whole_screen(board): """ Draws top and bottom bars, and board and chessmen """ Screen.draw_top_bar() Screen.draw_btm_bar() Screen.draw_checkered_board() Screen.draw_all_chessmen(board) @staticmethod def get_clicked_square(pos): """ Gets square where mouse clicked """ file = int((pos[0] - Screen.LEFTBAR) / Screen.GRID_SIZE) rank = 7 - int((pos[1] - Screen.TOPBAR) / Screen.GRID_SIZE) if rank < 0 or rank > 7: return None elif file < 0 or file > 7: return None else: square = TO_FILE[file] + TO_RANK[rank] return square @staticmethod def choose_promotion_piece(): """ Waits for user button click """ for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYUP: if event.key == K_q: return "Q" elif event.key == K_r: return "R" elif event.key == K_b: return "B" elif event.key == K_n: return "N"