def initgame(): global ttt if not ttt: ttt = TicTacToe() else: ttt.reset()
def draw(screen): draw = True start = True one_player = False two_player = False start_selector_num = 0 board_selector = [0, 0] cursor = [10, 32] p1_game = TicTacToe.TicTacToe() p2_game = TicTacToe.TicTacToe() draw_controller = Draw_Controller(draw, start, one_player, two_player, start_selector_num, board_selector, cursor, p1_game, p2_game) while draw_controller.draw: draw_controller.selector = screen.getch() screen.clear() #environment switcher environment_switch(draw_controller, screen) #this is for the different environment controls environment_controller(draw_controller, screen) #this is the options control printer option_switch(draw_controller, screen) #this is the board player turn controller screen.refresh()
def testState(self): # First "real life" example g = TicTacToe.Game() self.assertEqual(g.status, -1) g.play((0,0)); g.play((0,1)) self.assertEqual(g.status, -1) g.play((1,1)); g.play((1,0)) self.assertEqual(g.status, -1) g.play((2,2)); self.assertEqual(g.status, 1) with self.assertRaises(RuntimeError) as cm: g.play((2,1)) # Some more "to the point" tests g = TicTacToe.Game() g._board[0, 0:3] = 1 self.assertEqual(g._compute_status(), 1) self.assertEqual(g.status, 1) g = TicTacToe.Game() g._board[0:3, 2] = 1 self.assertEqual(g._compute_status(), 1) self.assertEqual(g.status, 1) g = TicTacToe.Game() g._board[2, 0] = 2 self.assertEqual(g._compute_status(), -1) self.assertEqual(g.status, -1) g._board[1, 1] = 2 self.assertEqual(g._compute_status(), -1) self.assertEqual(g.status, -1) g._board[0, 2] = 2 self.assertEqual(g._compute_status(), 2) self.assertEqual(g.status, 2)
def play(self): print("Setting up game...\n") alpha = -1 beta = 1 self.game = TicTacToe() self.player2 = AdversarialSearch(self.game.copy(), "O", self.depth) window = Tk() window.rowconfigure((0, 3), weight=1) window.columnconfigure((0, 2), weight=1) for i in range(0, 3): for j in range(0, 3): print(str(i)) b = Button(window, text="", pady=2, width=5, height=5, command=lambda a=i, b=j, : self.takeTurn(a, b)) b.grid(row=i, column=j) print(self.buttons) self.buttons[i][j] = b buttonR = Button(window, text="RESET", width=15, height=5, command=self.reset) buttonR.grid(row=3, column=0, columnspan=3) window.mainloop()
def test_func_1(self): computer_choice = "X" human_choice = "0" board_config = np.array([[1, 1, 0], [-1, 1, 1], [-1, 0, 0]]) print("Running test for win conditions in the board configuration:") #Win condition is determined is three move of same kind are in a row, colum or diagonal testObject = TicTacToe.TicTacToe(board=board_config) testObject.printGrid(computer_choice, human_choice) self.assertFalse(testObject.isWinner(user=-1)) print("Test Output: ", testObject.isWinner(user=-1)) #Row winning condition board_config = np.array([[1, -1, 1], [-1, -1, -1], [0, -1, 0]]) testObject = TicTacToe.TicTacToe(board=board_config) testObject.printGrid(computer_choice, human_choice) self.assertTrue(testObject.isWinner(user=-1)) print("Test Output: ", testObject.isWinner(user=-1)) #Column winning condition board_config = np.array([[1, -1, 0], [1, -1, 0], [1, 1, 0]]) testObject = TicTacToe.TicTacToe(board=board_config) testObject.printGrid(computer_choice, human_choice) self.assertTrue(testObject.isWinner(user=1)) print("Test Output: ", testObject.isWinner(user=1)) #Diagonal winning condition board_config = np.array([[-1, 0, 1], [-1, -1, 0], [0, -1, -1]]) testObject = TicTacToe.TicTacToe(board=board_config) testObject.printGrid(computer_choice, human_choice) self.assertTrue(testObject.isWinner(user=-1)) print("Test Output: ", testObject.isWinner(user=-1))
def reset(self): self.game = TicTacToe() alpha = -1 beta = 1 self.player2 = AdversarialSearch(self.game.copy(),"O", self.depth) for i in range(0,3): for j in range(0,3): self.buttons[i][j]["text"] = ""
def test_check_status5(self): game = TicTacToe() game.puzzle = [["X", "O", "O"], [" ", "O", " "], [" ", "O", " "]] self.assertTrue(game.check_status())
def test_check_status3(self): game = TicTacToe() game.puzzle = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] self.assertFalse(game.check_status())
def test_check_status2(self): game = TicTacToe() game.puzzle = [["O", "X", "O"], ["X", "X", "O"], ["O", "O", "X"]] self.assertFalse(game.check_status())
def initgame(): global ttt if not ttt: ttt = TicTacToe() ttt.playerTurn = 1 # Setting this manually. else: ttt.reset()
def test_is_good_input(self): self.assertFalse(TicTacToe.is_good_input(0, 2, self.table)) self.assertFalse(TicTacToe.is_good_input(1, 4, self.table)) self.table[0][1] = 'x' self.assertFalse(TicTacToe.is_good_input(0, 1, self.table)) self.assertTrue(TicTacToe.is_good_input(1, 1, self.table))
def gameType(): accepted = False while not accepted: gtype = input("Capitals (1) or custom words (2) or Tic Tac Toe (3)? ") if gtype == "1": accepted = True elif gtype == "2": accepted = True elif gtype == "3": TicTacToe.main() else: print("Try again!") return int(gtype)
def find_optimal_play(state): # Complete 20000 episodes from given state with agent giving first move environment = TicTacToe(deepcopy(state)) agent = play(environment=environment, policy="Q", random_start=False, episodes=20000) # Set environment back to given state and let learned agent take best move environment = TicTacToe(state) agent.set_environment(environment) agent.set_epsilon(0) # Ensures greedy move move = agent.find_move() # Uncomment to see Q-Values ''' for action in environment.get_available_actions(): state_val = ''.join(state) key = (state_val, action) print("Location:", action, "\tValue:", agent.get_Q()[key]) ''' # Place move and print board environment.place_move(agent.get_icon(), move) environment.print_board()
class TicTacToeTest(unittest.TestCase): """class responsible for testing TicTacToe game""" def setUp(self): self.n = randrange(3, 10) self.TTTgame = TicTacToe(self.n) def test_whether_good_index_is_passed(self): self.assertRaises(BadIndexPassed, self.TTTgame.putOnBoardPlayer1Move, self.n**2 + 1) self.assertRaises(BadIndexPassed, self.TTTgame.putOnBoardPlayer2Move, -1) self.assertRaises(BadIndexPassed, self.TTTgame.putOnBoardPlayer1Move, 2.34) self.assertRaises(BadIndexPassed, self.TTTgame.putOnBoardPlayer1Move, "someString") def test_whether_good_rules_are_set_up_for_1_player_win(self): for i in range(self.n): self.TTTgame.board[i][i] = 'x' self.TTTgame.isEnd() self.assertTrue(self.TTTgame.End) self.TTTgame.board[2][2] = 'o' self.TTTgame.isEnd() self.assertFalse(self.TTTgame.End) def test_wheter_good_rules_are_set_up_for_2_player_win(self): x = randrange(self.n) self.TTTgame.board[x] = ['o' for i in range(self.n)] self.TTTgame.isEnd() self.assertTrue(self.TTTgame.End) self.TTTgame.board[x][1] = 'x' self.TTTgame.isEnd() self.assertFalse(self.TTTgame.End)
def checaVitoriaVertice(self, vertice, maquinaInicia): """Checa se um vértice representa vitória, dependendo do nome do jogo se a maquina iniciou""" qntSimbolos = 0 for caractere in vertice.info: if caractere != '0': qntSimbolos += 1 if qntSimbolos % 2 == 0: qntSimbolos = 'par' else: qntSimbolos = 'impar' if self.nomeJogo == 'Wild': jogo = Wild() elif self.nomeJogo == 'Misere': jogo = Misere() else: jogo = TicTacToe() jogo.tabuleiro.tabuleiro = vertice.info ganhador = jogo.tabuleiroFinalizado() if ganhador: if self.nomeJogo == 'Misere' and maquinaInicia and qntSimbolos == 'par': return 'Vitoria' elif self.nomeJogo == 'Misere' and not maquinaInicia and qntSimbolos == 'impar': return 'Vitoria' elif self.nomeJogo == 'Wild' and maquinaInicia and qntSimbolos == 'impar': return 'Vitoria' elif self.nomeJogo == 'Wild' and not maquinaInicia and qntSimbolos == 'par': return 'Vitoria' elif self.nomeJogo == 'TicTacToe' and maquinaInicia and ganhador == 'X': return 'Vitoria' elif self.nomeJogo == 'TicTacToe' and not maquinaInicia and ganhador == 'O': return 'Vitoria' else: return 'Derrota' else: return 'Empate'
def train(cold=True, name='data.csv', n=10000): """Train the computer and store memory into training data file. If cold, computer starts with no prior training data. If warm, computer starts with whatever memory is in training data""" ttt = TicTacToe.TicTacToe() if cold: print('Stochastic\n') wins1 = ttt.CvC(iterations=int(0.2*n), rand=True) print('Learning\n') wins2 = ttt.CvC(iterations=int(0.8*n), rand=False) ttt.comp.store_dta(name) wins = wins1.append(wins2, ignore_index=True) x = wins.groupby(wins.index//100).sum() plt.plot(x['win']) plt.show() else: print('Loading...') ttt.comp.load_dta(name) wins = ttt.CvC(iterations=n, rand=False) ttt.comp.store_dta(name) x = wins.groupby(wins.index//100).sum() plt.plot(x['win'][:-1]) plt.show()
def playerVsAI(self): self.currentScreen = self.gameScreen self.play = True self.playAI = True self.clicked[12] = False self.buttonClick = [False for _ in range(self.size * self.size)] self.game = TicTacToe(self.size, 2, self.playerIsFirst, 10, False, True, self)
def playerVsPlayer(self): self.currentScreen = self.gameScreen self.play = True self.playAI = False self.clicked[12] = False self.buttonClick = [False for _ in range(self.size * self.size)] self.game = TicTacToe(self.size, self.numOfPlayers, True, 10, False, False, self)
def test_has_board_attr(self): self.test_has_TicTacToe_constructor() b = TicTacToe.TicTacToe() self.assertTrue( hasattr(b, 'board'), msg= 'You should have an attribute named board in the TicTacToe class.')
def test_checkBoard_full_game_o_win_with_bad_inputs(self): TicTac = TicTacToe.TicTacToe() TicTac.nextMove([0, 0]) #x [0,0] TicTac.nextMove([1, 0]) #o [1,0] TicTac.nextMove([1, 0]) # bad input TicTac.nextMove([0, 1]) #x [0,1] TicTac.nextMove([2, 0]) #o [2,0] TicTac.nextMove([1, 1]) #x [1,1] TicTac.nextMove([1, 0]) # bad input TicTac.nextMove([2, 1]) #o [2,1] TicTac.nextMove([1, 2]) #x [1,2] TicTac.nextMove(5) # bad input TicTac.nextMove([5, 0]) # bad input TicTac.nextMove([2, 2]) #o [2,2] self.assertEqual(TicTac.checkBoard('x'), enums.game_state.game_is_not_finished) self.assertNotEqual(TicTac.checkBoard('o'), enums.game_state.x_won) self.assertNotEqual(TicTac.checkBoard('x'), enums.game_state.x_won) self.assertNotEqual(TicTac.checkBoard('x'), enums.game_state.draw) self.assertNotEqual(TicTac.checkBoard('o'), enums.game_state.draw) self.assertNotEqual(TicTac.checkBoard('x'), enums.game_state.game_is_not_finished) self.assertNotEqual(TicTac.checkBoard('o'), enums.game_state.game_is_not_finished) self.assertNotEqual(TicTac.checkBoard('x'), enums.game_state.o_won) self.assertEqual(TicTac.checkBoard('o'), enums.game_state.o_won)
def __init__(self, address, port, data_size): self.data_size = data_size self._createTcpIpSocket() self._bindSocketToThePort(address, port) self.numberGame = NumberGame(0,100) self.tttGame = TicTacToe(0) self.state = [State.NO_GAME]
def __init__(self, s): self.state = S_OFFLINE self.peer = '' self.me = '' self.out_msg = '' self.s = s # set my own private key self.public_base = 0 self.public_clock = 0 self.private_key = random.randint(1, 1000) self.public_key = 0 self.peer_public_key = 0 self.group_public_key = 0 self.group_private_key = 0 self.shared_key = 0 self.offset = 0 # store results of dice rolls for me and peer self.result = '' self.roll_first = '' self.peer_result = '' # store info for TicTacToe game self.go_first = '' self.board = TicTacToe.Board() self.xo = '' self.my_position = '' self.peer_position = ''
def __init__(self, master): #ttt.training() ttt.readValue_n_stepTD() frame = Frame(master) frame.pack() self.button = Button(frame, text="Quit", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Play Tic Tac Toe", command=self.openGame) self.hi_there.pack(side=LEFT)
def test_nextMove_changes_to_board(self): TicTac = TicTacToe.TicTacToe() TicTac.nextMove([0, 0]) TicTac.nextMove([0, 1]) board = [[' ' for x in range(3)] for x in range(3)] board[0][0] = "x" board[0][1] = "o" self.assertEqual(TicTac.getBoard(), board)
def test_nextMove_move_if_off_the_board(self): TicTac = TicTacToe.TicTacToe() self.assertEqual(TicTac.nextMove([50, 50]), enums.error.different_position) self.assertEqual(TicTac.nextMove([-2, 1]), enums.error.different_position) self.assertEqual(TicTac.nextMove([-5, -5]), enums.error.different_position)
def test_get_player_char_no_params(self): self.test_get_player_char_exists() t = TicTacToe.TicTacToe() self.assertTrue( len(signature(t.get_player_char).parameters) == 0, msg= 'get_player_char method in TicTacToe should have only self as a paramter ' )
def test_has_TicTacToe_constructor(self): self.test_has_TicTacToe_class() b = TicTacToe.TicTacToe() self.assertTrue( hasattr(b, '__init__'), msg= 'Could not find constructor ("__init__") method in TicTacToe class' )
def main(): output_string = "\nHello!\nThis is a game of Tic Tac Toe\nPlayer 1 uses \"X\" and Player 2 uses \"O\"\nEnjoy the game!\n\n" for char in output_string: sys.stdout.write(char) sys.stdout.flush() time.sleep(.05) game = TicTacToe() player1_turn = True player_char = "" while not game.check_status(): if player1_turn: print("Player 1") player_char = "X" else: print("Player 2") player_char = "O" player1_turn = not player1_turn game.player_turn(player_char) print("\n\n") game.print_game() print("\n\n") if (player1_turn): print("Player 2 win!!") else: print("Player 1 win!!")
class GameManager: def __init__(self): self.ttt = TicTacToe() def play(self): # 게임판 보여주자 print(self.ttt) # row, col 입력받자 self.ttt.set(1, 1) print(self.ttt) # check_winner 면 끝내자 while True: # row, col 입력받자 row = int(input("row : ")) col = int(input("col : ")) self.ttt.set(row, col) print(self.ttt) # check_winner 면 끝내자 if self.ttt.check_winner() == "O": print("O win!!!") break elif self.ttt.check_winner() == "X": print("X win!!!") break elif self.ttt.check_winner() == "d": print("무승부") break
def test_free_pos_8(self): self.table[1][1] = 'x' returns = [] for index in range(100): returns.append(TicTacToe.free_pos_8(self.table, 8)) self.assertTrue([0, 2] in returns) self.assertTrue([2, 0] in returns) self.assertTrue([2, 2] in returns) self.assertTrue([0, 0] in returns) self.table[1][1] = ' ' self.table[0][2] = 'x' self.assertEqual(TicTacToe.free_pos_8(self.table, 8), [1, 1]) self.assertFalse(TicTacToe.free_pos_8(self.table, 4))
def getMove(request): m=request.GET.get('board') board=[] for i in m: if i=='-': board.append(None) else: board.append(int(i)) move=TicTacToe.getBestPossibleMove(board,0,7) print board,move return HttpResponse(move+1)
def test_check_rows(self): self.table[1][1] = 'x' self.table[0][0] = 'x' self.table[2][0] = 'o' self.assertEqual(TicTacToe.check_rows(self.table, [], 'x'), []) self.table[0][0] = ' ' self.table[1][0] = 'x' self.assertEqual(TicTacToe.check_rows(self.table, [], 'x'), [[1, 2]]) self.table[1][0] = ' ' self.table[1][2] = 'x' self.assertEqual(TicTacToe.check_rows(self.table, [], 'x'), [[1, 0]]) self.table[1][1] = ' ' self.table[1][0] = 'x' self.assertEqual(TicTacToe.check_rows(self.table, [], 'x'), [[1, 1]])
def test_check_col(self): self.table[1][1] = 'x' self.table[0][0] = 'x' self.table[2][0] = 'o' self.assertEqual(TicTacToe.check_col(self.table, [], 'x'), []) self.table[0][0] = ' ' self.table[2][1] = 'x' self.assertEqual(TicTacToe.check_col(self.table, [], 'x'), [[0, 1]]) self.table[2][1] = ' ' self.table[0][1] = 'x' self.assertEqual(TicTacToe.check_col(self.table, [], 'x'), [[2, 1]]) self.table[1][1] = ' ' self.table[2][1] = 'x' self.assertEqual(TicTacToe.check_col(self.table, [], 'x'), [[1, 1]])
def test_check_diagonals(self): self.table[1][1] = 'x' self.table[0][0] = 'x' self.table[2][0] = 'o' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [[2, 2]]) self.table[1][1] = ' ' self.table[2][2] = 'x' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [[1, 1]]) self.table[0][0] = ' ' self.table[1][1] = 'x' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [[0, 0]]) self.table[2][0] = 'x' self.table[2][2] = 'o' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [[0, 2]]) self.table[0][2] = 'x' self.table[2][0] = ' ' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [[2, 0]]) self.table[2][0] = 'x' self.table[1][1] = ' ' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [[1, 1]]) self.table[2][0] = ' ' self.assertEqual(TicTacToe.check_diagonals(self.table, [], 'x'), [])
def main(): t = TicTacToe() board = [['.' for i in xrange(0, 3)] for j in xrange(0, 3)] t.prettyPrint(board) print "You wanna take on first ? (y/n)", op = raw_input().lower() if op == 'y': player = 'X' bot = 'O' t.setPlayerTurn(bot) else: player = 'O' bot = 'X' t.setPlayerTurn(bot) print "I'll start then.." time.sleep(0.5) code, board, res = t.nextMove(board) t.prettyPrint(board) while True: i, j = getMove(board) board[i][j] = player print "Your move is.." t.prettyPrint(board) code, board, res = t.nextMove(board) if code == 1: print "Here is my move.." time.sleep(0.5) t.prettyPrint(board) if not res == 'unknown': if res == 'draw': print "It's a draw!" else: if res == player: print "You won!" else: print "I won!" break print "Thanks for playing. Good day!" return 0
def tictactoe(self): gui.destroy() import TicTacToe TicTacToe.playGame()
__author__ = 'Ales Kocur' from TicTacToe import * import time #game = Game(size=4, starting_player=Player.X, ai_player=Player.O) game = TicTacToe(size=20) game.draw() while not game.has_winner(): print('== {} playing =='.format(game.whose_turn().name)) if (game.whose_turn() == game.ai_player): print("{}'s thinking...".format(game.ai_player.name)) start = time.time() position = game.next_ai_move() end = time.time() print('Took: {}s'.format(end - start)) else: x = int(input('Row index:')) y = int(input('Column index:')) position = Position(x, y) print('Choosen position: {} {}'.format(position.x, position.y)) if game.move(position): game.draw() else: print('Unallowed move! Try again...')
def test_pcs_if_pc_can_win(self): self.table[0][0] = 'o' self.table[0][1] = 'o' self.assertEqual(TicTacToe.pc(self.table), [0, 2])
self.fenetre = gtk.Window(gtk.WINDOW_TOPLEVEL) self.fenetre.connect("delete_event", self.evnmt_delete) self.fenetre.connect("destroy", self.destroy) self.fenetre.set_border_width(10) self.fenetre.resize(622,622) self.vbox = gtk.VBox(True,1) #self.visual = gtk.gdk.Visual(1,gtk.gdk.VISUAL_STATIC_GRAY) #self.colormap = gtk.gdk.Colormap(self.visual, True) #self.vbox.set_colormap(self.colormap) self.color = gtk.gdk.Color('blue') for i in range(board.nb): self.hbox = gtk.HBox(True,1) for j in range(board.nb): self.event = gtk.EventBox() self.event.modify_bg(gtk.STATE_NORMAL, self.color); self.event.connect("button_press_event", self.play , None, board, i, j) self.event.show() self.hbox.add(self.event) self.vbox.add(self.hbox) self.hbox.show() self.fenetre.add(self.vbox) self.vbox.show() self.fenetre.show() def boucle(self): gtk.main() if __name__ == "__main__": game = TicTacToe() game.run()
def test_count_free(self): self.assertEqual(TicTacToe.count_free(self.table), 9) self.table[1][1] = 'x' self.assertEqual(TicTacToe.count_free(self.table), 8) self.table[1][2] = 'x' self.assertEqual(TicTacToe.count_free(self.table), 7)
from TicTacToe import * x = TicTacToe() x.add_X(1) x.add_X(5) x.add_O(4) x.add_X(9) print(x.board) print(str(x.check_for_win(1))) print(x.main_dic[1])