Answered step by step
Verified Expert Solution
Question
1 Approved Answer
[Please help me complete these two parts of codes to create an AI player for Tic Tac Toe games] 1) import math import time from
[Please help me complete these two parts of codes to create an AI player for Tic Tac Toe games]
1)
import math import time from player import HumanPlayer, RandomComputerPlayer class TicTacToe(): def __init__(self): self.board = self.make_board() self.current_winner = None @staticmethod def make_board(): return [' ' for _ in range(9)] def print_board(self): for row in [self.board[i*3:(i+1) * 3] for i in range(3)]: print('| ' + ' | '.join(row) + ' |') @staticmethod def print_board_nums(): # 0 | 1 | 2 number_board = [[str(i) for i in range(j*3, (j+1)*3)] for j in range(3)] for row in number_board: print('| ' + ' | '.join(row) + ' |') def make_move(self, square, letter): if self.board[square] == ' ': self.board[square] = letter if self.winner(square, letter): self.current_winner = letter return True return False def winner(self, square, letter): #this function should have the logic to check for the winning condition #for instance, three O's in a straight line def empty_squares(self): return ' ' in self.board def num_empty_squares(self): return self.board.count(' ') def available_moves(self): #this function should compute the available moves on the board def play(game, x_player, o_player, print_game=True): #the complete logic for the game should be defined here if __name__ == '__main__': x_player = RandomComputerPlayer('X') o_player = HumanPlayer('O') t = TicTacToe() play(t, x_player, o_player, print_game=True)
2)
import math import random class Player(): def __init__(self, letter): self.letter = letter def get_move(self, game): pass class HumanPlayer(Player): def __init__(self, letter): super().__init__(letter) def get_move(self, game): valid_square = False val = None while not valid_square: square = input(self.letter + '\'s turn. Input move (0-9): ') try: val = int(square) if val not in game.available_moves(): raise ValueError valid_square = True except ValueError: print('Invalid square. Try again.') return val class RandomComputerPlayer(Player): def __init__(self, letter): super().__init__(letter) def get_move(self, game): square = random.choice(game.available_moves()) return square
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started