def main() -> None: """Play multiple rounds of a TIC-TAC-TOE based on user input settings. """ print("=== TIC-TAC-TOE ===\n\n") p1 = make_player('player 1', 'X') p2 = make_player('player 2', 'O') if (isinstance(p1, ComputerPlayer) and isinstance(p2, ComputerPlayer)) or \ (isinstance(p1, CyborgPlayer) and isinstance(p2, CyborgPlayer)): p1.name = p1.name + ' 1' p2.name = p2.name + ' 2' while True: game = TicTacToe((p1, p2)) winner = game.play() if winner is None: print('Game tied!') else: print(f'And the winner is {winner.name}!!! \n') winner.wins += 1 again = input( f'{p1.name} and {p2.name}, would you like to play again? ' f'(y/n)') print('') if again != 'y' and again != 'Y': print(f'{p1.name} won {p1.wins} times!') print(f'{p2.name} won {p2.wins} times!') print('GAME OVER!') return None
def testCurrentPlayerIsX(self): game = TicTacToe() if game.currentPlayer() == 'X': result = True else: result = False self.assertEqual(result, True)
def testAddPlayer(self): game = TicTacToe() game.add_player("playerx") game.add_player("playery") self.assertTrue("playerx" in game.players) self.assertTrue("playery" in game.players)
def test_learn_single(self): self.learner = Learner('X') self.other_player = Player('O') self.tictactoe = TicTacToe() fields = [(0, 0), (0, 1), (0, 2)] for field in fields: self.tictactoe.play(*field, self.learner) self.assertEqual(fields, self.tictactoe.is_winner(self.learner)) self.learner.learn(self.tictactoe, 100, self.learner) print(self.learner.rewards) self.tictactoe = TicTacToe() while (self.tictactoe.available_moves() and not self.tictactoe.is_winner(self.learner) and not self.tictactoe.is_winner(self.other_player)): self.tictactoe.play(*self.learner.next_move(self.tictactoe), self.learner) print(self.tictactoe.board) self.assertFalse(self.tictactoe.is_winner(self.other_player)) self.assertEqual(fields, self.tictactoe.is_winner(self.learner))
def __init__(self, host, port, hostLetter, goesFirst): print("Server started") self.host = host self.port = port self.hostLetter = hostLetter self.goesFirst = goesFirst self.finishedServing = False # Store player client info self.clientList = [] # Create instance of TTT game self.game = TicTacToe() # Create socket instance - Creates default TCP self.s = socket.socket() # Timeout every 0 seconds to listen for key exception and create non blocking socket # self.s.settimeout(0) # self.s.setblocking(0) # Bind host/port to socket self.s.bind((host, port)) # Start server listening for connections self.s.listen(2) # Start getting connection self.startServer()
def test_games(games): for i in range(games): game = TicTacToe(p1, p2) game.play_game() for thing in test_games_results: test_games_results[thing] += game.score[thing] print('The results of ' + str(games) + ' games played was ' + str(test_games_results))
def test_learn_single_starting(self): self.learner = Learner() self.other_player = Player() self.tictactoe = TicTacToe() fields = [(0, 0), (0, 1), (0, 2)] other_fields = [(1, 0), (1, 1)] for field in range(len(fields)): self.tictactoe.play(*fields[field], self.learner) try: self.tictactoe.play(*other_fields[field], self.other_player) except (IndexError): pass self.learner.look(self.tictactoe) self.assertEqual(fields, self.tictactoe.is_winner(self.learner)) self.learner.learn(self.tictactoe, 100, self.learner) print(self.learner.rewards) self.tictactoe = TicTacToe() while (self.tictactoe.available_moves() and not self.tictactoe.is_winner(self.learner) and not self.tictactoe.is_winner(self.other_player)): self.tictactoe.play(*self.learner.next_move(self.tictactoe), self.learner) if (other_fields): self.tictactoe.play(*other_fields.pop(0), self.other_player) print(self.tictactoe.board) self.assertFalse(self.tictactoe.is_winner(self.other_player)) self.assertEqual(fields, self.tictactoe.is_winner(self.learner))
def test_set_reward(self): reward = 100 self.learner = Learner() tictactoe = TicTacToe() action = tictactoe.available_moves()[0] self.learner.set_reward(reward, action, tictactoe.board) self.assertEqual(reward, self.learner.get_reward(action, tictactoe.board))
def restart(self): """ Handles game restart and reconstruction. """ self.game = TicTacToe() self.win_lose_label.destroy() self.canvas.destroy() self.draw_board()
def test_look_other_player(self): self.learner = Learner() self.other_player = RandomPlayer() tictactoe = TicTacToe() action = tictactoe.available_moves()[0] tictactoe.play(action[0], action[1], self.other_player) self.learner.look(tictactoe) self.assertEqual(1, len(self.learner.history[self.other_player.name])) self.assertEqual(action, self.learner.history[self.other_player.name][0])
def test_restart(): game = TicTacToe() game.place_marker(0, 0) game.place_marker(0, 2) game.place_marker(0, 1) game.place_marker(1, 1) game.place_marker(1, 0) game.place_marker(2, 0) game.restart() assert game.board == [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
class GameManager_GUI: def __init__(self): self.ttt = TicTacToe() CAMVAS_SIZE = 300 self.TILE_SIZE = CAMVAS_SIZE / 3 self.root = tkinter.Tk() self.root.title("틱 택 토") self.root.geometry(str(CAMVAS_SIZE) + "x" + str(CAMVAS_SIZE)) # geometry("300 x 300") self.root.resizable(width=False, height=False) self.canvas = tkinter.Canvas(self.root, bg="white", width=CAMVAS_SIZE, height=CAMVAS_SIZE) self.canvas.pack() self.images = dict() self.images["O"] = tkinter.PhotoImage(file="Image/O.gif") self.images["X"] = tkinter.PhotoImage(file="Image/O.gif") self.canvas.bind("<Button-1>", self.click_handler) def click_handler(self, event): row = math.floor(event.y / self.TILE_SIZE) col = math.floor(event.x / self.TILE_SIZE) self.ttt.set(row, col) self.draw_board() def draw_board(self): self.canvas.delete("all") x = 0 y = 0 for i, v in enumerate(self.ttt.board): if v == ".": pass elif v == "O": self.canvas.create_image(x, y, anchor="nw", image=self.images["O"]) elif v == "X": self.canvas.create_image(x, y, anchor="nw", image=self.images["X"]) x += self.TILE_SIZE if i % 3 == 2: x = 0 y += self.TILE_SIZE def play(self): self.root.mainloop()
def play_game(player_token): agent = Agent(switch_token(player_token)) game = TicTacToe([' '] * 9) while not game.over(): play_turn(agent, game) print(game) if game.won(): winner = game.winner() print(f"Better luck next time! {winner} wins!\n") else: print("Game ends in a draw!\n")
class Client: def __init__(self, host, port): # Server host/port self.host = host self.port = port # Client game instance self.clientGame = TicTacToe() # Initialize socket object self.sock = socket.socket() # Connect to game server self.sock.connect((self.host, self.port)) # Start getting connection self.startClient() def startClient(self): print("Connected to game server") sendThread = threading.Thread(target=self.sendMessage) sendThread.daemon = True sendThread.start() while True: data = self.sock.recv(1024) data = pickle.loads(data) self.clientGame.setGameState(data) self.clientGame.renderAll() # for stuff in data: # print(stuff) # print("Recieved from server: " + str(data)) # Set game data and render game # self.clientGame.setGameState(data) # self.clientGame.renderAll() print("->", end="") message = input() # print("message") print(message) # message = pickle.dumps(message) # maybe send all self.sock.send(message.encode("utf-8")) def sendMessage(self): while True: print("->", end="") msg = input() self.sock.send(msg.encode("utf-8"))
def run(self): while (True): self.View = MenuView(3, self.players) buttons1, buttons2, PlayButton, GRID3, GRID10 = self.View.draw_Menu( self.players) flag = 0 p1 = None p2 = None p3 = None while (flag == 0): for event in pygame.event.get(): if (event.type == pygame.QUIT): sys.exit() if (event.type == pygame.MOUSEBUTTONDOWN): if (p1 != None and p2 != None and p3 != None): if (PlayButton.isClicked(event) == 1): flag = 1 p3 = 2 if (GRID3.isClicked(event) == 1 and p3 != 2): GRID3.Toggle() GRID10.UnToggle() GRID_SIZE = 3 p3 = 1 if (GRID10.isClicked(event) == 1 and p3 != 2): GRID10.Toggle() GRID3.UnToggle() GRID_SIZE = 10 p3 = 1 for i, b in enumerate(buttons1): if (b.isClicked(event) > 0): p1 = deepcopy(self.players[i]) for bb in buttons1: bb.UnToggle() b.Toggle() for i, b in enumerate(buttons2): if (b.isClicked(event) > 0): p2 = deepcopy(self.players[i]) for bb in buttons2: bb.UnToggle() b.Toggle() print("!!!") # TicTacToe(needToWin, GRID_SIZE,player1,player2) A_TicTacToe = TicTacToe(needToWinDict[GRID_SIZE], GRID_SIZE, p1, p2, False) A_TicTacToe.run() pygame.time.wait(30000)
def test_game3(self): game = TicTacToe() game.put_choice(2, 1) game.put_choice(2, 4) game.put_choice(1, 10) game.put_choice(1, 3) game.put_choice(2, 7) self.assertEqual(game.status_of_the_match(), 2)
def __init__(self): game_number = self.chosen_game_mode(self.args_parser()) if game_number == 1: print("Welcome to The TicTacToe game.") ttt = TicTacToe("Tic Tac Toe Game", "190x210", self.board_size_tic_tac_toe_game) ttt.run_game() elif game_number == 2: print("Welcome to The Checkers game.") print("In the building process.")
def test_game1(self): game = TicTacToe() game.put_choice(1, 1) game.put_choice(2, 2) game.put_choice(1, 5) game.put_choice(2, 7) game.put_choice(1, 9) game.put_choice(2, 4) self.assertEqual(game.status_of_the_match(), 1)
def test_second_case(self): game = TicTacToe() game.playX(0, 0) game.playO(1, 1) game.playX(2, 2) board_as_x = game.board_for_learning() expected_as_x = numpy.array( [1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0]) self.assertTrue((board_as_x == expected_as_x).all()) board_as_o = game.board_for_learning_as_O() expected_as_o = numpy.array( [2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0]) self.assertTrue((board_as_o == expected_as_o).all())
def train(games): # Set timer startTime = clock() # Train computer for i in range(1, games + 1): if i % 1000 == 0: print(i) game = TicTacToe(p1, p2) game.play_game() deltaTime = clock() - startTime m, s = divmod(deltaTime, 60) print("It took " + str(int(m)) + " minutes and " + str(s) + " seconds to play " + str(games) + " games")
def Main(): humanChoice = '' aiChoice = '' turn = '' while 1 : humanChoice = input('Select symbol X or O: ').lower() if humanChoice == 'x': aiChoice = 'o' break elif humanChoice == 'o': aiChoice = 'x' break print('') print('wrong choice') print('') while 1: turn = input('Would you like to play first (y/n): ').lower() if turn == 'y': turn = 'human' break elif turn == 'n': turn = 'ai' break print('') print('wrong choice') print('') game = TicTacToe(humanChoice,aiChoice) while not game.CheckFinalState() and len(game.GetEmptyCells()) > 0: if turn == 'human': game.HumanTime() turn = 'ai' else: game.AiTime() turn = 'human' game.Clear() game.Render() if game.Winner(-1): print('The human wins') elif game.Winner(1): print('The AI wins') else: print('tie')
def test_cross_win(): game = TicTacToe() game.place_marker(0, 0) game.place_marker(0, 1) game.place_marker(1, 1) game.place_marker(0, 2) game.place_marker(2, 2) assert game.state == STATES.CROSS_WON
def main(): game = TicTacToe() currentInput = ' ' if random.randint(0, 1) == 0: game.nextAIMove() game.printField() while (currentInput != 'q' and game.gameIsRunning): currentInput = input() game.performMoves(currentInput) game.printField() print()
def test_2_random_players_cl(self): player1 = RandomPlayer('R1') player2 = RandomPlayer('R2') game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_learner_random_players(self): player1 = Learner() player2 = RandomPlayer() game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def __init__(self): self.mainGrid = [[TicTacToe() for j in range(3)] for i in range(3)] self.currentBoard = [1, 1] self.hasWon = False self.wonBy = ' ' self.currentPlayer = 'X' self.verbose = 1
def test_random_human_players_cl(self): player1 = RandomPlayer() player2 = HumanPlayer() game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_2_human_players_cl(self): player1 = HumanPlayer('H1') player2 = HumanPlayer('H2') game = TicTacToe() gui = CommandlineGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def test_human_learner_players(self): player1 = HumanPlayer() player2 = Learner() game = TicTacToe() gui = KtinterGui(game) match = Match(gui, game, players=[player1, player2]) match.play()
def __init__(self, host, port): # Server host/port self.host = host self.port = port # Client game instance self.clientGame = TicTacToe() # Initialize socket object self.sock = socket.socket() # Connect to game server self.sock.connect((self.host, self.port)) # Start getting connection self.startClient()
# Define the size of the board board_rows = 3 board_cols = 3 # Define win condition (# of symbols in a row) k_to_win = 3 # Define how many games to play n_games = 100000 # Define how many hidden layer nodes for the NN to have num_nodes = 100 boardlist_size = board_rows*board_cols game = TicTacToe(board_rows, board_cols, k_to_win) Bot1 = {'win':0, 'lose':0, 'tie':0} Bot2 = {'win':0, 'lose':0, 'tie':0} for game_num in range(0,n_games): print("Playing game " + repr(game_num) + "...") playerturn = random.randint(0,1) turn = 0 while not game.won: boardlist = game.boardlist if turn%2 == playerturn:
def setUp(self): self.ttt = TicTacToe()
from TicTacToe import TicTacToe tb = TicTacToe() tb.simulateGame()
class test_TicTacToe(unittest.TestCase): def setUp(self): self.ttt = TicTacToe() def test_reset(self): board = ["."] * 9 squares = [[],[]] free_squares = [x for x in range(9)] game_over = False turns = 0 self.ttt.reset_board() self.assertEqual(self.ttt.board, board) self.assertEqual(self.ttt.squares, squares) self.assertEqual(self.ttt.free_squares, free_squares) self.assertEqual(self.ttt.game_over, game_over) self.assertEqual(self.ttt.turns, turns) def test_move_possible(self): self.assertTrue(self.ttt.move_possible(3)) self.ttt.make_move(self.ttt.COMPUTER, 3) self.assertFalse(self.ttt.move_possible(3)) def test_make_move(self): self.ttt.make_move(self.ttt.COMPUTER, 0) self.ttt.make_move(self.ttt.HUMAN, 4) board = ["."] * 9 board[0] = "x" board[4] = "o" self.assertEqual(self.ttt.board, board) human = [4] computer = [0] self.assertEqual(human, self.ttt.squares[self.ttt.HUMAN]) self.assertEqual(computer, self.ttt.squares[self.ttt.COMPUTER]) free_squares = [x for x in range(9)] free_squares.remove(0) free_squares.remove(4) self.assertEqual(free_squares, self.ttt.free_squares) self.assertEqual(2, self.ttt.turns) def test_undo_move(self): self.ttt.make_move(self.ttt.COMPUTER, 0) self.ttt.make_move(self.ttt.HUMAN, 8) board = ["."] * 9 board[0] = "x" self.assertTrue(self.ttt.undo_move(self.ttt.HUMAN, 8)) self.assertEqual(board, self.ttt.board) self.assertEqual([], self.ttt.squares[self.ttt.HUMAN]) self.assertFalse(self.ttt.undo_move(self.ttt.HUMAN, 0)) free_squares = [x for x in range(1, 9)] self.assertEqual(set(self.ttt.free_squares), set(free_squares)) self.assertEqual(self.ttt.turns, 1) def test_check_game_over(self): #test computer victory self.ttt.squares = [[0,1,2],[]] self.assertEqual(self.ttt.check_game_over(), (True, 1)) #test human victory self.ttt.squares = [[],[2,5,8]] self.assertEqual(self.ttt.check_game_over(), (True, -1)) #test tie #squares = [[4,1,8,6,5],[0,7,3,2]] self.ttt.reset_board() self.ttt.make_move(self.ttt.COMPUTER,4) self.ttt.make_move(self.ttt.HUMAN,0) self.ttt.make_move(self.ttt.COMPUTER,1) self.ttt.make_move(self.ttt.HUMAN,7) self.ttt.make_move(self.ttt.COMPUTER,8) self.ttt.make_move(self.ttt.HUMAN,3) self.ttt.make_move(self.ttt.COMPUTER,6) self.ttt.make_move(self.ttt.HUMAN,2) self.ttt.make_move(self.ttt.COMPUTER,5) self.assertEqual(self.ttt.check_game_over(), (True, 0)) #test no winner, no tie self.ttt.undo_move(self.ttt.COMPUTER, 5) self.assertEqual(self.ttt.check_game_over(), (False, None)) def test_do_computer_turn(self): self.ttt.do_computer_turn() self.assertEqual(self.ttt.squares[self.ttt.COMPUTER], [4]) self.ttt.do_computer_turn() self.assertEqual(len(self.ttt.squares[self.ttt.COMPUTER]), 2) self.assertEqual(self.ttt.board_control, self.ttt.HUMAN) self.assertEqual(self.ttt.turns, 2) def test_find_good_move(self): #check that all initial moves are neutral (expected to tie) score, pos = self.ttt.find_good_move(self.ttt.COMPUTER) self.assertEqual(score, 0) for i in range(9): self.ttt.make_move(self.ttt.HUMAN, i) score, pos = self.ttt.find_good_move(self.ttt.COMPUTER) self.ttt.undo_move(self.ttt.HUMAN, i) self.assertEqual(score, 0) self.ttt.reset_board() #set up a cpu wins situation and make sure cpu finds it self.ttt.make_move(self.ttt.COMPUTER, 0) self.ttt.make_move(self.ttt.HUMAN, 3) self.ttt.make_move(self.ttt.COMPUTER, 1) self.ttt.make_move(self.ttt.HUMAN, 4) score, pos = self.ttt.find_good_move(self.ttt.COMPUTER) self.assertEqual(score, 1) #set up a human wins situation and make sure human finds it self.ttt.make_move(self.ttt.COMPUTER, 8) score, pos = self.ttt.find_good_move(self.ttt.HUMAN) self.assertEqual(score, -1) #play a game, both players make best moves. ensure a tie self.ttt.reset_board() while not self.ttt.game_over: if self.ttt.board_control == self.ttt.COMPUTER: self.ttt.do_computer_turn() else: score, pos = self.ttt.find_good_move(self.ttt.HUMAN) self.ttt.make_move(self.ttt.HUMAN, pos) self.ttt.board_control = self.ttt.COMPUTER self.ttt.game_over, winner = self.ttt.check_game_over() if self.ttt.game_over: self.assertEqual(winner, 0)
for arg in sys.argv: args.append(arg) if len(args) != 6: print("Must have exactly 5 commandline arguments: <board rows> <board columns> <k-in-a-row to win> <Monte Carlo bot passes> <# games>") sys.exit() else: board_rows = int(args[1]) board_cols = int(args[2]) k_to_win = int(args[3]) bot_passes = int(args[4]) n_games = int(args[5]) boardlist_size = board_rows*board_cols game = TicTacToe(board_rows, board_cols, k_to_win) clf = MCbot(bot_passes) MCmemory = {} Bot1 = {'win':0, 'lose':0, 'tie':0} Bot2 = {'win':0, 'lose':0, 'tie':0} train_X_large = [] train_Y_large = [] for game_num in range(0,n_games): playerA_X = [] # X symbol playerB_X = [] # @ symbol playerA_Y = [] # X symbol playerB_Y = [] # @ symbol
def testGame(self): #setup game = TicTacToe() game.add_player("playerx") game.add_player("playery") game.begin() self.assertTrue(game.validate("playerx", {"x" : 0, "y" : 0})) game.execute("playerx", {"x" : 0, "y" : 0}) self.assertTrue(game.validate("playery", {"x" : 1, "y" : 0})) game.execute("playery", {"x" : 1, "y" : 0}) self.assertTrue(game.validate("playerx", {"x" : 2, "y" : 0})) game.execute("playerx", {"x" : 2, "y" : 0}) self.assertTrue(game.validate("playery", {"x" : 0, "y" : 1})) game.execute("playery", {"x" : 0, "y" : 1}) self.assertTrue(game.validate("playerx", {"x" : 1, "y" : 1})) game.execute("playerx", {"x" : 1, "y" : 1}) self.assertTrue(game.validate("playery", {"x" : 1, "y" : 2})) game.execute("playery", {"x" : 1, "y" : 2}) self.assertTrue(game.validate("playerx", {"x" : 2, "y" : 1})) game.execute("playerx", {"x" : 2, "y" : 1}) self.assertTrue(game.validate("playery", {"x" : 2, "y" : 2})) game.execute("playery", {"x" : 2, "y" : 2})
def __init__(self, h=7, v=6, k=4): TicTacToe.__init__(self, h, v, k)
args.append(arg) if len(args) != 5: print("Must have exactly 4 commandline arguments: <board rows> <board columns> <k-in-a-row to win> <Monte Carlo bot passes>") sys.exit() else: board_rows = int(args[1]) board_cols = int(args[2]) k_to_win = int(args[3]) bot_passes = int(args[4]) boardlist_size = board_rows*board_cols clf = MCbot(bot_passes) game = TicTacToe(board_rows, board_cols, k_to_win) playerturn = 0 while True: print("") print("Starting new game!") turn = 0 game.printboard() while not game.won: if turn%2 == playerturn: print("Player taking turn...") val = int(raw_input("Please select a cell number: "))