def turn(): if request.method == 'POST': game_state = request.get_json() (board, player, move, message, err) = unpack(game_state) if err: # TODO: # Come up with error scheme and handle those # errors in a nice way. return 'Some error was thrown' # Reset the message. message = None # Check if desired space is occupied if not ttt.is_space_free(board, move): message = 'Invalid move!' game_state = pack(board=board, player=player, move=move, message=message, err=err) return jsonify(game_state) ttt.make_move(board, player, move) # Check to see if that move won. if ttt.is_winner(board, player): message = 'Player ' + str(player) + ' wins!' game_state = pack(board=board, player=player, move=move, message=message, err=err) return jsonify(game_state) # Check to see if that move completed the board. if ttt.is_board_full(board): message = 'Game over' game_state = pack(board=board, player=player, move=move, message=message, err=err) return jsonify(game_state) # If not, game goes on. Alternate the current player. if player == 'X': player = 'O' else: player = 'X' game_state = pack(board=board, player=player, move=move, message=message, err=err) return jsonify(game_state) elif request.method == 'GET': # Return sample state for easy API usage! (maybe?) message = 'This is an example game state. Write things like "Invalid move" or "Game Over!" here.' err = 'Leave this NULL when no errors occur.' game_state = new_game_state(message=message, error_message=err) return jsonify(game_state)
def move(sid, game_code, move_data, emblem): # Load the game state (payload) from redis. r = Redis(host=REDIS) game_state_json = r.get(game_code).decode("utf-8") game_state = json.loads(game_state_json) # Check to see who's turn it's supposed to be if game_state["move_count"] % 2 == 0: turn = game_state["player1"] else: turn = game_state["player2"] # if the initiating sid isn't the same as the turn sid, then raise an exception if turn != sid: raise Exception(turn, sid, "It's not your turn!") # Create new game state based on user input. moved_state = make_move(game_state=game_state, x=move_data["x"], y=move_data["y"], emblem=emblem) moved_json = json.dumps(moved_state) # Persist new game state to redis. r.set(game_state["game_code"], moved_json) # Emit SocketIO event for updated game_state. sio.emit("game_state_change", moved_json, room=game_code) # If an end-game condition is found... if game_state["win_state"] is True: # A player won the game. winner = "X" if game_state["move_count"] % 2 == 0 else "O" sio.emit("win_state", winner, room=game_code) elif game_state["win_state"] is "Draw": # The game is a draw. sio.emit("draw", room=game_code)
def get(self): board = utils.string_to_list(self.request.get('board')) next_move = -1 # check if they sent you a full board, this will happen if the player went first. if tictactoe.is_full_board(board): # if they did, just check the game state. game_state, message = tictactoe.get_game_state(board) else: try: next_move = tictactoe.get_move(board, config.COMPUTER) new_board = tictactoe.make_move(board, next_move, config.COMPUTER) game_state, message = tictactoe.get_game_state(new_board) except Exception as e: game_state, message = config.ERROR, e.message result = {'move': next_move, 'game_state': game_state, 'message': message} self.render_json(result)
def GamePage(playerChoice): '''Initialize the game interface''' # Initialize (yet another!) pygame window windowSurface = WindowSetup() # Define a windowgap and spacing constants to make the board interface # look neat GAP = 40 SPACING = 140 CENTER = GAP + SPACING / 2 # Draw 2 horizontal lines pygame.draw.line(windowSurface, BLACK, [GAP, GAP + SPACING], [500 - GAP, GAP + SPACING], 5) pygame.draw.line(windowSurface, BLACK, [GAP, GAP + SPACING * 2], [500 - GAP, GAP + SPACING * 2], 5) # Draw 2 vertical lines pygame.draw.line(windowSurface, BLACK, [GAP + SPACING, GAP], [GAP + SPACING, 500 - GAP], 5) pygame.draw.line(windowSurface, BLACK, [GAP + SPACING * 2, GAP], [GAP + SPACING * 2, 500 - GAP], 5) pygame.display.update() # Initialize class Player, based on selection screen choice if playerChoice == 'X': human = tic.Player('X',0) computer = tic.Player('O',1) else: computer = tic.Player('X',0) human = tic.Player('O',1) # Pre-define landing squares for MOUSEBUTTONUP corners = [] rowCorners = [] for row in range(1,4): for square in [i * SPACING for i in range(3)]: corners.append(rowCorners.append(((GAP + square, GAP + SPACING * (row - 1)),(GAP + square + SPACING, GAP + SPACING * row)))) # Pre-define landing squares for XO images imageCoord = [] for row in range(3): for square in range(3): imageCoord.append((CENTER + square * SPACING, CENTER + SPACING * row)) # Create a dict where key=imageCoords, value=rect object imageRender = {} for coords in imageCoord: placeholder = pygame.Rect(0, 0, 65, 65) placeholder.centerx = coords[0] placeholder.centery = coords[1] imageRender[coords] = placeholder # Create a dict for key = mouse input and value = board coord boardmap = {} for a,b in zip(rowCorners,tic.keys): dictBuffer = {a: b} boardmap.update(dictBuffer) # Also create a dict for key=board coord, value=imageCoord imageMapping = {} for a,b in zip(tic.keys,imageCoord): dictBuffer = {a: b} imageMapping.update(dictBuffer) # Time to start event loop while True: for event in pygame.event.get(): # Exit if user closes the program if event.type == QUIT: pygame.quit() sys.exit() # initialize board move variable move = False # if Computer's turn if computer.myTurn(tic.board) == True: time.sleep(1) move = tic.make_move(computer,human) # else listen for mouse input elif event.type == MOUSEBUTTONUP: mouse_pos = pygame.mouse.get_pos() for k, v in boardmap.items(): if mouse_pos[0] > k[0][0] and mouse_pos[0] < k[1][0] and mouse_pos[1] > k[0][1] and mouse_pos[1] < k[1][1]: if human.place(v,tic.board): move = v # take action when a move is inputed if move: for k,v in imageMapping.items(): if move == k: if not computer.myTurn(tic.board): if computer.get_piece() == 'X': windowSurface.blit(xImage,imageRender[v]) else: windowSurface.blit(oImage,imageRender[v]) else: if human.get_piece() == 'X': windowSurface.blit(xImage,imageRender[v]) else: windowSurface.blit(oImage,imageRender[v]) pygame.display.update() # Check if any exit board conditions has occured if computer.win(tic.board): time.sleep(2) pygame.display.quit() return 0 elif human.win(tic.board): time.sleep(2) pygame.display.quit() return 1 elif tic.legalmoves(tic.board) == []: time.sleep(2) pygame.display.quit() return 2
move = gamePlay.HumanPlayer(Board, History, Players) # Player One #drop piece to column else: print("Player 2 turn") #print ("move", move) #connect4.print_board(Board) if Mode == "C": move = gamePlay.ComputerPlayer(Board, History, Players ) elif Mode == "P": move = gamePlay.HumanPlayer(Board, History, Players) # Player Two #1print ("Piece", Players[turn % 2]) '''check if the move is valid and add to the history''' if tictactoe.make_move(Board, move, Players[turn % 2]): # print ("drop piece") Tries = 0 History.append(move) '''if players makes more than 3 invalid moves, the game is stuck''' if Tries > 3: print ('Player {} is stuck!'.format((turn % 2) + 1)) break '''prints the updated board''' tictactoe.print_board(Board) print() print()
def test_make_move_valid(self): my_board = new_board() for i in range(9): self.assertTrue(tictactoe.make_move(my_board, i, config.COMPUTER)) self.assertTrue(tictactoe.make_move(my_board, i, config.HUMAN))