def alfabeta(board, depth, alfa, beta): boardstring = board.tostr() + str(board.team) + str(depth) # print boardstring , board.value() if boardstring in memo: return memo[boardstring] if depth == 0 or board.is_final(): return (board.value(), None) ret = None bestValue = -INF childNodes = board.movimentos() if not childNodes: return (0, None) for child in childNodes: newboard = Board(board.s) newboard.move(child) (val, x) = alfabeta(newboard, depth - 1, -beta, -alfa) val = -val if val > bestValue: ret = child bestValue = val if val > alfa: alfa = val if alfa >= beta: break memo[boardstring] = (bestValue, ret) return (bestValue, ret)
def setUp(self): self.testboard = Board() # WHITE FIGURES # self.test_white_pawn1 = Figure("p", "white", "A2", self.testboard) # self.test_white_pawn2 = Figure("p", "white", "B2", self.testboard) # self.test_white_pawn3 = Figure("p", "white", "C2", self.testboard) # self.test_white_pawn4 = Figure("p", "white", "D2", self.testboard) # self.test_white_pawn5 = Figure("p", "white", "E2", self.testboard) # self.test_white_pawn6 = Figure("p", "white", "F2", self.testboard) # self.test_white_pawn7 = Figure("p", "white", "G2", self.testboard) # self.test_white_pawn8 = Figure("p", "white", "H2", self.testboard) self.test_white_rook_left = Figure("r", "white", "A1", self.testboard) self.test_white_rook_right = Figure("r", "white", "H1", self.testboard) self.test_white_knight_left = Figure("k", "white", "B1", self.testboard) self.test_white_knight_right = Figure("k", "white", "G1", self.testboard) self.test_white_bishop_left = Figure("b", "white", "C1", self.testboard) self.test_white_bishop_right = Figure("b", "white", "F1", self.testboard) self.test_white_queen = Figure("Q", "white", "D1", self.testboard) self.test_white_king = Figure("K", "white", "E1", self.testboard) # BLACK FIGURES self.test_black_pawn1 = Figure("p", "black", "A7", self.testboard) self.test_black_pawn2 = Figure("p", "black", "B7", self.testboard) self.test_black_pawn3 = Figure("p", "black", "C7", self.testboard) self.test_black_pawn4 = Figure("p", "black", "D7", self.testboard) self.test_black_pawn5 = Figure("p", "black", "E7", self.testboard) self.test_black_pawn6 = Figure("p", "black", "F7", self.testboard) self.test_black_pawn7 = Figure("p", "black", "G7", self.testboard) self.test_black_pawn8 = Figure("p", "black", "H7", self.testboard) self.test_black_rook_left = Figure("r", "black", "A8", self.testboard) self.test_black_rook_right = Figure("r", "black", "H8", self.testboard) self.test_black_knight_left = Figure("k", "black", "B8", self.testboard) self.test_black_knight_right = Figure("k", "black", "G8", self.testboard) self.test_black_bishop_left = Figure("b", "black", "C8", self.testboard) self.test_black_bishop_right = Figure("b", "black", "F8", self.testboard) self.test_black_queen = Figure("Q", "black", "D8", self.testboard) self.test_black_king = Figure("K", "black", "E8", self.testboard) self.testboard.update() # print(self.testboard) self.results = []
def connect_four(player1, player2): """ Plays a game of Connect Four between the two specified players, and returns the Board object as it looks at the end of the game. inputs: player1 and player2 are objects representing Connect Four players (objects of the Player class or a subclass of Player). One player should use 'X' checkers and the other should use 'O' checkers. """ # Make sure one player is 'X' and one player is 'O'. if player1.checker not in 'XO' or player2.checker not in 'XO' \ or player1.checker == player2.checker: print('need one X player and one O player.') return None print('Welcome to Connect Four!') print() board = Board(6, 7) print(board) while True: if process_move(player1, board) == True: return board if process_move(player2, board) == True: return board
def __init__(self, numRows: int, numCols: int, blankChar: str = '*', possibleTotalHits: int = None) -> None: self.blankChar = blankChar self.possibleTotalHits = None # this will obviously need to change to what is included in config. file self.board = Board(numRows, numCols, blankChar) self.players = [] self.maxX = numRows - 1 self.maxY = numCols - 1 self._curPlayerTurn = 0
def __init__(self, puzzle_size, clue_str, symmetry=None, starting_cell=None, find_all=True): '''Object that holds this puzzles details and inputs''' self.puzzle_size = puzzle_size self.clue_str = clue_str + 'Y' self.symmetry = symmetry self.starting_cell = starting_cell self.find_all = find_all self.first_board = Board(initialize_first_grid(self.puzzle_size), self)
def p1vsai(): clearScreen() diff = difficulty() time.sleep(1.5) board = Board() turns_taken = 0 possible_nums = [str(i) for i in range(1, 10)] last_move, AI_XO, p1_XO = chooseXO() while turns_taken < 9: clearScreen() board.print_board() if last_move == "p1": print("Bot's turn") time.sleep(1.5) if diff == "E": possible_nums = AI_turn_easy(board, possible_nums, AI_XO, p1_XO) elif diff == "H": possible_nums = AI_turn_hard(board, possible_nums, AI_XO, p1_XO) elif diff == "I": possible_nums = AI_turn_impossible(board, possible_nums, AI_XO, p1_XO) last_move = "AI" elif last_move == "AI": print("Player 1's turn") possible_nums = p1_turn(board, possible_nums, p1_XO) last_move = "p1" win = check_win(board, turns_taken) if win == None: pass else: break turns_taken += 1 clearScreen() board.print_board() if win == AI_XO: print("Bot wins. You lose :(") time.sleep(1.5) elif win == p1_XO: print("You win :) Congratulations!") time.sleep(1.5) else: print("It was a draw") time.sleep(1.5) time.sleep(1.5)
def takeTurns(gameDisplay, columns, username, teams, target, boardWidth, boardHeight): ''' - Creates basic gameplay loop. - Each team/color takes it in turns to add a chip to the board. The user can click to add a chip. On a CPU's turn, the 'findMove()' function from the 'Board' object is called. ''' exitGame = False teamsIter = cycle(iter(teams)) clock = pygame.time.Clock() for i in range(np.random.randint(1, len(teams) + 1)): next(teamsIter) turn = next(teamsIter) board = Board(columns, columns, teams, target) while not exitGame: for event in pygame.event.get(): if event.type == pygame.QUIT: exitGame = True if board.checkWin() == None and board.availableColumns != []: if turn != username: newColumn = board.findMove(turn) board.addChip(newColumn, turn) turn = next(teamsIter) else: if event.type == pygame.MOUSEBUTTONDOWN: posx = event.pos[0] move = int(math.floor(posx / (boardWidth / columns))) if move in board.availableColumns: board.addChip(move, turn) turn = next(teamsIter) drawBoard(gameDisplay, board) if board.checkWin() != None: print('{} wins!!'.format(turn)) elif board.availableColumns == []: print("It's a draw!!") pygame.display.update() clock.tick(25)
def aivsai(): clearScreen() board = Board() turns_taken = 0 possible_nums = [str(i) for i in range(1, 10)] print("Bot 1 is 'O' and will go first") print("Bot 2 is 'X' and will go second") time.sleep(2) AI1_XO = "O" AI2_XO = "X" last_move = "AI2" AI1_moves = [AI_turn_easy, AI_turn_hard, AI_turn_impossible] AI2_moves = [AI_turn_easy, AI_turn_hard, AI_turn_impossible] while turns_taken < 9: clearScreen() board.print_board() if last_move == "AI2": print("Bot 1's Turn") time.sleep(1.5) possible_nums = random.choice(AI1_moves)(board, possible_nums, AI1_XO, AI2_XO) last_move = "AI1" elif last_move == "AI1": print("Bot 2's turn") time.sleep(1.5) possible_nums = random.choice(AI2_moves)(board, possible_nums, AI2_XO, AI1_XO) last_move = "AI2" win = check_win(board, turns_taken) if win == None: pass else: break turns_taken += 1 clearScreen() board.print_board() if win == AI1_XO: print("Bot 1 wins!") time.sleep(1.5) elif win == AI2_XO: print("Bot 2 wins!") time.sleep(1.5) else: print("It was a draw") time.sleep(1.5) time.sleep(1.5)
import random import pygame import pygame.gfxdraw import pygame.mouse import sys import time from math import floor from settings import Settings from board_class import Board from filledrounded_rect import AAfilledRoundedRect from piece import Piece board = Board() turn = 0 def bot_choice(): return random.randint(0, 6) def user_choice_def(event): user_choice = event.pos[0] user_choice = int(floor(user_choice / 100)) if user_choice > 6: user_choice = 6 return user_choice def check_events(ai_settings, screen, game_over, piece): # Reakcja na zdarzenia generowane przez klawiaturę i mysz. for event in pygame.event.get():
from board_class import Board from file_io import get_maze_key_from_file, write_dict_to_file, read_dict_from_file, write_set_to_file import matplotlib.pyplot as plt maze = Board() print("\n") num_sol_gen = {} num_of_mazes_per_iter = 10 iterations = 10 for i in range(iterations): maze_set = maze.build_random_maze2(num_of_mazes=num_of_mazes_per_iter, verbose=True, size_board=(9, 9), min_moves=30, adl_checks=True, adl_check_threshold=50) print("\n") write_set_to_file(maze_set) print("\n") for key, value in sorted(maze_set.items()): num_sol_gen[key] = len(value) print("This pass generated these mazes: ") print(num_sol_gen) print("\n") # Generate the histogram. keys = num_sol_gen.keys()
#checks if a string can be cast to an int def is_int(s): try: int(s) return True except: return False #returns an index based on current board configuration def ai_pick(board, counter): state = state_from_board(board, counter) return np.argmax(sess.run('action_values:0', feed_dict={states: state})) board = Board() player_symbol = input('Pick X or O (X goes first): ') while player_symbol != 'X' and player_symbol != 'O': player_symbol = input('Invalid symbol. Pick X or O: ') if player_symbol == 'X': player_num = 0 else: player_num = 1 winner = '' counter = 0 symbols = ['X', 'O'] while winner == '':
from board_class import Board, Minotaur, Player import file_io # maze_key = file_io.read_dict_from_file("mazes/6x6.txt")[47][0] maze_key = {'size_board': (5, 5), 'walls': [((0, 1), (1, 1)), ((1, 0), (1, 1)), ((1, 1), (1, 2)), ((1, 2), (2, 2)), ((1, 3), (1, 4)), ((2, 2), (2, 3)), ((2, 3), (2, 4)), ((3, 0), (3, 1)), ((3, 1), (3, 2)), ((3, 2), (3, 3)), ((3, 3), (3, 4)), ((4, 0), (4, 1)), ((4, 1), (4, 2)), ((4, 3), (4, 4))], 'player_start': (1, 4), 'mino_start': (4, 4), 'goal': (4, 4), 'solution': ['left', 'up', 'right', 'right', 'right', 'right', 'up', 'left', 'left', 'up', 'up', 'left', 'left', 'right', 'right', 'down', 'down', 'right', 'right', 'down', 'up', 'left', 'left', 'up', 'up', 'right', 'right', 'left', 'left', 'left', 'left', 'down', 'down', 'down', 'down', 'right', 'right', 'right', 'right'], 'sol_length': 39, 'seed': 7188903436156103517} maze = Board(maze_key) player = Player(maze) mino = Minotaur(maze) maze.visualize_board() solution = maze_key["solution"] game_end = False moves = 0 for step in solution: # Get player move player_move = step # Update player location location_before = player.location player.move(player_move) location_after = player.location print("Player moved from {before} to {after}.".format(before=location_before, after=location_after)) maze.visualize_board() moves += 1 # Minotaur's turn
def __init__(self): self.board = Board()
def play_game(self): P1 = Player(self.player_1_type, 1) P2 = Player(self.player_2_type, 2) B = Board() player_list = [P1, P2] turn_count = 0 error_count = 0 winner_id = '' while turn_count < 42: current_player = player_list[turn_count % 2] move, piece = current_player.make_move_master(B.board_dict) # print("You are here. This is move we got coming in: " + str(move)) if B.is_error(move) != 0: if B.is_error(int(move)) == 1: print('ERROR CODE 1 move not int!') error_count += 1 # print('Error count: ' + str(error_count)) continue if B.is_error(int(move)) == 2: print('ERROR CODE 2 move not 1-7!') error_count += 1 # print('Error count: ' + str(error_count)) if current_player.player_type == 'Human': continue else: break if B.is_error(int(move)) == 3: # print('ERROR CODE 3 move off board') error_count += 1 # print('Error count: ' + str(error_count)) continue error_count = 0 B.board_move(move, piece) if self.print_status == 2: B.print_board() if B.is_win() is True: winner_id = (turn_count % 2) + 1 print("Game Won!!!") break turn_count += 1 if winner_id == '': winner_id = 3 if self.print_status == 1 or self.print_status == 2: print("FINAL BOARD: ") B.print_board() print(B.board_dict) print('') print(B.move_list) return winner_id, B.board_dict
if counter == 1: state = -state state = state.reshape((1,9)) return state memory = Memory(3000)#not sure how many samples will crash the computer, so let's keep it conservative for now model = Model() epsilon = 0.9 #we'll play a thousand games with tf.Session() as sess: sess.run(model.var_init) for game in range(4000): if game%100 == 0: print(game) board = Board() winner = '' counter = 0 symbols = ['X', 'O'] #we need to store samples temporarily because we don't get their values till the end of each game samples = []#each sample contains state, action, reward, and next state while winner == '': state = state_from_board(board, counter) action = choose_action(epsilon, state, model, sess) current_sample = [] current_sample.append(state) current_sample.append(action) if board.getSquare(action) == 0:
# TEST FILE FOR BOARD from board_class import Board alpha = float('-inf') beta = float('inf') # print works board = Board() #board.print_board() #print('\n') # new board works new_board = board.new_board() # Inital Move Test # Takes two optional parameters flag and iterations # if flag == True Will run k iterations with depth+2 depth # iterations = number of times to run the extended depth board.play_game(3) # minimax testing #move = board.minimax(board, 5, alpha, beta, True, color) #print(move.move)
def make_move_smart_2(self, board_dict): # Checks if can force a win # print("Start of Move Analysis") # Test comment win_count = 0 bad_move_list = [] good_move_list = [] possible_move_list = [] temp_B = Board() for i in range(1, 8): if temp_B.is_error(i) == 3: continue else: possible_move_list.append(i) # temp_B.print_board() for move in possible_move_list: temp_B.board_dict = board_dict.copy() # print("Original Board: ") # temp_B.print_board() # print("TEMP MOVE FIRST LAYER: " + str(i)) temp_B.board_move(i, self.player_piece) # print("Level 1 Move Board: ") if temp_B.is_win() is True: # print("Level 1 Win Found") return i win_count = 0 for k in range(1, 8): temp_B.board_move(k, self.opposing_piece) if temp_B.is_win() is True: # print("This move would lead to a guaranteed loss: " + str(i)) # temp_B.print_board() bad_move_list.append(i) temp_B.take_back() break for p in range(1, 8): temp_B.board_move(p, self.player_piece) # print("TEMP MOVE 3: " + str(p)) if temp_B.is_win() is True: win_count += 1 # print("Level 3 Win found below. Level 3 Win Count: " + str(win_count)) # temp_B.print_board() if win_count == 7: print( "ABSOLUTE WIN FOUND- Aren't you a clever boy: " + str(i)) # Bug where move returned is off-board, because player wins regardless good_move_list.append(i) temp_B.take_back() break temp_B.take_back() temp_B.take_back() temp_B.take_back() # Checks first to make sure not missing an oponent has a winning move temp_B.board_dict = board_dict.copy() for i in range(1, 8): temp_B.board_move(i, self.opposing_piece) if temp_B.is_win() is True: return i else: temp_B.board_dict = board_dict.copy() # Solves bug of constantly returning a move that is off-board temp_B.board_dict = board_dict.copy() for user_move in good_move_list: if temp_B.is_error(user_move) == 0: return user_move # Solves bug if no good move left if len(bad_move_list) >= 6: # print("THERE ARE NO GOOD MOVES BREAK") user_move = random.randint(1, 7) return user_move # BUG HERE: When you get near end of game, there is only one column to move in. But it's # in the bad move list, so it gets trapped in the While loop below # If still no good move user_move = random.randint(1, 7) while user_move in bad_move_list: print("You do get here") user_move = random.randint(1, 7) # print("Random Move playing: " + str(user_move)) return user_move
def make_move_smart_1(self, board_dict): # Just checks if next move is winning, or blocks an opposing winning move temp_B = Board() temp_B.board_dict = board_dict.copy() for i in range(1, 8): temp_B.board_move(i, self.player_piece) if temp_B.is_win() is True: return i else: temp_B.board_dict = board_dict.copy() for i in range(1, 8): temp_B.board_move(i, self.opposing_piece) if temp_B.is_win() is True: return i else: temp_B.board_dict = board_dict.copy() user_move = random.randint(1, 7) return user_move
def make_move_human(self, board_dict): temp_B = Board() temp_B.board_dict = board_dict.copy() temp_B.print_board() user_move = input("Make move: ") return int(user_move)
class FiguresMovesTest(unittest.TestCase): # TO DO: write tests for all figures def setUp(self): self.testboard = Board() # WHITE FIGURES # self.test_white_pawn1 = Figure("p", "white", "A2", self.testboard) # self.test_white_pawn2 = Figure("p", "white", "B2", self.testboard) # self.test_white_pawn3 = Figure("p", "white", "C2", self.testboard) # self.test_white_pawn4 = Figure("p", "white", "D2", self.testboard) # self.test_white_pawn5 = Figure("p", "white", "E2", self.testboard) # self.test_white_pawn6 = Figure("p", "white", "F2", self.testboard) # self.test_white_pawn7 = Figure("p", "white", "G2", self.testboard) # self.test_white_pawn8 = Figure("p", "white", "H2", self.testboard) self.test_white_rook_left = Figure("r", "white", "A1", self.testboard) self.test_white_rook_right = Figure("r", "white", "H1", self.testboard) self.test_white_knight_left = Figure("k", "white", "B1", self.testboard) self.test_white_knight_right = Figure("k", "white", "G1", self.testboard) self.test_white_bishop_left = Figure("b", "white", "C1", self.testboard) self.test_white_bishop_right = Figure("b", "white", "F1", self.testboard) self.test_white_queen = Figure("Q", "white", "D1", self.testboard) self.test_white_king = Figure("K", "white", "E1", self.testboard) # BLACK FIGURES self.test_black_pawn1 = Figure("p", "black", "A7", self.testboard) self.test_black_pawn2 = Figure("p", "black", "B7", self.testboard) self.test_black_pawn3 = Figure("p", "black", "C7", self.testboard) self.test_black_pawn4 = Figure("p", "black", "D7", self.testboard) self.test_black_pawn5 = Figure("p", "black", "E7", self.testboard) self.test_black_pawn6 = Figure("p", "black", "F7", self.testboard) self.test_black_pawn7 = Figure("p", "black", "G7", self.testboard) self.test_black_pawn8 = Figure("p", "black", "H7", self.testboard) self.test_black_rook_left = Figure("r", "black", "A8", self.testboard) self.test_black_rook_right = Figure("r", "black", "H8", self.testboard) self.test_black_knight_left = Figure("k", "black", "B8", self.testboard) self.test_black_knight_right = Figure("k", "black", "G8", self.testboard) self.test_black_bishop_left = Figure("b", "black", "C8", self.testboard) self.test_black_bishop_right = Figure("b", "black", "F8", self.testboard) self.test_black_queen = Figure("Q", "black", "D8", self.testboard) self.test_black_king = Figure("K", "black", "E8", self.testboard) self.testboard.update() # print(self.testboard) self.results = [] def testKnightMoves(self): for move_ in ["C3", "E4", "G4", "C5", "D7", "F8", "D5", "H8", "G6"]: self.results.append( move(self.test_white_knight_left, move_, self.testboard, False)) self.assertEqual( self.results, [True, True, False, True, True, True, False, False, True]) def testQueenMoves(self): for move_ in [ "D2", "D4", "H7", "G7", "H8", "E5", "G6", "F6", "I6", "B6", "A5" ]: self.results.append( move(self.test_white_queen, move_, self.testboard, False)) self.assertEqual(self.results, [ True, True, False, True, True, True, False, True, False, True, True ]) def testKingMoves(self): for move_ in ["D1", "D2", "E3", "E2", "E4", "C2", "G4", "E3"]: self.results.append( move(self.test_white_king, move_, self.testboard, False)) self.assertEqual(self.results, [False, True, True, True, False, False, False, True]) # def testCheck(self): # for move_ in ["E2", "E3", "E4", "E5", "E6"]: # move(self.test_white_king, move_, self.testboard, True) # # self.assertTrue(self.testboard.is_check()) def tearDown(self): self.results = None del self.testboard
maze_key = get_maze2(size=sys.argv[1], difficulty="random") except UnboundLocalError: sys.exit("ERROR: Please provide a valid size argument") elif len(sys.argv) > 2: # Two or more args were given. Interpret first two as board size and difficulty try: maze_key = get_maze2(size=sys.argv[1], difficulty=sys.argv[2]) except UnboundLocalError: sys.exit( "ERROR: Please provide a valid size and difficulty argument") print("Maze key retrieved.") print(maze_key) # Set up board_class objects maze = Board(maze_key) player = Player(maze) mino = Minotaur(maze) # Add extra moves to make animation work easily player_moves = [ maze.G.graph["player_location"], maze.G.graph["player_location"] ] mino_moves = [ maze.G.graph["mino_location"], maze.G.graph["mino_location"], maze.G.graph["mino_location"] ] # Run main # Set window size window = pygame.display.set_mode(size=calculate_screen_size(maze)[0])
def on_move(self, state): b = Board(state) print b.value() move = getmove(b) self.send_move(move[0], move[1])
p = pawn, Q = queen, K = king, k = knight, b = bishop, r = rook TO DO LIST: - GUI - rochade, en passant, promotion, check, checkmate - TURN STARTS HERE - """ from figure_class import Figure, move from board_class import Board my_board = Board() # WHITE FIGURES white_pawn1 = Figure("p", "white", "A2", my_board) white_pawn2 = Figure("p", "white", "B2", my_board) white_pawn3 = Figure("p", "white", "C2", my_board) white_pawn4 = Figure("p", "white", "D2", my_board) white_pawn5 = Figure("p", "white", "E2", my_board) white_pawn6 = Figure("p", "white", "F2", my_board) white_pawn7 = Figure("p", "white", "G2", my_board) white_pawn8 = Figure("p", "white", "H2", my_board) white_rook_left = Figure("r", "white", "A1", my_board) white_rook_right = Figure("r", "white", "H1", my_board) white_knight_left = Figure("k", "white", "B1", my_board)
for new_option in maze.get_move_options(player_location)["player"]: move_queue.append([new_option, current_state, move_list[:]]) pass elif game_end is True and game_win is False: # In this case, the Minotaur killed the player. No new options are added to the queue. # print("Game loss.") pass elif game_end is True and game_win is True: # The solver has found a solution. move_list.append(option) return True, move_list # maze.visualize_board() # print(move_queue) # If the end of the while loop is reached, then there is no solution. return False, [] maze = Board(maze_file="mazes/level_20.txt") maze.visualize_board() print("\n") solvable, solution = solve(maze) if solvable: print("The maze is solvable in {} moves with the following solution: ".format(len(solution))) print(solution) else: print("The maze is not solvable.") maze.visualize_board()
random_policy /= probsum return np.random.choice(9, p=random_policy) agent_num = 0 agent_winsX = 0 agent_winsO = 0 drawsX = 0 drawsO = 0 for game in range(8000): if game % 100 == 0: print(game) winner = '' counter = 0 symbols = ['X', 'O'] board = Board() while winner == '': if counter == agent_num: index = ai_pick(board, counter) else: index = random_pick(board, counter) winner = board.setSquare(index, symbols[counter]) counter = (counter + 1) % 2 counter = (counter + 1) % 2 if winner == 'D': if agent_num == 0: drawsX += 1 else: drawsO += 1 elif counter == agent_num: if counter == 0:
if counter == 1: state = -state state = state.reshape((1, 9)) return state memory = Memory(3000) model = Model(0.001) epsilon = 0.9 with tf.Session() as sess: sess.run(model.var_init) for game in range(10000): if game % 100 == 0: print(game) board = Board() winner = '' counter = 0 symbols = ['X', 'O'] #we need to store samples temporarily because we don't get their values till the end of each game samples = [ ] #each sample contains state, action, reward, and next state while winner == '': state = state_from_board(board, counter) action = choose_action(epsilon, state, model, sess) current_sample = [] current_sample.append(state) current_sample.append(action)
class TicTacToe: def __init__(self): self.board = Board() def get_player_char(self): x_or_o = input('Would you like to be X or O') while x_or_o is not 'x' and x_or_o is not 'X' and x_or_o is not 'o' and x_or_o is not 'O': x_or_o = input('Please enter an x or o') if x_or_o is 'x': x_or_o = 'X' elif x_or_o is 'o': x_or_o = 'O' return x_or_o def get_player_spot(self): i = 0 while i < 1: number = int(input('Enter a number for your x or o')) if number == 1 or number == 2 or number == 3 or number == 4 or number == 5 or number == 6 or number == 7 or number == 8 or number == 9: i = 1 else: i = 0 return number # do not change anything from here to the end def get_computer_spot(self): index = random.randint(0, self.board.nbr_of_unfilled_slots() - 1) nbr = self.board.choose_spot_at(index) print('Computer chooses', nbr) return nbr def start(self): print("This program plays tic-tac-toe") user_mark = self.get_player_char() if user_mark == 'X': # make sure yourMark is a capital X or O computer_mark = 'O' else: computer_mark = 'X' # keep going until somebody has won or the board is full while not (self.board.win() or self.board.full()): if computer_mark == 'X': # if computer is X, computer goes first index = self.get_computer_spot() self.board.setX(index) if self.board.full() or self.board.win(): break # is game over before player turn? index = self.get_player_spot() # user goes after computer self.board.setO(index) else: # player is X, so goes first index = self.get_player_spot() # user goes first self.board.setX(index) if self.board.full() or self.board.win(): break index = self.get_computer_spot() # then computer if user did not win with last move self.board.setO(index) self.board.display() if self.board.win(): print(self.board.get_winner() + " wins.") else: print("Nobody wins.")