def human_v_human(current_state, player1, player2): game_over = False while game_over is False: response = False while response is False: Ui.msg(BoardPresenter.display_terminal_board(current_state)) response = CommandLinePrompt.get_input( "Enter a number from 1-9: ") response = UserActions.make_move(current_state, response) BoardState.update_state(current_state, User.current_player, response) if EndStates.did_a_player_win(current_state, User.current_player, win_config.winning_combos): Ui.msg(BoardPresenter.display_terminal_board(current_state)) Ui.msg('Game Over: ' + User.current_player + ' WINS!') return True if EndStates.is_draw(current_state): Ui.msg('DRAW. GameOver') return True if User.current_player == player1: User.switch_current_user(User.current_player, player2) else: User.switch_current_user(User.current_player, player1)
def test_when_a_user_picks_an_occupied_spot_is_occupied_will_be_True(): game_board = Board() spot = 1 player1 = 'X' game_board.new_game() BoardState.update_state(game_board.board_state, player1, spot) assert SpotStates.is_occupied(game_board.board_state, spot) == True
def test_when_a_user_picks_a_spot_board_is_updated_with_their_spot(): game_board = Board() player1 = 'X' spot = 1 game_board.new_game() BoardState.update_state(game_board.board_state, player1, spot) assert game_board.board_state == ["X", "", "", "", "", "", "", "", ""]
def test_when_a_user_finishes_move_it_is_the_opponents_turn(): game_board = Board() game_board.new_game() BoardState.update_state(game_board.board_state, User.current_player, 1) player1 = User("X") player2 = User("O") User.switch_current_user(User.current_player, player2.symbol) assert User.current_player == "O"
def __init__(self, previous_state, new_state_raw_img, new_state_proc_img): self.previous_state = previous_state self.new_state_raw_img = new_state_raw_img self.new_state_proc_img = new_state_proc_img self.process_image() post_state = BoardState(self.new_state_proc_img) self.new_color_map = post_state.get_color_map()
def solve_board(board): '''Checks the current board and compares it to the perfect board. It then runs a while loop and the "create_children" until the current board matches the goal board.''' # show initial board configuration show_board(board) if not is_possible(board): print("Bro, not cool. Enter a valid board next time.") return q = Queue() q.put(BoardState(board, None)) goal_state = [ [1,2,3], [4,5,6], [7,8,0], ] visited = Queue() while True: current = q.push() visited.put(current) if current.board == goal_state: print('Board solved successfully!!') show_board(current.board) return a = create_children(current) for x in a: if q.instances(x) == 0 and visited.instances(x) == 0: q.put(x) elif q.instances(x) != 0: q[0].stepcost = 0
def reset(self, screen: pygame.Surface): screen.blit(self.background, (0, 0)) self.update_info(screen) self.current_player = 1 self.scores = { k: 0 for k in self.scores.keys() } self.board = BoardState()
def __init__(self, display_width: int = 900, display_height: int = 650): """ Defines the sizes, fonts and images in the game Surface :param display_width: :param display_height: """ N = 15 # 1 is user self.jorge = Jorge(2, GomokuUI.PLAYER_COUNT) self.jorges = [] self.board: BoardState = BoardState() self.current_player = 1 self.game_state: BoardState = BoardState() self.display_width: int = display_width self.display_height: int = display_height self.margin = 23 self.line_width = 1 self.cell_side = 40 self.box_width = (self.line_width + self.cell_side) * 4 self.box_height = (self.line_width + self.cell_side) * 3 self.title_font = pygame.font.SysFont('Calibri', 24) self.score_font = pygame.font.SysFont('Calibri', 20) self.board_width = self.line_width * N + self.cell_side * (N - 1) res = './res' self.background = pygame.image.load(f'{res}/board.png') self.panel = pygame.image.load(f'{res}/panel.png') self.pieces: List[pygame.Surface] = [] for i in range(GomokuUI.PLAYER_COUNT): self.pieces.append(pygame.image.load(f'{res}/p{i}.png')) self.scores = { str(i): 0 for i in range(1, GomokuUI.PLAYER_COUNT + 1) } self.startx = 0 self.starty = 0 self.infox = 3 * self.margin + self.board_width self.info1_y = 100 self.info2_y = 263 self.info_width = 165 self.info_height = 125 self.bg_width = (display_width - self.infox) - 1 self.piece_size = 29 self.box_line_width = 4
def __init__(self, opponent_model=None, agent_piece=BLACK): # since black always starts self.state = BoardState(generate_empty_board(DIM, DIM), BLACK): # contains the piece type that the agent will use self.agent_piece = agent_piece # If an opponent model was provided, use that. If not, just use a # model that makes random choices. if opponent_model == None: print("Using random opponent model.") self.opponent_model = RandomModel(self.action_space) else: print("Using provided opponent model.") self.opponent_model = opponent_model self.reset()
class GameRunner: def __init__(self, size=19, depth=2): self.size = size self.depth = depth self.finished = False self.restart() def restart(self, player_index=-1): self.is_max_state = True if player_index == -1 else False self.state = BoardState(self.size) self.ai_color = -player_index def play(self, i, j): position = (i, j) if self.state.color != self.ai_color: return False if not self.state.is_valid_position(position): return False self.state = self.state.next(position) self.finished = self.state.is_terminal() return True def aiplay(self): # import time # t = time.time() if self.state.color == self.ai_color: return False, (0, 0) move, value = get_best_move(self.state, self.depth, self.is_max_state) self.state = self.state.next(move) self.finished = self.state.is_terminal() # print(time.time() - t) return True, move def get_status(self): board = self.state.values return { 'board': board.tolist(), 'next': -self.state.color, 'finished': self.finished, 'winner': self.state.winner, # 'debug_board': self.state.__str__() }
def computer_v_computer(current_state, player1, player2): game_over = False while game_over is False: Ui.msg(BoardPresenter.display_terminal_board(current_state)) computers_move = Ai.make_move(current_state) BoardState.update_state(current_state, User.current_player, computers_move) if EndStates.did_a_player_win(current_state, User.current_player, win_config.winning_combos): Ui.msg(BoardPresenter.display_terminal_board(current_state)) Ui.msg('Game Over: ' + User.current_player + ' WINS!') return True if EndStates.is_draw(current_state): Ui.msg('DRAW. GameOver') return True if User.current_player == player1: User.switch_current_user(User.current_player, player2) else: User.switch_current_user(User.current_player, player1)
def minimax(self, state: BoardState, alpha: int, beta: int, depth: int, jorge: int) -> Tuple[Optional[Tuple[int, int]], int]: if depth == 0: return None, state.score(jorge, self.jorge_count) best_play: Tuple[int, int] = None new_depth = depth - 1 is_my_turn = jorge == self.number next_jorge = 1 if jorge == self.jorge_count else jorge + 1 for pos, st in state.possible_plays(next_jorge): _, val = self.minimax(st, alpha, beta, new_depth, next_jorge) if best_play is None: best_play = pos if is_my_turn: if val > alpha: best_play = pos alpha = val else: if val < beta: best_play = pos beta = val if alpha > beta: break return best_play, (alpha if is_my_turn else beta)
def play_game(agent1, agent2): board = BoardState() while True: x_move = agent1.act(board) if not board.is_legal_move(x_move): agent1.reward(-10) agent2.reward(1) return -10, 1 if board.put_x(x_move): agent1.reward(1) agent2.reward(-1) return 1, -1 if board.is_over(): agent1.reward(0) agent2.reward(0) return 0, 0 o_move = agent2.act(board) if not board.is_legal_move(o_move): agent1.reward(1) agent2.reward(-10) return 1, -10 if board.put_o(o_move): agent1.reward(-1) agent2.reward(1) return -1, 1 if board.is_over(): agent1.reward(0) agent2.reward(0) return 0, 0
def restart(self, player_index=-1): self.is_max_state = True if player_index == -1 else False self.state = BoardState(self.size) self.ai_color = -player_index
class Go(gym.Env): metadata = {'render.modes': ['human']} # 2 since we can either pass or not pass action_space = spaces.Tuple(spaces.Discrete(2), spaces.Box(low=-1, high=1, shape=(DIM**2,), dtype=np.float32)) # allowed values are 0 - 2 to represent BLACK, WHITE, EMPTY states observation_space = spaces.Tuple(spaces.Discrete(2), spaces.Box(low=0, high=2, shape=(DIM**2,), dtype=np.int8)) def __init__(self, opponent_model=None, agent_piece=BLACK): # since black always starts self.state = BoardState(generate_empty_board(DIM, DIM), BLACK): # contains the piece type that the agent will use self.agent_piece = agent_piece # If an opponent model was provided, use that. If not, just use a # model that makes random choices. if opponent_model == None: print("Using random opponent model.") self.opponent_model = RandomModel(self.action_space) else: print("Using provided opponent model.") self.opponent_model = opponent_model self.reset() def _makeOpponentMove(self): action, _ = self.opponent_model.predict(self.state.board.flatten()) return get_move_from_array(action) def step(self, action): # Get score before action for diff (self - opponent) prev_score = self.state.score(self.agent_piece) - self.state.score(not self.agent_piece) row, col = get_move_from_array(action) # If this returns None due to invalid placement, you lose if self.state.place(row, col) is None: return self.state.board.flatten(), ILLEGAL_MOVE_REWARD, True, {'IllegalMove': True} # Then choose the square opponent will play on opp_row, opp_col = self._makeOpponentMove() # Check legality; if it's illegal opponent loses. if self.state.place(opp_row, opp_col) is None: return self.state.board.flatten(), -1 * ILLEGAL_MOVE_REWARD, True, {'IllegalMove': 'opponent'} # You get the difference between new score and previous score new_score = self.state.score(self.agent_piece) - self.state.score(not self.agent_piece) return self.state.flatten(), new_score - prev_score, False, {} def reset(self): self.counter = 0 # counts the pieces on the board self.state = np.array([[EMPTY for i in range(3)] for s in range(3)]) # If our piece is O, this means the opponent is X and they should # go first. # We put this here because the starting environment which the agent # first looks at should already have the opponent's move. if self.agent_piece == O: self._makeOpponentMove() return self.state.flatten() def render(self): stateToPic = { O: "O", X: "X", EMPTY: ".", } for i in range(3): for j in range(3): print(stateToPic[self.state[i][j]], end = " ") print("")
from flask import Flask, render_template, request, jsonify from board import BoardState from mtcs import MonteCarloTreeSearch app = Flask(__name__) board = BoardState() @app.route('/') def index(): return render_template('index.html') @app.route('/move', methods=['POST']) def move(): x = int(request.form['x']) y = int(request.form['y']) if x == 100 and y == 100: board.pass_move() board.pass_move() winner = board.get_winner() message = 'END OF GAME. ' if winner == 1: message += 'BLACK PLAYER WINS' else: message += 'WHITE PLAYER WINS' else: message = board.move((y, x)) if message == 'OK': bot = MonteCarloTreeSearch(board)
def main(argv): b = BoardState() b.initialize_from_file("../data/test_init.json") ''' for i in range(b.DEFAULT_BOARD_SIZE): for j in range(b.DEFAULT_BOARD_SIZE): print("({}, {}) -> {}".format(i, j, b._board[i][j])) ''' for player in [BoardState.Player.WHITE, BoardState.Player.BLACK]: b._next_player = player total_moves = len(b.get_all_legal_moves()) print("Player {}, {} possible moves.".format(player, total_moves)) b.print_board() # Check captures moves = list() moves.append(Move(Coord(0, 3), Coord(2, 3), BoardState.Player.BLACK)) moves.append(Move(Coord(4, 4), Coord(2, 4), BoardState.Player.WHITE)) moves.append(Move(Coord(3, 0), Coord(3, 3), BoardState.Player.BLACK)) moves.append(Move(Coord(5, 4), Coord(4, 4), BoardState.Player.WHITE)) moves.append(Move(Coord(3, 3), Coord(3, 4), BoardState.Player.BLACK)) for move in moves: print("") print("--------------------------------------------------------") print("") # print(str(move)) b.process_move(move) b.print_board()
def play_against(agent): print( 'Please notice that it takes approximately a zillion games for agent to become better' ) while True: debug = False input_debug = input( 'Do you want to see probability distribution ("thoughts") of AI? y/n:' ) if input_debug == 'y': debug = True break elif input_debug == 'n': break while True: # game series print_line() board = BoardState() if random() > 0.5: print('You won a toss - place X!') while True: # one game board.render() x_move = int(input('Your move is... ')) if not board.is_legal_move(x_move): print('This is illegal move - you {}lost{}!'.format( COLOR_RED, COLOR_END)) break if board.put_x(x_move): print('Congratulations - you {}won{}!'.format( COLOR_GREEN, COLOR_END)) break if board.is_over(): print('That\'s it - game is over with {}draw{}!'.format( COLOR_YELLOW, COLOR_END)) break if debug: board.render_distribution(agent.get_distribution(board)) o_move = agent.act(board) if not board.is_legal_move(o_move): print('AI made illegal move - so you {}won{}!'.format( COLOR_GREEN, COLOR_END)) break if board.put_o(o_move): print( 'AI finished his combination and you {}lost{}!'.format( COLOR_RED, COLOR_END)) break if board.is_over(): print('That\'s it - game is over with {}draw{}!'.format( COLOR_YELLOW, COLOR_END)) break else: print('You lost a toss - AI will now place X!') while True: # one game if debug: board.render_distribution(agent.get_distribution(board)) x_move = agent.act(board) if not board.is_legal_move(x_move): print('AI made illegal move - so you {}won{}!'.format( COLOR_GREEN, COLOR_END)) break if board.put_x(x_move): print( 'AI finished his combination and you {}lost{}!'.format( COLOR_RED, COLOR_END)) break if board.is_over(): print('That\'s it - game is over with {}draw{}!'.format( COLOR_YELLOW, COLOR_END)) break board.render() o_move = int(input('Your move is... ')) if not board.is_legal_move(o_move): print('This is illegal move - you {}lost{}!'.format( COLOR_RED, COLOR_END)) break if board.put_o(o_move): print('Congratulations - you {}won{}!'.format( COLOR_GREEN, COLOR_END)) break if board.is_over(): print('That\'s it - game is over with {}draw{}!'.format( COLOR_YELLOW, COLOR_END)) break
def swap(board,x,y,x1,y1): '''Swaps two elements.''' board1 = copy.deepcopy(board.board) board1[x][y], board1[x1][y1] = board1[x1][y1], board1[x][y] return BoardState(board1, board)
import sys from collections import OrderedDict from IPython import embed from board import BoardState b = BoardState(sys.argv[1]) sqrs = b.squares green_squares = [ sqrs[2][1], sqrs[2][3], sqrs[2][5], sqrs[2][7], sqrs[3][0], sqrs[3][2], sqrs[3][4], sqrs[3][6], sqrs[4][1], sqrs[4][3], sqrs[4][5], sqrs[4][7], sqrs[5][0], sqrs[5][2], sqrs[5][4], sqrs[5][6] ] white_squares = [ sqrs[2][0], sqrs[2][2], sqrs[2][4], sqrs[2][6], sqrs[3][1], sqrs[3][3], sqrs[3][5], sqrs[3][7], sqrs[4][0], sqrs[4][2], sqrs[4][4], sqrs[4][6], sqrs[5][1], sqrs[5][3], sqrs[5][5], sqrs[5][7] ] black_pieces = sqrs[0] + sqrs[1] green_pixels = [img.hsv.flatten() for img in green_squares] white_pixels = [img.hsv.flatten() for img in white_squares] black_pixels = [img.hsv.flatten() for img in black_pieces] # Calculate Green Pixels green = {'h': {}, 's': {}, 'v': {}} for pixel in green_pixels: