def fill_coords(XCoords, OCoords): testBoard = GameBoard() for x in range(len(XCoords)): testBoard.board[XCoords[x][0]][XCoords[x][1]] = 'X' for o in range(len(OCoords)): testBoard.board[OCoords[o][0]][OCoords[o][1]] = 'O' return testBoard
def play_tic_tac_toe(): gb = GameBoard() gb.turnNumber = random.choice([0, 1]) # gb.print_board() while True: # print() currPlayer, otherPlayer = activePlayer[gb.turnNumber], activePlayer[(gb.turnNumber + 1) % 2] coord = currPlayer.make_move(gb) gb.place_piece(coord) results = gb.get_results() if results == currPlayer.piece: currPlayer.update(1, gb) otherPlayer.update(-1, gb) break if results == "-": # tie game currPlayer.update(0.5, gb) otherPlayer.update(0.5, gb) break otherPlayer.update(0, gb) if player[0] != "persona" or player[1] != "persona": gb.print_board() gb.switch_turn()
def assess(self, other): for c1 in self.chromosomes: for c2 in other.chromosomes: # print("new battle") for games in range(10): p1 = Players.Chromo("O", c1) p2 = Players.Chromo("X", c2) players = [p1, p2] gb = GameBoard() while True: active, nextP = players[gb.turnState], players[(gb.turnState + 1) % 2] move = active.make_move(gb) # print(move) # gb.print_board() gb.place_piece(move) gb.increment_turn() r = gb.get_results() if r == "O": # gb.print_board() c1.update(1) c2.update(-1) break if r == "X": # gb.print_board() c1.update(-1) c2.update(1) break if r == "-": c1.update(.2) c2.update(.2) break gb.switch_turn()
def train(numberOfGames): gb = GameBoard() p1 = Players.Merlin("O") p2 = Players.Merlin("X") players = [p1, p2] for i in range(numberOfGames): if i % 100 == 0: print(i) gb = GameBoard() gb.turnNumber = random.choice([0, 1]) while True: # gb.print_board() active, nextP = players[gb.turnNumber], players[(gb.turnNumber + 1) % 2] move = active.make_move(gb) gb.place_piece(move) r = gb.get_results() # print(r) if r == "O" or r == "X": active.update(1, gb) nextP.update(-1, gb) break if r == "-": active.update(0, gb) nextP.update(0, gb) break active.update(0, gb) nextP.update(0, gb) gb.switch_turn() p2.write_history()
def __init__(self, t): self.memory = self.read_history("history.txt") self.currBoard = GameBoard() self.boardStates = [GameBoard().to_string_one_line()] self.piece = t self.UNRESEARCHEDBOARDVALUE = .5 self.TIEWORTH = .7
def test_has_won(): print("\nTesting has_won...") gb = GameBoard() gb.place_piece([0,0]) gb.place_piece([1,0]) gb.place_piece([1,1]) gb.place_piece([2,0]) gb.place_piece([2,2]) gb.place_piece([2,1]) if (gb.has_won(gb.pieces[gb.turnNumber])): print("Success")
def play_vs_merlin(numberOfGames): p1 = Players.Player("O") p2 = Players.Merlin("X", learning = False) players = [p1, p2] for i in range(numberOfGames): gb = GameBoard() gb.turnNumber = random.choice([0, 1]) while True: gb.print_board() move = players[gb.turnNumber].make_move(gb) gb.place_piece(move) gb.switch_turn() if (gb.get_results() != None): break
def play(numberOfGames): p1 = Players.Player("O") p2 = Players.Player("X") players = [p1, p2] for i in range(numberOfGames): gb = GameBoard() while True: print(gb.valid_actions()) gb.print_board() move = players[gb.turnNumber].make_move(gb) gb.place_piece(move) if (gb.get_results() != None): break gb.switch_turn()
def __init__(self): self._atom_list = sample(list(product(range( 1, 9), repeat=2)), k=5) # initialize random list of atom locations self._gameB = GameBoard( self._atom_list) # initialize a game board with the atom list self._board = self._gameB.get_board( ) # get the game board for calculating ray path self._score = 25 # initialize the starting points for the game self._ray_locations = [] # empty list to store ray entry/exit squares self._wrong_atom_guesses = [ ] # empty list to store incorrect atom guesses self._correct_atom_guesses = [ ] # empty list to store correct atom guesses self._ray_status = None self._ray_row = None self._ray_column = None self._screen = pygame.display.set_mode((600, 800)) self._font = pygame.font.Font('freesansbold.ttf', 36) self.background = pygame.image.load('board_grid.png') self.background = pygame.transform.scale(self.background, (600, 600)) self._game_status = True self._ray_color = None
def evaluate_options(self): Temperature = 5 currWinner = None editBoard = GameBoard() editBoard.board = self.copy_board(self.currBoard) score = 0 strng = "" prob = list() self.currBoard.print_board() for i in range(3): for j in range(3): if (self.currBoard.is_valid_move((i, j))): editBoard.board[i][j] = self.piece strng = editBoard.to_string_one_line() score = 0 prob.append(((i, j), self.evaluate_option(strng, (i, j), Temperature))) editBoard.board = self.copy_board(self.currBoard) bot = 0 for dub in prob: bot += dub[1] for dub in range(len(prob)): # print(prob[dub]) if dub == 0: prob[dub] = (prob[dub][0], prob[dub][1] / bot) else : prob[dub] = (prob[dub][0], prob[dub][1] / bot + prob[dub - 1][1]) rand = random() # print(prob) for dub in prob: if (rand < dub[1]): return dub[0] print("F**K") return (0, 0)
class Player(ABC): ''' abstract base class of a player ''' def __init__(self): self.__game_board = GameBoard() self.__opponent_map = GameBoard() self.__game_board.populate_board() @property def game_board(self): return self.__game_board @property def opponent_map(self): return self.__opponent_map @abstractmethod def strike_opponent(self, opponent): pass @property def has_won(self): ''' Checks if a player has already discovered all enemy ships ''' for ship, found in self.opponent_map.revealed.items(): if found != BoardStates(ship).value: return False return True def print_map(self, map): ''' Debugging utility for printing out current board space ''' with np.printoptions(precision=3, floatmode='maxprec', suppress=True): print(map, end='\n\n')
def test_is_valid_move(): print("Testing is_valid_move...") gb = GameBoard() gb.place_piece([1,1]) if (not(gb.is_valid_move([1,1]))): print(" Success") if (gb.is_valid_move([1, 2])): print(" Success") if (not(gb.is_valid_move([1,3]))): print(" Success")
class Game(object): def __init__(self, Player1, Player2): self.player1 = Player1 self.player2 = Player2 self.board = GameBoard() self.turn = 1 @staticmethod def checkwin(board): #check if someone has won curboard = 0 if isinstance(board,GameBoard): #typechecking is not working consistently. curboard = board elif isinstance(board, list): curboard = GameBoard(board) else: return 1 #SOMETHING WENT WRONG. if( #horizontals (curboard.is1(0,0) and curboard.is1(0,1) and curboard.is1(0,2)) or (curboard.is1(1,0) and board.is1(1,1) and curboard.is1(1,2)) or (curboard.is1(2,0) and curboard.is1(2,1) and curboard.is1(2,2)) or #verticals (curboard.is1(0,0) and curboard.is1(1,0) and curboard.is1(2,0)) or (curboard.is1(0,1) and curboard.is1(1,1) and curboard.is1(2,1)) or (curboard.is1(0,2) and curboard.is1(1,2) and curboard.is1(2,2)) or #diagonals (curboard.is1(0,0) and curboard.is1(1,1) and curboard.is1(2,2)) or (curboard.is1(0,2) and curboard.is1(1,1) and curboard.is1(2,0)) ): return 1 #1 wins elif ( #horizontals (curboard.is2(0,0) and curboard.is2(0,1) and curboard.is2(0,2)) or (curboard.is2(1,0) and curboard.is2(1,1) and curboard.is2(1,2)) or (curboard.is2(2,0) and curboard.is2(2,1) and curboard.is2(2,2)) or #verticals (curboard.is2(0,0) and curboard.is2(1,0) and curboard.is2(2,0)) or (curboard.is2(0,1) and curboard.is2(1,1) and curboard.is2(2,1)) or (curboard.is2(0,2) and curboard.is2(1,2) and curboard.is2(2,2)) or #diagonals (curboard.is2(0,0) and curboard.is2(1,1) and curboard.is2(2,2)) or (curboard.is2(0,2) and curboard.is2(1,1) and curboard.is2(2,0)) ): return 2 # 2 wins else: has_valid_move = False for i in range(3): for j in range(3): if not curboard.is1(i,j) and not curboard.is2(i,j): has_valid_move = True break; if has_valid_move: break; if has_valid_move: return 0 # keep going else: return -1 # draw. def prompt_for_move(self): move = [-1,-1] if self.turn == 1: move = self.player1.get_move(self.board) elif self.turn == 2: move = self.player2.get_move(self.board) self.board.makemove(self.turn,move[0],move[1]) if self.turn == 1: self.turn = 2 else: self.turn = 1 def play(self): while self.checkwin(self.board) == 0: self.board.printboard_debug() self.prompt_for_move() self.board.printboard(); if self.checkwin(self.board) == 1: self.player1.report_win() self.player2.report_loss() elif self.checkwin(self.board) == 2: self.player2.report_win() self.player1.report_loss() elif self.checkwin(self.board) == -1: self.player1.report_draw() self.player2.report_draw() else: print("Something went wrong, checkwin is {0}".format(self.checkwin(self.board)))
if __name__ == "__main__": # check the style guide for import! from Board import GameBoard filename = "file1.txt" print("running") board = GameBoard() board.load_board(filename) game_time = board.time time = 0 board.print_board() while time < game_time: time += 1 board.spread() board.air_flow() board.print_board() board.get_sum()
def __init__(self): self.__game_board = GameBoard() self.__opponent_map = GameBoard() self.__game_board.populate_board()
def copy_board(self, board): tempBoard = GameBoard() for i in range(3): for j in range(3): tempBoard.board[i][j] = board.board[i][j] return tempBoard.board
class BlackBoxGame: """Implementation of the Black Box game. Contains method to create a GameBoard instance with indicated atom placement. Contains methods to shoot rays, adjust the game score, guess atom locations, get the current score, and get how many atoms are left to guess.""" def __init__(self): self._atom_list = sample(list(product(range( 1, 9), repeat=2)), k=5) # initialize random list of atom locations self._gameB = GameBoard( self._atom_list) # initialize a game board with the atom list self._board = self._gameB.get_board( ) # get the game board for calculating ray path self._score = 25 # initialize the starting points for the game self._ray_locations = [] # empty list to store ray entry/exit squares self._wrong_atom_guesses = [ ] # empty list to store incorrect atom guesses self._correct_atom_guesses = [ ] # empty list to store correct atom guesses self._ray_status = None self._ray_row = None self._ray_column = None self._screen = pygame.display.set_mode((600, 800)) self._font = pygame.font.Font('freesansbold.ttf', 36) self.background = pygame.image.load('board_grid.png') self.background = pygame.transform.scale(self.background, (600, 600)) self._game_status = True self._ray_color = None def shoot_ray(self, row, column): """Accepts as parameters a row and column that designates the entry point of a ray. Simulates the ray path with appropriate hit, detours and/or reflections. Returns 'False' if the entry row and column are not legal plays (non-corner border squares). Returns 'None' if the play is a hit. Returns a tuple of exit square row and column if the play exits the game black box. Deducts from the player's score: 1 point for ray entry and 1 point for ray exit, if the squares have not already been used.""" # check if ray is being shot from corner square if (row == 0 or row == 9) and (column == 0 or column == 9): return False # check if ray is being shot from non-border square if row in range(1, 9) and column in range(1, 9): return False if self._ray_color is None: self._ray_color = 0 else: self._ray_color += 1 self.adjust_score( row, column, self._ray_color) # adjust score for entry ray position self._ray_status = 'Play' # set flag variable for ray status if column == 0 or column == 9: # if shooting from horizontal position if column == 0: # if ray is moving to the right self.horiz_move_right(row, column) elif column == 9: # if ray is moving to the left self.horiz_move_left(row, column) if row == 0 or row == 9: # if shooting from vertical position if row == 0: # if ray is moving down self.vert_move_down(row, column) elif row == 9: # if ray is moving up self.vert_move_up(row, column) if self._ray_status == "Hit": # if ray hits an atom return None elif self._ray_status == "Exit": # if ray is a miss self.adjust_score( self._ray_row, self._ray_column, self._ray_color) # adjust score with exit ray position return self._ray_row, self._ray_column def horiz_move_right(self, ray_path_r, ray_path_c): """Accepts as parameters the current row and column of the ray path. Calculates the next square of a horizontal ray path to the right and determines if there are any atoms resulting in a hit or detour. Adjusts ray status variable if there is a Hit or Exit. Returns nothing.""" self._ray_row = ray_path_r self._ray_column = ray_path_c while self._ray_status == "Play": # continue ray path determination while still in "play" # check for edge case reflection if ray_path_c == 0 and self._ray_column == 0: if (self._board[ray_path_r + 1][ray_path_c + 1]) or ( self._board[ray_path_r - 1][ray_path_c + 1]) == 'A': self._ray_column -= 1 self._ray_status = "Exit" self._ray_column += 1 # move ray path one square to the right # check if ray is exiting 'black box' if self._ray_column == 9: self._ray_status = "Exit" # check for hit elif self._board[self._ray_row][ self. _ray_column] == 'A': # if atom is in next ray path square self._ray_status = "Hit" # check for reflection elif (self._board[self._ray_row + 1][self._ray_column]) and ( self._board[self._ray_row - 1][self._ray_column]) == 'A': self._ray_column -= 1 self.horiz_move_left(self._ray_row, self._ray_column) # check for detour (change ray path to 'up) elif self._board[self._ray_row + 1][self._ray_column] == 'A': self._ray_column -= 1 self.vert_move_up(self._ray_row, self._ray_column) # check for detour (change ray path to 'down) elif self._board[self._ray_row - 1][self._ray_column] == 'A': self._ray_column -= 1 self.vert_move_down(self._ray_row, self._ray_column) def horiz_move_left(self, ray_path_r, ray_path_c): """Accepts as parameters the current row and column of the ray path. Calculates the next square of a horizontal ray path moving to the left and determines if there are any atoms resulting in a hit or detour. Adjusts ray status variable if there is a Hit or Exit. Returns nothing.""" self._ray_row = ray_path_r self._ray_column = ray_path_c while self._ray_status == "Play": # continue ray path determination while still in "play" # check for edge case reflection if ray_path_c == 9 and self._ray_column == 9: if (self._board[ray_path_r + 1][ray_path_c - 1]) or ( self._board[ray_path_r - 1][ray_path_c - 1]) == 'A': self._ray_column += 1 self._ray_status = "Exit" self._ray_column -= 1 # move ray path one square to the left # check for exit if self._ray_column == 0: self._ray_status = "Exit" # check for hit elif self._board[self._ray_row][ self. _ray_column] == 'A': # if atom is in next ray path square self._ray_status = "Hit" # check for reflection elif (self._board[self._ray_row + 1][self._ray_column]) and ( self._board[self._ray_row - 1][self._ray_column]) == 'A': self._ray_column += 1 self.horiz_move_right(self._ray_row, self._ray_column) # check for detour (change to 'up' direction) elif self._board[self._ray_row + 1][self._ray_column] == 'A': self._ray_column += 1 self.vert_move_up(self._ray_row, self._ray_column) # check for detour (change to 'down' direction) elif self._board[self._ray_row - 1][self._ray_column] == 'A': self._ray_column += 1 self.vert_move_down(self._ray_row, self._ray_column) def vert_move_down(self, ray_path_r, ray_path_c): """Accepts as parameters the current row and column of the ray path. Calculates the next square of a vertical ray path moving down and determines if there are any atoms resulting in a hit or detour. Adjusts ray status variable if there is a Hit or Exit. Returns nothing.""" self._ray_row = ray_path_r self._ray_column = ray_path_c while self._ray_status == "Play": # continue ray path determination while still in "play" # check for edge case reflection if ray_path_r == 0 and self._ray_row == 0: if (self._board[ray_path_r + 1][ray_path_c + 1]) or ( self._board[ray_path_r + 1][ray_path_c - 1]) == 'A': self._ray_row -= 1 self._ray_status = "Exit" self._ray_row += 1 # adjust ray path one square 'down' # check for exit if self._ray_row == 9: self._ray_status = "Exit" # check for hit elif self._board[self._ray_row][ self. _ray_column] == 'A': # if atom is in next ray path square self._ray_status = "Hit" # check for reflection elif (self._board[self._ray_row][self._ray_column + 1]) and ( self._board[self._ray_row][self._ray_column - 1]) == 'A': self._ray_row -= 1 self.vert_move_up(self._ray_row, self._ray_column) # check for detour (change direction to 'left' direction) elif self._board[self._ray_row][self._ray_column + 1] == 'A': self._ray_row -= 1 self.horiz_move_left(self._ray_row, self._ray_column) # check for detour (change direction to 'right' direction elif self._board[self._ray_row][self._ray_column - 1] == 'A': self._ray_row -= 1 self.horiz_move_right(self._ray_row, self._ray_column) def vert_move_up(self, ray_path_r, ray_path_c): """Accepts as parameters the current row and column of the ray path. Calculates the next square of a vertical ray path moving up and determines if there are any atoms resulting in a hit or detour. Adjusts ray status variable if there is a Hit or Exit. Returns nothing.""" self._ray_row = ray_path_r self._ray_column = ray_path_c while self._ray_status == "Play": # continue ray path determination while still in "play" # check for edge case reflection if ray_path_r == 9 and self._ray_row == 9: if (self._board[ray_path_r - 1][ray_path_c + 1]) or ( self._board[ray_path_r - 1][ray_path_c - 1]) == 'A': self._ray_row += 1 self._ray_status = "Exit" self._ray_row -= 1 # adjust ray path one square in 'up' direction # check for exit if self._ray_row == 0: self._ray_status = "Exit" # check for hit elif self._board[self._ray_row][ self. _ray_column] == 'A': # if atom is in next ray path square self._ray_status = "Hit" # check for reflection elif (self._board[self._ray_row][self._ray_column + 1]) and ( self._board[self._ray_row][self._ray_column - 1]) == 'A': # self._ray_row +=1 self.vert_move_down(self._ray_row, self._ray_column) # check for detour (change direction to 'left' direction) elif self._board[self._ray_row][self._ray_column + 1] == 'A': self._ray_row += 1 self.horiz_move_left(self._ray_row, self._ray_column) # check for detour (change direction to 'right' direction) elif self._board[self._ray_row][self._ray_column - 1] == 'A': self._ray_row += 1 self.horiz_move_right(self._ray_row, self._ray_column) def update_game_status(self): """Update the game status for game win or loss. Display message to screen.""" # update for a game loss, score below 0 if self._score <= 0: # check if game is over (score of 0 or less) game_loss = self._font.render( 'YOU LOSE! FINAL SCORE: ' + str(self._score), True, (0, 0, 0)) self._screen.blit(game_loss, (10, 750)) for atom in self._atom_list: self.draw_marker((0, 0, 0), atom) pygame.display.update() if len(self._atom_list ) == 0: # once all atoms are guessed, the game is over game_win = self._font.render( 'YOU WIN! FINAL SCORE: ' + str(self._score), True, (0, 0, 0)) self._screen.blit(game_win, (10, 750)) def adjust_score(self, row, column, color, atom_guess=None): """Accepts as parameters a row and column and assignment for the variable atom_guess (default argument of None). If the method call initiates from shoot_ray method, the default argument of None is used and decrements the player's score by 1 point if the entry/exit square has not already been used. If the method call originates from the guess_atom method, the atom_guess default argument is utilized and 5 points are deducted from the player's score if the guess is not a previous guess. Does not return anything.""" # decrement the score for a ray entry/exit point if atom_guess is None: if (row, column) not in self._ray_locations: self._ray_locations.append( (row, column, color)) # add to ray locations list self._gameB.update_ray_points( row, column ) # update the used ray location to game board visual self._score -= 1 # decrement the score by 1 point # decrement the score for an atom guess if atom_guess is True: if (row, column) not in self._wrong_atom_guesses: self._wrong_atom_guesses.append( (row, column)) # add to atom_guesses list self._score -= 5 # decrement the score by 5 points def guess_atom(self, row, column): """Accepts as parameters a row and column that represents the player's guess for an atom location. Returns True if the guess is correct. If the guess is incorrect, decrements the player's score and returns False.""" if (row, column) in self._atom_list: self._atom_list.remove( (row, column)) # if guess is in atom list, remove from list self._correct_atom_guesses.append( (row, column)) # add to correct atom guess list return True else: # if guess is incorrect, send the guess to adjust_score and include parameter 'True' to indicate atom guess self.adjust_score(row, column, None, True) return False def atoms_left(self): """Accepts no parameters and returns the number of atoms that haven't been guessed.""" atoms_left = self._font.render( 'Atoms Left: ' + str(len(self._atom_list)), True, (0, 0, 0)) self._screen.blit(atoms_left, (10, 670)) def get_score(self): current_score = self._font.render('Score: ' + str(self._score), True, (0, 0, 0)) self._screen.blit(current_score, (10, 610)) def calculate_square(self, coord): """Accepts as a parameter the x- y- coordinates of a mouse click and calculates the corredsponding row and column of the board game square. The x- coordinate is equivalent to the column and the y-coordinate is equivalent to the column""" col = (coord[0] // 60) row = (coord[1] // 60) return col, row def check_events(self): """Accepts no parameters. Checks the events of the pygame. Quits game when necessary. Otherwise, checks detection of mouseclick, gets the x-y coordinates of mouseclick, sends to function to calculate corresponding square on game board. Sends square to shoot_ray or guess_atom function.""" for event in pygame.event.get(): if event.type == pygame.QUIT: self._game_status = False # get coordinates of mouse click if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() pos_tup = self.calculate_square( pos) # change x-y coord to square of row, column row = pos_tup[0] column = pos_tup[1] if (row == 0 or row == 9) or (column == 0 or column == 9): self.shoot_ray(row, column) elif 0 < row < 9 and 0 < column < 9: self.guess_atom(row, column) def update_screen(self): """Update display screen with ray locations, atom location, current score, and atoms left to guess""" color_list = [(91, 109, 212), (237, 210, 159), (195, 124, 242), (182, 252, 251), (45, 51, 237), (247, 243, 2), (123, 31, 181), (237, 104, 2), (242, 124, 226), (62, 47, 135), (106, 33, 122)] self._screen.fill((240, 240, 240)) self._screen.blit(self.background, (0, 0)) self.get_score() self.atoms_left() for ray in self._ray_locations: self.draw_marker(color_list[ray[2]], (ray[0], ray[1])) for atom in self._wrong_atom_guesses: self.draw_marker((255, 0, 0), atom) for atom in self._correct_atom_guesses: self.draw_marker((20, 255, 3), atom) self.update_game_status() pygame.display.update() def draw_marker(self, color, pos): """Accepts a color as a parameter. Draws a marker at the indicated position (x-y coordinates)""" x_coord = pos[1] * 60 + 30 y_coord = pos[0] * 60 + 30 pygame.draw.circle(self._screen, color, (y_coord, x_coord), 20, 50) def get_game_status(self): return self._game_status
#################### # Load Configuration File #################### configuration_path = sys.argv[1] with open(configuration_path) as f: try: lines = f.readlines() board_size = lines[0].replace("\n", "").split(" ") ship_data_array = [] for x in lines[1:]: ship_data = x.replace("\n", "").split(" ") ship_data[1] = int(ship_data[1]) ship_data_array.append(tuple(ship_data)) board1 = GameBoard(board_size) board2 = GameBoard(board_size) except: print("Some error is in the configuration file. Please check the file.") sys.exit() #################### # Create Players and Ships #################### # player1_name = input("Player 1 please enter your name: ") player1 = Player(player1_name, board1) for shipData in ship_data_array: name = shipData[0]
from Board import GameBoard from HumanPlayer import HumanPlayer from DumbAI import DumbAI from SmartAI import SmartAI # draw board # while not game finished # get player move # redraw board # check for game over board = GameBoard() player1 = SmartAI("SmartAI", 'O', board) player2 = DumbAI("DumbAI", 'X') players = [player1, player2] for i in range(0, 100): print(i) board.reset() while board.game_over() == 0: for player in players: move = player.get_move() while board.submit_move(move) != 1: move = player.get_move() if board.game_over() != 0: if board.game_over() != 'TIE': player.Winner() break
def __init__(self, Player1, Player2): self.player1 = Player1 self.player2 = Player2 self.board = GameBoard() self.turn = 1
def checkwin(board): #check if someone has won curboard = 0 if isinstance(board,GameBoard): #typechecking is not working consistently. curboard = board elif isinstance(board, list): curboard = GameBoard(board) else: return 1 #SOMETHING WENT WRONG. if( #horizontals (curboard.is1(0,0) and curboard.is1(0,1) and curboard.is1(0,2)) or (curboard.is1(1,0) and board.is1(1,1) and curboard.is1(1,2)) or (curboard.is1(2,0) and curboard.is1(2,1) and curboard.is1(2,2)) or #verticals (curboard.is1(0,0) and curboard.is1(1,0) and curboard.is1(2,0)) or (curboard.is1(0,1) and curboard.is1(1,1) and curboard.is1(2,1)) or (curboard.is1(0,2) and curboard.is1(1,2) and curboard.is1(2,2)) or #diagonals (curboard.is1(0,0) and curboard.is1(1,1) and curboard.is1(2,2)) or (curboard.is1(0,2) and curboard.is1(1,1) and curboard.is1(2,0)) ): return 1 #1 wins elif ( #horizontals (curboard.is2(0,0) and curboard.is2(0,1) and curboard.is2(0,2)) or (curboard.is2(1,0) and curboard.is2(1,1) and curboard.is2(1,2)) or (curboard.is2(2,0) and curboard.is2(2,1) and curboard.is2(2,2)) or #verticals (curboard.is2(0,0) and curboard.is2(1,0) and curboard.is2(2,0)) or (curboard.is2(0,1) and curboard.is2(1,1) and curboard.is2(2,1)) or (curboard.is2(0,2) and curboard.is2(1,2) and curboard.is2(2,2)) or #diagonals (curboard.is2(0,0) and curboard.is2(1,1) and curboard.is2(2,2)) or (curboard.is2(0,2) and curboard.is2(1,1) and curboard.is2(2,0)) ): return 2 # 2 wins else: has_valid_move = False for i in range(3): for j in range(3): if not curboard.is1(i,j) and not curboard.is2(i,j): has_valid_move = True break; if has_valid_move: break; if has_valid_move: return 0 # keep going else: return -1 # draw.
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) BLACK = (0, 0, 0) RED = (250, 0, 0) BLUE = (0, 0, 250) WHITE = (250, 250, 250) done = False clock = pygame.time.Clock() cellStates = ["-", "O", "X"] colors = [WHITE, RED, BLUE] gb = GameBoard() p1 = Player("O") p2 = Persona("X", learning = False) players = [p1, p2] def get_cell(msx, msy): return (msx // 200, msy // 200) count = 0 # -------- Game Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): # User did something
class Persona: def copy_board(self, board): tempBoard = GameBoard() for i in range(3): for j in range(3): tempBoard.board[i][j] = board.board[i][j] return tempBoard.board def rev_board(self, board): d = {"-": "-", "O": "X", "X": "O"} s = "" for c in board: s = s + d[c] return s # this is where end of game / memory file stuff is def read_history(self, fileName): mem = dict() with open(fileName, "r") as file: split = [] # print(file.read()) for line in file.readlines(): # print(line) split = line.split(" ") split[2] = split[2][:-1] # print(split) mem[split[0]] = (float(split[1]), float(split[2])) file.close() # print(mem) return mem def write_history(self, fileName): file = open(fileName, "w") for brd in self.memory: file.write(brd) file.write(" ") file.write(str(self.memory[brd][0])[:7]) file.write(" ") file.write(str(self.memory[brd][1])) file.write("\n") file.close() def add_board_to_memory(self, board, w): if board in self.memory: self.memory[board] = ((self.memory[board][0] * self.memory[board][1] + w) / (self.memory[board][1] + 1), self.memory[board][1] + 1) else: self.memory[board] = (w, 1) rBoard = self.rev_board(board) d = {0: 1, 1: 0, self.TIEWORTH: self.TIEWORTH} if rBoard in self.memory: # self.memory[rBoard] = ((self.memory[rBoard][0] * self.memory[rBoard][1] + d[w]) / (self.memory[rBoard][1] + 1), self.memory[rBoard][1] + 1) t = True else: self.memory[rBoard] = (d[w], 1) # this is where in game memory is def add_board(self, brdStrng): if brdStrng not in self.boardStates: self.boardStates.append(brdStrng) def __init__(self, t): self.memory = self.read_history("history.txt") self.currBoard = GameBoard() self.boardStates = [GameBoard().to_string_one_line()] self.piece = t self.UNRESEARCHEDBOARDVALUE = .5 self.TIEWORTH = .7 # default operations of a "player" def Q(self, board, move): posBonus = 0 if board in self.memory: print("IN MEMORY") prevQ = self.memory[board][0] * math.log(self.memory[board][1], 10) posBonus = posBonus / self.memory[board][1] else: print("NEW MOVE") prevQ = self.UNRESEARCHEDBOARDVALUE return prevQ + posBonus def evaluate_option(self, board, move, temp): top = math.e ** (self.Q(board, move) / temp) return top def evaluate_options(self): Temperature = 5 currWinner = None editBoard = GameBoard() editBoard.board = self.copy_board(self.currBoard) score = 0 strng = "" prob = list() self.currBoard.print_board() for i in range(3): for j in range(3): if (self.currBoard.is_valid_move((i, j))): editBoard.board[i][j] = self.piece strng = editBoard.to_string_one_line() score = 0 prob.append(((i, j), self.evaluate_option(strng, (i, j), Temperature))) editBoard.board = self.copy_board(self.currBoard) bot = 0 for dub in prob: bot += dub[1] for dub in range(len(prob)): # print(prob[dub]) if dub == 0: prob[dub] = (prob[dub][0], prob[dub][1] / bot) else : prob[dub] = (prob[dub][0], prob[dub][1] / bot + prob[dub - 1][1]) rand = random() # print(prob) for dub in prob: if (rand < dub[1]): return dub[0] print("F**K") return (0, 0) def make_move(self): return self.evaluate_options() def update(self, board, pos): self.add_board(board.to_string_one_line()) if (board.to_string_one_line() != self.currBoard.to_string_one_line()): self.currBoard.board = self.copy_board(board) def end_game(self, board, w): d = {"-": self.TIEWORTH, "O": 1 if self.piece == w else 0, "X": 1 if self.piece == w else 0} # print(self.boardStates) # print("") self.add_board(board.to_string_one_line()) [self.add_board_to_memory(b, d[w]) for b in self.boardStates] self.boardStates = [GameBoard().to_string_one_line()]