def main(): screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gamestate = GameState() loadImages() running = True selected_square = () # Stores previously-clicked square clicks = [] # [(6,4),(4,4)] moves white pawn forward two while running: for e in p.event.get(): if e.type == p.QUIT: running = False if e.type == p.MOUSEBUTTONDOWN: mouse_position = p.mouse.get_pos( ) # Gives (x, y) location of mouse col = mouse_position[0] // SQUARE_SIZE row = mouse_position[1] // SQUARE_SIZE if (selected_square == (row, col)): selected_square = () # If already selected, deselect clicks = [] # Clear clicks else: selected_square = (row, col) clicks.append(selected_square) if (len(clicks) == 2): move = Move(clicks[0], clicks[1], gamestate.board) print(move.getChessNotation()) gamestate.makeMove(move) selected_square = () clicks = [] drawGameState(screen, gamestate, selected_square) # Draws screen every tick clock.tick(FPS) p.display.flip() # Updates screen every tick
def ai_light_move(gs): """ makes automated valid light moves input parameter(s): gs --> Game_state object return parameter(s): light_move --> move made for light team gs --> Game_state object """ ### TODO: edit to your unique algorithm (mini-max w/ pruning, etc) ### ### Static evaluation of the board can be done with 'light_pieces' and 'dark_pieces' dictionaries ### light_move = None move = minimax(gs, 3)[0] # Move as decided by minimax if move: # create move copy (only copy (start_row, start_col) & (end_row, end_col) of move object) light_move = Move((move.start_row, move.start_col), (move.end_row, move.end_col), gs.board) gs.make_move(light_move) # make move # handles pawn promotion if (light_move.end_row == 0) and (light_move.piece_moved[0] == "p"): gs.board[light_move.end_row][light_move.end_col] = random.choice( ("ql", "rl", "bl", "nl")) # randomly select promotion piece # update light pieces position dictionary # light_pieces.pop("{},{}".format(light_move.start_row, light_move.start_col)) # light_pieces["{},{}".format(light_move.end_row, light_move.end_col)] = light_move.piece_moved # # remove pieces captured from dark_piece dictionary for faster static board evaluation in your mini-max algorithm rewrite # if light_move.piece_captured != " " and not light_move.en_passant_captured: # dark_pieces.pop("{},{}".format(light_move.end_row, light_move.end_col)) # elif light_move.en_passant_captured: # dark_pieces.pop("{},{}".format(light_move.end_row+1, light_move.end_col if gs.light_to_move else light_move.end_row-1, light_move.end_col)) else: if gs.is_in_check(): gs.check_mate = True else: gs.stale_mate = True return light_move, gs
def ai_dark_move(gs): """ makes automated valid dark moves input parameter(s): gs --> Game_state object return parameter(s): dark_move --> move made for dark team gs --> Game_state object """ ### TODO: edit to your unique algorithm (mini-max w/ pruning, etc) ### ### Static evaluation of the board can be done with 'light_pieces' and 'dark_pieces' dictionaries ### valid_moves, turn = gs.get_valid_moves() if valid_moves: move = random.choice(valid_moves) # select random move to make # create move copy (only copy (start_row, start_col) & (end_row, end_col) of move object) dark_move = Move((move.start_row, move.start_col), (move.end_row, move.end_col), gs.board) gs.make_move(dark_move) # make move # handles pawn promotion if (dark_move.end_row == 7) and (dark_move.piece_moved[0] == "p"):\ gs.board[dark_move.end_row][dark_move.end_col] = random.choice(("qd", "rd", "bd", "nd")) # randomly select promotion piece # update dark pieces position dictionary # dark_pieces.pop("{},{}".format(dark_move.start_row, dark_move.start_col)) # dark_pieces["{},{}".format(dark_move.end_row, dark_move.end_col)] = dark_move.piece_moved # # remove pieces captured from light_piece dictionary for faster static board evaluation in your mini-max algorithm rewrite # if dark_move.piece_captured != " " and not dark_move.en_passant_captured: # light_pieces.pop("{},{}".format(dark_move.end_row, dark_move.end_col)) # elif dark_move.en_passant_captured: # light_pieces.pop("{},{}".format(dark_move.end_row+1, dark_move.end_col if gs.light_to_move else dark_move.end_row-1, dark_move.end_col)) else: dark_move = None return dark_move, gs
def main(): # Variables needed for pygame run = True pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Chess') selectedSquare = () # (x, y) playerClicks = [] # Has 2 tuples Start, End validMoves = board.getValidMoves() madeMove = False # flag to only check valid moves once a move is made boosting performance while run: for event in pygame.event.get(): # if user closes the program if event.type == pygame.QUIT: run = False elif event.type == pygame.MOUSEBUTTONDOWN: # if the user clicks the left mouse button if event.button == 1: # Gets the mouse location and divides by the square size this integer value is the index of the square location = pygame.mouse.get_pos() col = location[0] // SQUARE_SIZE row = location[1] // SQUARE_SIZE if selectedSquare == (row, col): selectedSquare = () # Deselect as user clicked twice playerClicks = [] # Reset Clicks else: selectedSquare = (row, col) playerClicks.append(selectedSquare) if len(playerClicks) == 2: # deselects the clicks on empty squares if board.board[playerClicks[0][0]][playerClicks[0][1]] == 0: playerClicks = [] else: # creates the Move object and executes the move if its in the Valid moves move = Move(playerClicks[0], playerClicks[1], board) print(move.getChessNotation()) if move in validMoves: board.makeMove(move) madeMove = True # resets the variables for the next move selectedSquare = () playerClicks = [] elif event.button == 3: # if the user clicks the right mouse button board.undoMove() madeMove = True # if a move is made or unmade check for the valid moves for this position if madeMove: validMoves = board.getValidMoves() madeMove = False clock.tick(FPS) drawGame(screen, validMoves, selectedSquare) pygame.display.flip() pygame.quit()
def main(): screen = pg.display.set_mode((WIDTH + BORDER, HEIGHT + BORDER)) clock = pg.time.Clock() #screen.fill(pg.Color("ghostwhite")) screen.fill(pg.Color("brown4")) gs = Game_state() load_images() running = True square_selected = () # x, y coordinate of selected square player_clicks = [] # list of appended square_selected valid_moves = [] while running: valid_moves, first_click_turn = gs.get_valid_moves() for e in pg.event.get(): if e.type == pg.QUIT: running = False elif e.type == pg.KEYDOWN: if e.key == pg.K_u: # u key pressed (undo last move) gs.undo_move() elif e.key == pg.K_r: # r key pressed (reset game) gs = Game_state() valid_moves, turn = [], None square_selected = () player_clicks = [] print("Board reset!") elif e.type == pg.MOUSEBUTTONDOWN: location = pg.mouse.get_pos() # x, y location of mouse click location_col_transform = location[0] // SQ_SIZE - 1 location_row_transform = location[1] // SQ_SIZE - 1 col = (location_col_transform) if ( 0 <= location_col_transform < 8) else -1 row = (location_row_transform) if ( 0 <= location_row_transform < 8) else -1 if col >= 0 and row >= 0: if square_selected == (row, col): # clicked same position twice square_selected = () player_clicks = [] else: # new position clicked (destination) square_selected = (row, col) player_clicks.append(square_selected) if len(player_clicks ) == 2: # 'from' and 'to' are available move = Move(player_clicks[0], player_clicks[1], gs.board) # create move object if move in valid_moves: gs.make_move(move) animate(move, screen, gs.board, clock) print(move.get_chess_notation()) square_selected = () player_clicks = [] else: current_turn = "l" if gs.light_to_move else "d" if current_turn == first_click_turn: player_clicks = [square_selected] square_selected = () else: player_clicks = [] square_selected = () display_game_state(screen, gs, valid_moves, player_clicks) clock.tick(MAX_FPS) pg.display.flip()
def main(): screen = pg.display.set_mode((WIDTH + BORDER, HEIGHT + BORDER)) clock = pg.time.Clock() #screen.fill(pg.Color("ghostwhite")) screen.fill(pg.Color("brown4")) #screen.fill(pg.Color("sienna")) gs = Game_state() load_images() running = True square_selected = () # x, y coordinate of selected square player_clicks = [] # list of appended square_selected valid_moves, first_click_turn = gs.get_valid_moves( ) # compute valid moves outside loop (for efficiency) game_over = False # signals end of game user_prompt = False # pauses gui rendering for user input AI_MODE = False # flag for activating AI mode delay = 0 # delay the speed of AI plays display_time = 0 # AI_MODE text display persistence timer while running: if not user_prompt: found = False if AI_MODE and display_time == 0 and not game_over: # pause a bit between AI plays if delay > 0 if delay == 0: move, gs = ai_move(gs) if move: # if AI made a move animate(move, screen, gs.board, clock) print(move.get_chess_notation()) delay = 4 # pause magnitude else: delay -= 1 for e in pg.event.get(): if e.type == pg.QUIT: running = False elif e.type == pg.KEYDOWN: if e.key == pg.K_u and not AI_MODE: # u key pressed (undo last move) gs.undo_move() valid_moves, first_click_turn = gs.get_valid_moves() elif e.key == pg.K_r and not AI_MODE: # r key pressed (reset game) gs = Game_state() valid_moves, turn = [], None square_selected = () player_clicks = [] print("Board reset!") valid_moves, first_click_turn = gs.get_valid_moves() elif e.key == pg.K_a: # a key pressed (toggle AI mode) #toggle = True display_time = 10 AI_MODE = not AI_MODE ai_reset() print("AI MODE ENABLED") if AI_MODE else print( "AI MODE DISABLED") elif e.type == pg.MOUSEBUTTONDOWN: if not game_over and not AI_MODE: location = pg.mouse.get_pos( ) # x, y location of mouse click location_col_transform = location[0] // SQ_SIZE - 1 location_row_transform = location[1] // SQ_SIZE - 1 col = (location_col_transform) if ( 0 <= location_col_transform < 8) else -1 row = (location_row_transform) if ( 0 <= location_row_transform < 8) else -1 if col >= 0 and row >= 0: if square_selected == ( row, col): # clicked same position twice square_selected = () player_clicks = [] else: # new position clicked (destination) square_selected = (row, col) player_clicks.append(square_selected) if len(player_clicks ) == 2: # 'from' and 'to' are available move = Move(player_clicks[0], player_clicks[1], gs.board) # create move object for obj in range(len(valid_moves)): if move == valid_moves[obj]: move = valid_moves[obj] found = True gs.make_move(move) if (move.end_row == 0 or move.end_row == 7) and (move.piece_moved[0] == "p"): user_prompt = True choice = ("q", "r", "b", "n") promotion = "" while promotion not in choice: promotion = input( "Promote to: q => Queen, r => Rook, b => Bishop, n => Knight\n" ) gs.board[move.end_row][ move. end_col] = promotion + move.piece_moved[ 1] user_prompt = False animate(move, screen, gs.board, clock) print(move.get_chess_notation()) square_selected = () player_clicks = [] valid_moves, first_click_turn = gs.get_valid_moves( ) break if not found: # move selected not a valid move current_turn = "l" if gs.light_to_move else "d" if current_turn == first_click_turn: player_clicks = [square_selected] square_selected = () else: player_clicks = [] square_selected = () display_game_state(screen, gs, valid_moves, player_clicks) # display text for switching AI mode if display_time > 0: display_text(screen, "AI MODE ENABLED", "Green") if AI_MODE else display_text( screen, "AI MODE DISABLED", "Red") display_time -= 1 # countdown for text to disappear if gs.check_mate: game_over = True if gs.light_to_move: display_text(screen, "Dark wins by checkmate") else: display_text(screen, "Light wins by checkmate") elif gs.stale_mate: game_over = True display_text(screen, "Stalemate") clock.tick(MAX_FPS) pg.display.flip()
def main(choice=False): screen = pg.display.set_mode((WIDTH + BORDER, HEIGHT + BORDER)) clock = pg.time.Clock() #screen.fill(pg.Color("ghostwhite")) screen.fill(pg.Color("Peru")) gs = Game_state() load_images() gs.light_to_move = not gs.light_to_move if FLIP else True running = True square_selected = () # x, y coordinate of selected square player_clicks = [] # list of appended square_selected valid_moves, first_click_turn = gs.get_valid_moves() # compute valid moves outside loop (for efficiency) game_over = False # signals end of game user_prompt = False # pauses gui rendering for user input AI_MODE = choice # flag for activating AI mode delay = 0 # delay the speed of AI plays display_time = 0 # AI_MODE text display persistence timer PLAYBACK_MODE=False playback_index=0 while running: if not user_prompt: found = False if AI_MODE and display_time == 0 and not game_over: # pause a bit between AI plays if delay > 0 if delay == 0: move, gs = ai_move(gs) if move: # if AI made a move animate(move, screen, gs.board, clock) print(move.get_chess_notation()) if Move.mute==True: engine.say(move.get_chess_notation()) engine.runAndWait() delay = 20 # pause magnitude else: delay -= 1 for e in pg.event.get(): if e.type == pg.QUIT: running = False elif e.type == pg.KEYDOWN: if e.key == pg.K_u and not AI_MODE and not PLAYBACK_MODE: # u key pressed (undo last move) gs.undo_move() valid_moves, first_click_turn = gs.get_valid_moves() elif e.key == pg.K_m: # m key pressed (mute commentary) Move.mute=not Move.mute elif e.key == pg.K_r and not AI_MODE and not PLAYBACK_MODE: # r key pressed (reset game) gs = Game_state() valid_moves, turn = [], None square_selected = () player_clicks = [] print("Board reset!") if Move.mute==True: engine.say("Board reset!") engine.runAndWait() valid_moves, first_click_turn = gs.get_valid_moves() # elif e.key == pg.K_a: # a key pressed (toggle AI mode) # #toggle = True # display_time = 10 # AI_MODE = not AI_MODE # ai_reset() # print("AI MODE ENABLED") if AI_MODE else print("AI MODE DISABLED") elif e.key == pg.K_p and not AI_MODE and game_over: PLAYBACK_MODE = not PLAYBACK_MODE playback_log = gs.move_log gs = Game_state() valid_moves, turn = [], None square_selected = () player_clicks = [] valid_moves, first_click_turn = gs.get_valid_moves() print("PLAYBACK MODE ENABLED \nNumber of Moves Available: " + str(len(playback_log))) if PLAYBACK_MODE else print( "PLAYBACK MODE DISABLED") playback_index = 0 elif e.key == pg.K_n and PLAYBACK_MODE and game_over: if len(playback_log) == 0: print("No Moves to Play") if Move.mute==True: engine.say("No Moves to Play") engine.runAndWait() break if playback_index == len(playback_log): # playback_index = len(playback_log) - 1 print("Max Playback Reached!") if Move.mute==True: engine.say("Max Playback Reached!") engine.runAndWait() else: str_sqr = str(playback_log[playback_index]) start_row = int(str_sqr[1]) start_col = int(str_sqr[4]) start_sqr = (start_row, start_col) end_row = int(str_sqr[8]) end_col = int(str_sqr[11]) end_sqr = (end_row, end_col) clicked_sqr = [start_sqr, end_sqr] # print(start_sqr) # print(end_sqr) # print(str_sqr) # print(clicked_sqr) playback_index += 1 move = Move( start_sqr, end_sqr, gs.board) gs.make_move(move) animate(move, screen, gs.board, clock) print("Move: "+str((playback_index))) if Move.mute==True: engine.say("Move: "+str((playback_index))) engine.runAndWait() print(move.get_chess_notation()) if Move.mute==True: engine.say(move.get_chess_notation()) engine.runAndWait() elif e.key == pg.K_b and PLAYBACK_MODE and game_over: if playback_index <= 0: playback_index = 0 print("Min Playback Reached!") if Move.mute==True: engine.say("Min Playback Reached!") engine.runAndWait() else: playback_index -= 1 print("Move: "+str((playback_index+1))) if Move.mute==True: engine.say("Move: "+str((playback_index+1))) engine.runAndWait() gs.undo_move() valid_moves, first_click_turn = gs.get_valid_moves() # gs.make_move(move) # animate(gs.undo_move, screen, gs.board, clock) # print(move.get_chess_notation()) elif e.type == pg.MOUSEBUTTONDOWN: if not game_over and not AI_MODE: location = pg.mouse.get_pos() # x, y location of mouse click location_col_transform = location[0] // SQ_SIZE - 1 location_row_transform = location[1] // SQ_SIZE - 1 col = (location_col_transform) if (0 <= location_col_transform < 8) else -1 row = (location_row_transform) if (0 <= location_row_transform < 8) else -1 if col >= 0 and row >= 0: if square_selected == (row, col): # clicked same position twice square_selected = () player_clicks = [] else: # new position clicked (destination) square_selected = (row, col) player_clicks.append(square_selected) if len(player_clicks) == 2: # 'from' and 'to' are available move = Move(player_clicks[0], player_clicks[1], gs.board) # create move object for obj in range(len(valid_moves)): if move == valid_moves[obj]: move = valid_moves[obj] found = True gs.make_move(move) if (move.end_row == 0 or move.end_row == 7) and (move.piece_moved[0] == "p"): user_prompt = True choice = ("q", "r", "b", "n") promotion = True while promotion: for event in pg.event.get(): if event.type == pg.MOUSEBUTTONDOWN: location = pg.mouse.get_pos() # x, y location of mouse click location_col_transform = location[0] // square- 1 # divided by sqaure size location_row_transform = location[1] // square - 1 row_comb= [1,2,15,16] # list for all the possible rows if location_row_transform in row_comb: #making sure the event meet requirements row = location_row_transform col =location_col_transform if ((row == 15) and (col%2 != 0)) or ((row == 1) and (col%2 != 0)): piece = "q" elif ((row == 15) and (col%2 == 0)) or ((row == 1) and (col%2 == 0)): piece = "r" elif ((row == 16) and (col%2 != 0)) or ((row == 2) and (col%2 != 0)): piece = "b" elif ((row == 16) and (col%2 == 0)) or ((row == 2) and (col%2 == 0)): piece = "n" print("Promoting Piece") if Move.mute==True: engine.say("Promoting Piece") engine.runAndWait() promotion = False display_board2(screen,move.end_row, move.end_col) pg.display.update() clock.tick(5) gs.board[move.end_row][move.end_col] = piece+ move.piece_moved[1] user_prompt = False animate(move, screen, gs.board, clock) print(move.get_chess_notation()) if Move.mute==True: engine.say(move.get_chess_notation()) engine.runAndWait() square_selected = () player_clicks = [] valid_moves, first_click_turn = gs.get_valid_moves() break if not found: # move selected not a valid move current_turn = "l" if gs.light_to_move else "d" if current_turn == first_click_turn: player_clicks = [square_selected] square_selected = () else: player_clicks = [] square_selected = () display_game_state(screen, gs, valid_moves, player_clicks) # display text for switching AI mode if display_time > 0: display_text(screen, "AI MODE ENABLED", "Green") if AI_MODE else display_text( screen, "AI MODE DISABLED", "Red") display_time -= 1 # countdown for text to disappear if AI_MODE and not game_over: if gs.light_to_move: display_Thinking_text(screen, gs, "Thinking....") else: display_Thinking_text(screen, gs, "Thinking....") if gs.check_mate: game_over = True AI_MODE = False engine.say("Checkmate!") engine.runAndWait() engine.stop() if gs.light_to_move: display_text(screen, "Dark wins by checkmate") else: display_text(screen, "Light wins by checkmate") elif gs.stale_mate: game_over = True AI_MODE = False engine.say("Stalemate!") engine.runAndWait() display_text(screen, "Stalemate") clock.tick(MAX_FPS) pg.display.flip()
from engine import GameState, Move x = Move('w', [(1, 2), (1, 2)]) print(x.player, x.start_positions, x.end_positions) y = GameState(7, is_white_turn=True) print(y.show_state()) print(y.turn) print(x.start_positions) print((y.board[1][1]) > 1) y.make_move(x) print(y.move_to_backgammon_notation(x)) print(y.show_state()) print(y.move_log)
def main(): #setup GUI p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() sys.stdout.flush() #Start Gamestate gs = GameState() validMoves = gs.getValidMoves() #load images for pieces loadImages() #flag variables running = True moveMade = False foundMove = False #coord variables sqSelected = () #holds coord of last click of user (tuple: row, col) playerClicks = [ ] #list that keep track of player clicks (2 tuples[(6, 4), (4, 4)] while running: for e in p.event.get(): if e.type == p.QUIT: running = False #mouse handler elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() # (x, y) location of mouse col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == (row, col): #click same square twice sqSelected = () playerClicks = [] else: #clicked a new square sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: move = Move(playerClicks[0], playerClicks[1], gs.board, 0) foundMove = False for moves in validMoves: if move.moveID == moves.moveID: gs.makeMove(moves, validMoves) moveMade = True foundMove = True sqSelected = () playerClicks = [] if foundMove is False: playerClicks = [sqSelected] foundMove = False #key handler elif e.type == p.KEYDOWN: if e.key == p.K_z and AIPLAYER: #undo when z is pressed gs.undoMove() gs.undoMove() moveMade = True if e.key == p.K_z and AIPLAYER == False: gs.undoMove() moveMade = True if e.key == p.K_x and AIPLAYER: #undo when x is pressed gs.undoMove() moveMade = True if e.key == p.K_n and (gs.checkmate or gs.stalemate) and not AUTOMATIC: gs.writeResults() del gs gs = GameState() validMoves = gs.getValidMoves() drawGame(screen, gs, sqSelected, validMoves) clock.tick(FPS) p.display.flip() #AI PLAYING if AIPLAYER and not gs.checkmate and not gs.stalemate and moveMade == False: if RANDOM: if gs.whiteMove == False and BLACKAI: time.sleep(SLEEPTIME) gs.randomMove(validMoves) moveMade = True elif gs.whiteMove == True and WHITEAI: time.sleep(SLEEPTIME) gs.randomMove(validMoves) moveMade = True else: if gs.whiteMove == False and BLACKAI: time.sleep(SLEEPTIME) gs.AI(validMoves) moveMade = True elif gs.whiteMove == True and WHITEAI: time.sleep(SLEEPTIME) gs.AI(validMoves) moveMade = True if moveMade and not gs.checkmate and not gs.stalemate: validMoves = gs.getValidMoves() gs.evaluateBoard(gs.boardScore, validMoves) moveMade = False if (gs.checkmate or gs.stalemate) and AUTOMATIC: gs.writeResults() del gs gs = GameState() validMoves = gs.getValidMoves()