def test_move(PosY, PosX, DestPosY, DestPosX): game_state = ChessEngine.GameState() move = ChessEngine.Move([PosY, PosX], [DestPosX, DestPosY], game_state.board) game_state.make_move(move) piece = game_state.board[DestPosX][DestPosY] return piece
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) screen.fill(p.Color("white")) gs = ChessEngine.GameState() loadImages() running = True selectedSq = () playerClicks = [] validMoves = [] while running: for e in p.event.get(): if e.type == p.QUIT: running = False if e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() col = location[0]//SQ_SIZE row = location[1]//SQ_SIZE selectedSq = (row, col) playerClicks.append((row, col)) if len(playerClicks) == 1: if gs.board[row][col][0] == ("w" if gs.whiteToMove else "b"): #Valid selection validMoves = gs.generateValidMoves(row, col) else: playerClicks = [] elif len(playerClicks) == 2: move = ChessEngine.Move(playerClicks[0][0], playerClicks[0][1], row, col) if gs.checkValidMove(move, validMoves): gs.makeMove(move) playerClicks = [] drawGameState(screen, gs, selectedSq, validMoves) p.display.flip()
def makeMove(self): if not self.openingMove: chosenMove = None finalMove = None depth = 0 boardValue = self.get_board_value(self.state, None, True) if boardValue <= 2500: self.endGame = True else: self.endGame = False while not self.timeUp: depth += 1 chosenMove = self.minimaxRoot(self.state, depth, True) if not self.timeUp: finalMove = chosenMove print("Depth = " + str(depth)) self.state.makeMove(finalMove, True) self.cg.branchingFactors.append( sum(self.branchingFactors) / len(self.branchingFactors)) self.cg.totalVisited += self.visited elif self.openingMove and self.state.whiteToMove: self.state.makeMove(random.choice(self.whiteOpeners), True) elif self.openingMove and not self.state.whiteToMove: if self.state.board[4][4] == "wp": self.state.makeMove( ChessEngine.Move((1, 4), (3, 4), self.state.board), True) elif self.state.board[4][3] == "wp": self.state.makeMove( ChessEngine.Move((1, 3), (3, 3), self.state.board), True)
def main(): pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() screen.fill(pygame.Color("white")) game_state = ChessEngine.GameState() # GAME_STATE validMoves = game_state.getValidMoves() moveMade = False # flag variable for when a move is made load_images() running = True sqSelected = () # Square clicked by user tuple(row, col) playerClicks = [] # Where user clicked after list[(row, col), (row2,col2)] while running: for e in pygame.event.get(): if e.type == pygame.QUIT: running = False # mouse handler elif e.type == pygame.MOUSEBUTTONDOWN: location = pygame.mouse.get_pos() # (x,y) location of mouse col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == ( row, col): # The user clicked the same square twice sqSelected = () # unselect playerClicks = [] # clear clicks else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: # after 2nd click move = ChessEngine.Move(playerClicks[0], playerClicks[1], game_state.board) print(move.get_chess_notation()) for i in range(len(validMoves)): if move == validMoves[i]: game_state.make_move(validMoves[i]) moveMade = True sqSelected = () # Reset clicks playerClicks = [] # Reset clicks if not moveMade: playerClicks = [sqSelected] # key handler elif e.type == pygame.KEYDOWN: if e.key == pygame.K_z: # "z" pressed game_state.undo_move() moveMade = True # Create new valid moves after move if moveMade: validMoves = game_state.getValidMoves() moveMade = False drawGameState(screen, game_state) clock.tick(15) pygame.display.flip()
def test_move(PosY, PosX, DestPosY, DestPosX, figure): game_state = ChessEngine.GameState() game_state.clearBoard() game_state.set_figure_in_position(PosY, PosX, figure) move = ChessEngine.Move([PosY, PosX], [DestPosX, DestPosY], game_state.board) game_state.make_move(move) piece = game_state.board[DestPosX][DestPosY] return piece
def main(): # initialise pygame p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False #flag to check the move made loadImages() running = True sqSelected = () #keeps track of last click of the user, Tuple playerClicks = [] #keeps a track of player clicks, Two tuples. ( while running: for e in p.event.get(): if e.type == p.QUIT: running = False #Mouse Listener elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() # x,y cords of mouse click col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == (row, col): sqSelected = () # deselect playerClicks = [] # clear player clicks else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) for i in range(len(validMoves)): if move == validMoves[i]: gs.makeMove(move) moveMade = True sqSelected = () # reset clicks playerClicks = [] if not moveMade: playerClicks = [sqSelected] # Keyboard Listener elif e.type == p.KEYDOWN: if e.key == p.K_z: #Undo when z is pressed gs.UndoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() moveMade = False drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False #flag variable for when a move is made load_images() running = True sqSelected = () #keeps track of the last click of the user playerClicks = [] #keeps track of player clicks while (running): for e in p.event.get(): if e.type == p.QUIT: running = False #clicking elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() #x and y location of mousezx col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == (row, col): #clicking the same square cancels sqSelected = () playerClicks = [] else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) for i in range(len(validMoves)): if move == validMoves[i]: print(validMoves[i].getChessNotation()) gs.makeMove(validMoves[i]) moveMade = True sqSelected = () #reset user click playerClicks = [] if not moveMade: print('Invalid Move') sqSelected = () playerClicks = [] #key press elif e.type == p.KEYDOWN: if e.key == p.K_z: gs.undoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() moveMade = False draw_gamestate(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def DoCompTurn(turn): if mainState.END: return if mainState.movenumber <= 5: start, end = ChessEngine.OpeningMoves(turn, mainState.movenumber, mainState.randmove) else: mv = ChessEngine.FindBest(turn) start, end = mv.movestart, mv.moveend checkForDead(start, end) pm.MovePiece(start, end) drawStuff(end) switchTurn(turn)
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("White")) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False loadImages() running = True sqSelected = () playerClicks = [] while running: for e in p.event.get(): if e.type == p.QUIT: running = False #souris elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() #(x,y) position de la souris col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == ( row, col ): #l'utilisateur clique sur le même carré deux fois sqSelected = () #déselectionne la case playerClicks = [] #efface/enlève le click du joueur else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: #après le deuxième click move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) for i in range(len(validMoves)): if move == validMoves[i]: gs.makeMove(validMoves[i]) moveMade = True sqSelected = () #reset le click playerClicks = [] if not moveMade: playerClicks = [sqSelected] #clavier elif e.type == p.KEYDOWN: if e.key == p.K_z: #annule le coup quand w(w = z en qwerty) est pressé gs.undoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() moveMade = False drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False loadImages() running = True sqSelected = () #no square is selected playerClicks = [] #keep trac k of player place while running: for e in p.event.get(): if e.type == p.QUIT: running = False elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == (row, col): # clicks same square twice sqSelected = () playerClicks = [] else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) for i in range(len(validMoves)): if move == validMoves[i]: gs.makeMove(validMoves[i]) moveMade = True sqSelected = () playerClicks = [] if not moveMade: playerClicks = [sqSelected] elif e.type == p.KEYDOWN: if e.key == p.K_z: gs.undoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() moveMade = False drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False #flag variable for when a move is made loadImages() #Load once, move images around running = True sqSelected = ( ) #Intial selection is empty, tracks last click of user (row, col) playerClicks = [] #list with 2 tuples: [(6, 5), (4, 4)] pawn move tracked while running: for e in p.event.get(): if e.type == p.QUIT: #exit strategy running = FALSE #MouseFunctions elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() #Where is the mouse col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == ( row, col ): #this clears the selection after a 2nd click on a square sqSelected = () Playerclicks = [] else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks ) == 2: #Make a move on the second unique click move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) if move in validMoves: gs.makeMove(move) moveMade = True sqSelected = () #reset the click count playerClicks = [] #Key functions elif e.type == p.KEYDOWN: if e.key == p.K_z: #undo when keyboard z is pressed gs.undoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() movemade = False drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def main(): screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False #flag varible for when a move is made loadImages() running = True sqSelected = () #nosquare is selected at first. Keeps track of the last click of the user playerClicks = [] #keeps track of player's clicks 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() col = location[0]//SQ_SIZE row = location[1]//SQ_SIZE if sqSelected == (row, col): #if the user clicks the smae square twice sqSelected = () playerClicks =[] else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2 : move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(playerClicks) print(move.getChessNotation()) if move in validMoves: gs.makeMove(move) moveMade = True sqSelected = () #reset clicks playerClicks = [] #key handler elif e.type == p.KEYDOWN: if e.key == p.K_z: #undo when 'z' is pressed gs.undoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() moveMade = False drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color('white')) gs = ChessEngine.GameState() valid_moves = gs.get_valid_moves() move_made = False # flag variable for when a move is made load_images() # only do this once, before the while loop running = True sq_selected: Tuple = () # no square is selected, keep track of the last click of the user (tuple: (row, col)) player_clicks = [] # keep track of player clicks (two 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 sq_selected == (row, col): # the user clicked the same square twice sq_selected = () # unselect player_clicks = [] # clear player clicks else: sq_selected = (row, col) player_clicks.append(sq_selected) # append for both 1st and 2nd clicks if len(player_clicks) == 2: # after 2nd click move = ChessEngine.Move(player_clicks[0], player_clicks[1], gs.board) print(move.get_chess_notation()) if move in valid_moves: gs.make_move(move) move_made = True sq_selected = () # reset user clicks player_clicks = [] # key handlers elif e.type == p.KEYDOWN: if e.key == p.K_z: # undo when 'z' is pressed gs.undo_move() move_made = True if move_made: valid_moves = gs.get_valid_moves() move_made = False draw_game_state(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def __init__(self): self.instructions_ = Instructions.Instructions("instructions_pl.txt", "Instrukcje gry") self.instructions_.show_instructions() self.chess_engine_ = ChessEngine.ChessEngine(True) self.gui_ = GUI.GUI() self.converter_ = ChessConverter.ChessConverter()
def main(): p.init() screen=p.display.set_mode((Width,Height)) clock = p.time.Clock() screen.fill(p.Color("white")) gs=ChessEngine.GameState() print(gs.board)
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() loadImages() running = True sqSelected = () # no square is selected initially - one tuple:(row,col) playerClicks = [ ] # keep tracks of the player clicks - two tuples: [(6,4),(4,4)] while running: for e in p.event.get(): if e.type == p.QUIT: running = False p.quit() elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos( ) # (x, y) coordinates for the mouse col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE #check if the user already selected this square, as it wqould be an undo if sqSelected == (row, col): sqSelected = () #Unselect the square playerClicks = [] #reset the clicks else: sqSelected = (row, col) playerClicks.append( sqSelected ) # we append both the first and second clicks #was this the user's second click? if len(playerClicks) == 2: #after the second click move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) gs.makeMove(move) sqSelected = () # reset the user clicks playerClicks = [] drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def generate_possible_moves(self, row, col, possible_moves, moves_dict, direction): end_sq = (row, col) if not (self.is_valid_square(end_sq)): return if not self.is_pinned or self.pin_direction == direction or self.opp_direction[ self.pin_direction] == direction: possible_moves.append(c.Move(self.current_sq, end_sq, self.board)) if self.board[row][col] != ".." and self.board[row][ col].color != self.color: # if the piece is of an opposing color return return self.moves_dict[direction](row, col, possible_moves, moves_dict)
def main(): p.init() window = p.display.set_mode((W_WIDTH, W_HEIGHT)) time = p.time.Clock() window.fill(p.Color("black")) gamestate = ChessEngine.Game() loadIMG() loop = True squareSelected = ( ) # this tuple holds the last click that was made (col,row) clicks = [ ] # two tuples meaning click 1 -> piece selected and click 2-> piece moved highlight = False row = -1 col = -1 while (loop): for e in p.event.get(): if e.type == p.QUIT: # quit the game loop = False elif e.type == p.MOUSEBUTTONDOWN: # player selected a square cursorposition = p.mouse.get_pos() # map the cursor position to dimensions needed for the board row = cursorposition[1] // SQ_SIZE col = cursorposition[0] // SQ_SIZE if squareSelected == (col, row): # player clicked the same sq twice # clears the clicks highlight = False squareSelected = () clicks = [] else: squareSelected = (col, row) clicks.append(squareSelected) # adds the last click if len(clicks ) == 1: # player selected a piece, so highlight it if row == 0 or row == 9: highlight = False squareSelected = () clicks = [] elif gamestate.board[row - 1][col] != "**": highlight = True else: highlight = False squareSelected = () clicks = [] if len(clicks) == 2: highlight = False clicks = [] squareSelected = [] drawBoard(window, gamestate, highlight, col, row) time.tick(FPS) p.display.flip()
def __init__(self, GameState, openingMove, isWhite, ChessGame): self.state = GameState self.openingMove = openingMove self.whiteOpeners = [ ChessEngine.Move((6, 4), (4, 4), self.state.board), ChessEngine.Move((6, 3), (4, 3), self.state.board), ChessEngine.Move((7, 6), (5, 5), self.state.board), ChessEngine.Move((6, 2), (4, 2), self.state.board) ] self.isWhite = isWhite self.ztable = [[[random.randint(1, 2**64 - 1) for i in range(12)] for j in range(8)] for k in range(8)] self.hashValue = self.computeHash(self.state.board) self.hashtable = dict() self.timeUp = False self.timer = threading.Timer(29.0, self.changeTimer) self.timer.start() self.endGame = False self.visit = False self.cg = ChessGame self.branchingFactors = [] self.visited = 0
def main(): ''' Main ''' screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() load_images() running = True while running: for e in p.event.get(): if e.type == p.QUIT: running = False draw_game_state(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color('white')) gs = ChessEngine.GameState() loadImages() running = True sqSelected = () # no square selected, keep track of last click of the user tuples: (row, col) playerClicks = [] # keep track of player clicks, [(6,4), (4,4)] while running: for e in p.event.get(): if e.type == p.QUIT: running = False elif e.type == p.MOUSEBUTTONDOWN: location = p.mouse.get_pos() # (x,y) position of mouse col = location[0]//SQ_SIZE row = location[1]//SQ_SIZE if sqSelected == (row, col): sqSelected = () # deselect playerClicks = [] # clear the clicks else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: # after second click move the pawn move = ChessEngine.Move( playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) gs.makeMove(move=move) sqSelected = () playerClicks = [] drawGameState(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def possible_moves(self): list_possible_moves = [(self.row + 2, self.col + 1), (self.row + 2, self.col - 1), (self.row + 1, self.col + 2), (self.row + 1, self.col - 2), (self.row - 2, self.col + 1), (self.row - 2, self.col - 1), (self.row - 1, self.col + 2), (self.row - 1, self.col - 2)] current_sq = (self.row, self.col) if not self.in_bounds(current_sq): print("****************RED FLAG****************") print(self.name + " " + self.color) print(current_sq) valid_moves = [] for move in list_possible_moves: if self.is_valid_square(move) and not self.is_pinned: possible_king = self.board[move[0]][move[1]] valid_moves.append(c.Move(current_sq, move, self.board)) return valid_moves
def __init__(self,game_mode): """Initializes the game in the desired game_mode""" self.moved_pieces = pygame.sprite.LayeredDirty() self.taken_pieces = pygame.sprite.LayeredDirty() self.white_pieces = pygame.sprite.LayeredDirty() self.black_pieces = pygame.sprite.LayeredDirty() self.board = Board() self.board.display() self.load_piece_dict('TileSet.png') self.init_pieces() self.chess_engine = ChessEngine() self.dirty_rects = [] self.selected_piece = None self.selected_square = None self.white_to_move = True self.display_fps = False
def move_piece(start, end): global moveMade global validMoves print("Move", start, end) move = ChessEngine.Move(start, end, game.board[sizeToBoard[size]]) validMoves = game.allValidMoves(sizeToBoard[size]) # for i in range(10): # print(validMoves[i].startRow, validMoves[i].startCol, "|", validMoves[i].endRow, validMoves[i].endCol) #print(move) #print(validMoves[0]) if game.board[sizeToBoard[size]][start[0]][start[1]] == "wV" or game.board[ sizeToBoard[size]][start[0]][start[1]] == "bV": print("Vanguard") if game.VanguardMoveAlternative(sizeToBoard[size], start[0], start[1], end[0], end[1]): print("valid") moveMade = True game.makeMove(move, sizeToBoard[size]) client.put_chess(game.board[sizeToBoard[size]], game.whiteToMove) moveMade = False return for k, move2 in enumerate(validMoves): if move2.startRow == move.startRow and move2.startCol == move.startCol and move2.endRow == move.endRow and move2.endCol == move.endCol: print("valid") moveMade = True game.makeMove(move, sizeToBoard[size]) client.put_chess(game.board[sizeToBoard[size]], game.whiteToMove) break else: moveMade = False if not moveMade: print("invalid") if moveMade: #validMoves = game.allValidMoves(sizeToBoard[size]) # for i in range(1): # print(validMoves[i].startRow, validMoves[i].startCol, "|", validMoves[i].endRow, validMoves[i].endCol) moveMade = False
def main(): """ The main driver for our code. This will handle user input and updating the graphics. """ p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color('white')) gs = ChessEngine.GameState() load_images() # only do this once, before the while loop running = True while running: for e in p.event.get(): if e.type == p.QUIT: running = False draw_game_state(screen, gs) clock.tick(MAX_FPS) p.display.flip()
def possible_moves(self): possible_moves = [] current_sq = (self.row, self.col) if not self.in_bounds(current_sq): print("****************RED FLAG****************") print(self.name + " " + self.color) print(current_sq) possible_directions = [(self.row + 1, self.col), (self.row + 1, self.col + 1), (self.row + 1, self.col - 1), (self.row - 1, self.col), (self.row - 1, self.col + 1), (self.row - 1, self.col - 1), (self.row, self.col - 1), (self.row, self.col + 1)] for direction in possible_directions: if (self.in_bounds(direction) and self.has_no_opposing_pieces(direction)): possible_moves.append(c.Move(current_sq, direction, self.board)) return possible_moves
def main(): p.init() screen = p.display.set_mode((BOARD_WIDTH+MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) moveLogFont = p.font.SysFont("Arial", 12, False, False) gs = ChessEngine.GameState() validMoves = gs.getValidMoves() moveMade = False #flag variable for when a move is made animate = False #flag for when to animate #print(gs.board) loadImages() #only do once, before while loop running = True sqSelected = () #no square selected initially, keep track of last click of user (tuple: (row,col)) prevSqSelected = () secondPrevSqSelected = () playerClicks = [] #keeps track of player clicks (two tuples: [(6,4),(4,4)]) gameOver = False playerOne = -1 #if human is playing white,then this will be true. If AI is playing, then false #can also make this an integer value, 0 being human 1-10 being difficulty of AI playerTwo = -1 #Same as above but for black while running: humanTurn = (gs.whiteToMove and playerOne == -1) or (not gs.whiteToMove and playerTwo == -1) for e in p.event.get(): if e.type == p.QUIT: running = False #handles mouse elif e.type == p.MOUSEBUTTONDOWN: if not gameOver and humanTurn: location = p.mouse.get_pos() #(x,y) location of mouse col = location[0]//SQ_SIZE #to get col, integer divide x coord on board w size of each square row = location[1]//SQ_SIZE #to get row, integer divide y coord on board w size of each square if sqSelected == (row,col) or col >= 8: #user clicked same square twice, so unselect or user clicked mouse log sqSelected = () #deselect playerClicks = [] #clear player clicks else: sqSelected = (row,col) playerClicks.append(sqSelected) #append for both 1st and 2nd clicks if len(playerClicks) == 2: #after 2nd click move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) for i in range(len(validMoves)): if move == validMoves[i]: gs.makeMove(validMoves[i]) print(str(gs.moveLog[-1])) moveMade = True animate = True prevSqSelected = playerClicks[-1] secondPrevSqSelected = playerClicks[-2] sqSelected = () #reset uer clicks playerClicks = [] if not moveMade: playerClicks = [sqSelected] #handles keys elif e.type == p.KEYDOWN: if e.key == p.K_z: #undo when 'z' is pressed gs.undoMove() moveMade = True animate = False gameOver = False if e.key == p.K_r: #reset when 'r' is pressed gs = ChessEngine.GameState() validMoves = gs.getValidMoves() sqSelected = () prevSqSelected = () secondPrevSqSelected = () moveMade = False gameOver = False animate = False #Chess AI if not gameOver and not humanTurn: if gs.whiteToMove: AIMove = chessAI.findBestMove(gs, validMoves, playerOne) else: AIMove = chessAI.findBestMove(gs, validMoves, playerTwo) if AIMove is None: if(len(validMoves) != 0): AIMove = chessAI.findRandomMove(validMoves) else: break gs.makeMove(AIMove) print(str(gs.moveLog[-1])) moveMade = True animate = True if moveMade: if animate: animateMove(gs.moveLog[-1], screen, gs.board, clock) validMoves = gs.getValidMoves() moveMade = False #print(prevSqSelected) drawGameState(screen,gs, validMoves, sqSelected, prevSqSelected, secondPrevSqSelected, moveLogFont) if gs.checkMate or gs.staleMate: gameOver = True text = 'Draw by stalemate' if gs.staleMate else ('Black wins by checkmate' if gs.whiteToMove else 'White wins by checkmate') drawEndGameText(screen, text) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() p.display.set_caption('Chess') # Game state gs = ChessEngine.GameState() minmaxPruning = ChessEngine.MinMaxPruning() validMoves = gs.getValidMoves() moveMade = False loadImages() # loadImage() running = True sqSelected = () # tuple (row, col) playerClicks = [] while running: if gs.whiteToMove: 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): # player clicked the same square sqSelected = () # deselect playerClicks = [] # clear player click else: sqSelected = (row, col) playerClicks.append( sqSelected) # apend fot 1st and 2nd click if len(playerClicks) == 2: # after player's 2nd click move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) if move in validMoves: gs.makeMove(move) moveMade = True sqSelected = () # reset player clicks playerClicks = [] else: playerClicks = [sqSelected] # key handler elif e.type == p.KEYDOWN: if e.key == p.K_z: gs.undoMove() moveMade = True if moveMade: validMoves = gs.getValidMoves() moveMade = False else: # print(minmaxPruning.minmaxRoot(2, gs)) bestMove = minmaxPruning.minmaxRoot(3, gs) gs.makeMove(bestMove) print("best move: ", bestMove.getChessNotation()) moveMade = True sqSelected = () # reset player clicks playerClicks = [] print("luot cua trang: ", gs.whiteToMove) # drawGameState(screen, gs) drawGameState(screen, gs, validMoves, sqSelected) clock.tick(MAX_FPS) p.display.flip()
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() validMoves = gs.getValidMove() moveMade = False ChessEngine.print_text_board(gs.board) loadImages() running = True sqSelected = () # box clicked by the user (row,col) playerClicks = [] # all clicks by user [(row,col),(row,col)] gameOver = False p.display.set_caption(turnText(gs.whiteToMove)) flag = 1 choice = 1 while running: if flag: flag = 0 choice = OptionWindow(screen, gs) if choice == 0: break for event in p.event.get(): if not gs.whiteToMove and choice == 2: move = aimove(gs, 3) gs.makeMove(move) moveMade = True p.display.set_caption(turnText(gs.whiteToMove)) print(len(gs.moveLog)) if event.type == p.QUIT: running = False # mouse handel # mouse press elif event.type == p.MOUSEBUTTONDOWN and (gs.whiteToMove or choice == 1): if gameOver == True: break location = p.mouse.get_pos() col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sqSelected == (row, col): sqSelected = () playerClicks = [] else: sqSelected = (row, col) playerClicks.append(sqSelected) if len(playerClicks) == 2: # two box selected move the piece move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board) print(move.getChessNotation()) print(playerClicks) for i in range(len(validMoves)): if move == validMoves[i]: print("moved here:", move.endRow, move.endCol) if validMoves[i].isPawnPromotion: print("Promote to:") new_piece = input().upper() validMoves[ i].promotionChoice = new_piece if new_piece in ( "Q", "R", "N", "B") else "Q" gs.makeMove(validMoves[i]) moveMade = True p.display.set_caption(turnText(gs.whiteToMove)) sqSelected = () playerClicks = [] break if not moveMade: playerClicks = [sqSelected] elif event.type == p.KEYDOWN: if event.key == p.K_z: # z to undo move print(gs.moveLog) gs.undoMove() if not gs.whiteToMove and choice == 2: gs.undoMove() moveMade = True p.display.set_caption(turnText(gs.whiteToMove)) if event.key == p.K_c: # c to clear variables sqSelected = () playerClicks = [] if event.key == p.K_f: # f to print valid moves for i in validMoves: print(i.startRow, i.startCol, i.endRow, i.endCol) if event.key == p.K_r: gs = ChessEngine.GameState() validMoves = gs.getValidMove() playerClicks = [] sqSelected = () moveMade = False p.display.set_caption(turnText(gs.whiteToMove)) if moveMade: validMoves = gs.getValidMove() moveMade = False p.display.set_caption(turnText(gs.whiteToMove)) drawGameState(screen, gs, validMoves, sqSelected) if gs.checkMate: gameOver = True if gs.whiteToMove: drawText(screen, "Black WON by checkmate") else: drawText(screen, "White WON by checkmate") clock.tick(MAX_FPS) p.display.flip()
def main(): """ Main driver. Handles user input and updating the board """ p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = ChessEngine.GameState() valid_moves = gs.get_valid_moves() move_made = False # Flag variable for when a move is made animate = False # Flag variable for when to animate load_images() running = True square_selected = () # no square selected initially, keeps track of the last user click player_clicks = [] # keeps track of player clicks [(1,2),(2,2)] game_over = False while running: for e in p.event.get(): if e.type == p.QUIT: running = False # mouse handlers elif e.type == p.MOUSEBUTTONDOWN: if not game_over: location = p.mouse.get_pos() # (x,y) location of mouse column = location[0]//SQ_SIZE row = location[1]//SQ_SIZE if square_selected == (row, column): # checking if user clicks the same square twice square_selected = () # deselects player_clicks = [] # clear player clicks else: square_selected = (row, column) player_clicks.append(square_selected) if len(player_clicks) == 2: move = ChessEngine.Move(player_clicks[0], player_clicks[1], gs.board) for i in range(len(valid_moves)): if move == valid_moves[i]: gs.make_move(valid_moves[i]) print(move.get_chess_notation()) move_made = True animate = True # reset user clicks square_selected = () player_clicks = [] if not move_made: player_clicks = [square_selected] # key handlers elif e.type == p.KEYDOWN: if e.key == p.K_z: gs.undo_move() move_made = True animate = False game_over = False if e.key == p.K_r: gs = ChessEngine.GameState() valid_moves = gs.get_valid_moves() square_selected = () player_clicks = [] move_made = False animate = False game_over = False if move_made: if animate: animate_move(gs.move_log[-1], screen, gs.board, clock) valid_moves = gs.get_valid_moves() move_made = False animate = False draw_game_state(screen, gs, valid_moves, square_selected) if gs.checkmate: game_over = True if gs.white_to_move: draw_text(screen, "Black wins by checkmate") else: draw_text(screen, "White wins by checkmate") elif gs.stalemate: game_over = True draw_text(screen, "Stalemate") clock.tick(MAX_FPS) p.display.flip()
def main(): """ The main driver for our code. This will handle user input and updating the graphics. """ p.init() screen = p.display.set_mode( (BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) game_state = ChessEngine.GameState() valid_moves = game_state.getValidMoves() move_made = False # flag variable for when a move is made animate = False # flag variable for when we should animate a move loadImages() # do this only once before while loop running = True square_selected = ( ) # no square is selected initially, this will keep track of the last click of the user (tuple(row,col)) player_clicks = [] # this will keep track of player clicks (two tuples) game_over = False ai_thinking = False move_undone = False move_finder_process = None move_log_font = p.font.SysFont("Arial", 14, False, False) player_one = True # if a human is playing white, then this will be True, else False player_two = False # if a hyman is playing white, then this will be True, else False while running: human_turn = (game_state.white_to_move and player_one) or (not game_state.white_to_move and player_two) for e in p.event.get(): if e.type == p.QUIT: p.quit() sys.exit() # mouse handler elif e.type == p.MOUSEBUTTONDOWN: if not game_over: location = p.mouse.get_pos( ) # (x, y) location of the mouse col = location[0] // SQUARE_SIZE row = location[1] // SQUARE_SIZE if square_selected == ( row, col ) or col >= 8: # user clicked the same square twice square_selected = () # deselect player_clicks = [] # clear clicks else: square_selected = (row, col) player_clicks.append( square_selected ) # append for both 1st and 2nd click if len(player_clicks ) == 2 and human_turn: # after 2nd click move = ChessEngine.Move(player_clicks[0], player_clicks[1], game_state.board) for i in range(len(valid_moves)): if move == valid_moves[i]: game_state.makeMove(valid_moves[i]) move_made = True animate = True square_selected = () # reset user clicks player_clicks = [] if not move_made: player_clicks = [square_selected] # key handler elif e.type == p.KEYDOWN: if e.key == p.K_z: # undo when 'z' is pressed game_state.undoMove() move_made = True animate = False game_over = False if ai_thinking: move_finder_process.terminate() ai_thinking = False move_undone = True if e.key == p.K_r: # reset the game when 'r' is pressed game_state = ChessEngine.GameState() valid_moves = game_state.getValidMoves() square_selected = () player_clicks = [] move_made = False animate = False game_over = False if ai_thinking: move_finder_process.terminate() ai_thinking = False move_undone = True # AI move finder if not game_over and not human_turn and not move_undone: if not ai_thinking: ai_thinking = True return_queue = Queue() # used to pass data between threads move_finder_process = Process(target=ChessAI.findBestMove, args=(game_state, valid_moves, return_queue)) move_finder_process.start() if not move_finder_process.is_alive(): ai_move = return_queue.get() if ai_move is None: ai_move = ChessAI.findRandomMove(valid_moves) game_state.makeMove(ai_move) move_made = True animate = True ai_thinking = False if move_made: if animate: animateMove(game_state.move_log[-1], screen, game_state.board, clock) valid_moves = game_state.getValidMoves() move_made = False animate = False move_undone = False drawGameState(screen, game_state, valid_moves, square_selected) if not game_over: drawMoveLog(screen, game_state, move_log_font) if game_state.checkmate: game_over = True if game_state.white_to_move: drawEndGameText(screen, "Black wins by checkmate") else: drawEndGameText(screen, "White wins by checkmate") elif game_state.stalemate: game_over = True drawEndGameText(screen, "Stalemate") clock.tick(MAX_FPS) p.display.flip()
class Game: def __init__(self,game_mode): """Initializes the game in the desired game_mode""" self.moved_pieces = pygame.sprite.LayeredDirty() self.taken_pieces = pygame.sprite.LayeredDirty() self.white_pieces = pygame.sprite.LayeredDirty() self.black_pieces = pygame.sprite.LayeredDirty() self.board = Board() self.board.display() self.load_piece_dict('TileSet.png') self.init_pieces() self.chess_engine = ChessEngine() self.dirty_rects = [] self.selected_piece = None self.selected_square = None self.white_to_move = True self.display_fps = False #self.font = pygame.font.Font(None,12) #self.dirty_fps = (0,0,0,0) def toggle_fps(self): self.display_fps = not self.display_fps def load_piece_dict(self,filename): """Load the table of chess pieces""" self.tile_set = pygame.image.load(filename).convert() image_width, image_height = self.tile_set.get_size() self.pieces_list = ['K','Q','N','B','R','P'] self.piece_dict = {} for color,y in [('black',1),('white',3)]: tempdict = {} x = 0 for piece in self.pieces_list: rect = (x*image_width/6,y*image_height/4,image_width/6,image_height/4) image = self.tile_set.subsurface(rect) image = pygame.transform.scale(image,(self.board.width/8,self.board.height/8)) image.set_colorkey((255,0,0)) tempdict[piece] = image x +=1 self.piece_dict[color] = tempdict return def init_pieces(self): #Piece(self.piece_dict['black'][placement[y][x]],x*self.board.width/8,y*self.board.height/8) """Places all of the pieces in an array""" backRank = ['R','N','B','Q','K','B','N','R'] pawns = ['P','P','P','P','P','P','P','P'] placement = [backRank,pawns] self.all_pieces = pygame.sprite.LayeredDirty() y = 0 for row in placement: x = 0 for key in row: piece = Piece(self.piece_dict['black'][key],x*self.board.width/8,y*self.board.height/8,key,'black') self.black_pieces.add(piece) self.all_pieces.add(piece) x+=1 y+=1 placement.reverse() y = 6 for row in placement: x = 0 for key in row: piece = Piece(self.piece_dict['white'][key],x*self.board.width/8,y*self.board.height/8,key,'white') self.white_pieces.add(piece) self.all_pieces.add(piece) x+=1 y+=1 self.all_pieces.draw(self.board.screen) self.board.display() def update(self,clock): """Updates the gamestate""" self.all_pieces.clear(self.board.screen,self.board.background) self.dirty_rects = self.all_pieces.draw(self.board.screen) if self.display_fps: print clock.get_fps() # fps = clock.get_fps() # fps_surface = self.font.render(str(fps),1,(255,255,20)) # self.dirty_fps = self.board.screen.blit(fps_surface,(7*self.board.width/8,7*self.board.height/8)) #self.dirty_rects.append(self.dirty_fps) pygame.display.update(self.dirty_rects) def click(self,pos): """Processes in game clicking""" if self.white_to_move: movable_pieces = self.white_pieces else: movable_pieces = self.black_pieces if self.selected_piece is not None: for row in self.board.squares: for rect in row: if rect.collidepoint(pos): self.selected_square = rect break for sprite in movable_pieces: if sprite.rect.collidepoint(pos): if sprite is not self.selected_piece: self.selected_piece = sprite break if self.selected_piece is not None and self.selected_square is not None: if self.selected_piece.rect != self.selected_square: print self.selected_piece.rect,self.selected_square,'\n' if self.get_test_move(): self.move_piece() self.white_to_move = not self.white_to_move print 'moved' else: pass self.selected_piece = None self.selected_square = None def take_piece(self): """Removes pieces that have been taken""" if self.selected_piece in self.white_pieces: taken = pygame.sprite.spritecollide(self.selected_piece,self.black_pieces,True) else: taken = pygame.sprite.spritecollide(self.selected_piece,self.white_pieces,True) if len(taken) !=0: self.taken_pieces.add(taken[0]) return def move_piece(self): """Moves the piece and updates the pieces moveSet if necessary""" self.selected_piece.dirty = 1 self.selected_piece.update_move() self.selected_piece.rect = self.selected_square self.take_piece() def get_test_move(self): w = self.board.width/8 h = self.board.height/8 movement_x = (self.selected_square.x - self.selected_piece.rect.x)/w movement_y = (self.selected_square.y - self.selected_piece.rect.y)/h start_x = self.selected_piece.rect.x/w start_y = self.selected_piece.rect.y/h return self.chess_engine.test_move(self.selected_piece,(movement_x,movement_y),self.white_pieces,self.black_pieces,self.all_pieces) def remove_piece(self,sprite): """Removes a piece from the board, and marks that rect to be updated""" sprite.dirty = 1 sprite.kill() self.taken_pieces.add(sprite)