def test_to_win(): player2 = Player('O') g = Game((Player('X'), player2), to_win=1) g.board.grid[0][0] = 'O' assert g.check_winner() is player2
def main(): """ Play a game! """ g = Game() g.printState() player1 = g.players[0] player2 = g.players[1] win_counts = [0, 0, 0] # [p1 wins, p2 wins, ties] exit = False while not exit: while not g.finished: g.nextMove() g.findFours() g.printState() if g.winner == None: win_counts[2] += 1 elif g.winner == player1: win_counts[0] += 1 elif g.winner == player2: win_counts[1] += 1 printStats(player1, player2, win_counts) exit = True
def test_game_column_size(description, column, size): game = Game(height=3, width=3) game._columns = [ [], [Piece.BLUE], [Piece.RED, Piece.BLUE], ] assert game.get_column_size(column=column) == size
def test_game_piece_at_position(description, row, column, piece): game = Game(height=3, width=3) game._columns = [ [], [Piece.BLUE], [Piece.RED, Piece.BLUE], ] assert game.get_piece_at_position(row=row, column=column) == piece
def test_game_too_full(description, height, width, piece, column): game = Game(height=height, width=width) game._columns = [[], [Piece.BLUE, Piece.RED]] with pytest.raises(Exception) as e: game.put_piece_in_column(piece=piece, column=column) assert ( e.msg == f"This piece can't be added to this column {column} since it is already full" )
def test_game_column_beyond_range(description, height, width, piece, column): game = Game(height=height, width=width) game._columns = [[], []] with pytest.raises(Exception) as e: game.put_piece_in_column(piece=piece, column=column) assert ( e.msg == f"column needs to be between 0 and {game._width}, column is {column}" )
def test_connect_in_direction(): game = Game(height=4, width=4) game._columns = [ [], [Piece.BLUE], [Piece.BLUE, Piece.BLUE, Piece.BLUE, Piece.BLUE], [], ] assert connect_in_direction(game=game, start=(0, 2), direction=(1, 0)) game = Game(height=4, width=4) game._columns = [ [Piece.BLUE], [Piece.BLUE, Piece.BLUE], [Piece.BLUE, Piece.BLUE, Piece.BLUE], [Piece.BLUE, Piece.BLUE, Piece.BLUE, Piece.BLUE], ] assert connect_in_direction(game=game, start=(2, 2), direction=(1, 1)) game = Game(height=4, width=4) game._columns = [ [Piece.BLUE, Piece.BLUE, Piece.BLUE, Piece.BLUE], [Piece.BLUE, Piece.BLUE, Piece.BLUE], [Piece.BLUE, Piece.BLUE], [Piece.BLUE], ] assert connect_in_direction(game=game, start=(0, 3), direction=(1, -1))
def play_game(self, on_move=None, verbose=False): """ explore another round of the game verbose: bool show the process of this game returns: list[np.array], list[int] the state of the playing field before the move and the move """ c4 = Game( self.height, self.width, on_move=np.random.choice([-1, 1]) if on_move is None else on_move) state_list = [] move_list = [] # generate training data through two AIs playing against each other while c4.winner is None: # and len(c4.possibleMoves()) > 0: color = c4.on_move move, meta = self.ais[color].next_exploring_move( c4, epsilon=self.epsilon) state_list.append(np.copy(c4.field) * color) print_cond(c4.field, cond=verbose) c4.play(move) print_cond("move:", move, " (explore=", meta["explore"], ") ends=", c4.winner, cond=verbose) move_list.append(move) if c4.winner in (-1, 0, 1): break return state_list, move_list
def test_game(self, enemy="opp", verbose=False, player1_starts=True): c4 = Game(self.height, self.width, on_move=1 if player1_starts else -1) while c4.winner is None: if player1_starts: move, q_max = c4.best_next_move(self.qnet) c4.play(move) print_cond(c4.field, "\nplayer 1 (qnet) played", move, cond=verbose) player1_starts = True if c4.winner is None: if enemy == "qnet": move, q_max = c4.best_next_move(self.qnet) elif enemy == "opp": move = self.ais[-1].next_move(c4) elif enemy == "rand": move = np.random.choice(c4.possible_moves()) elif enemy == "human": print("Current Field state:\n", c4.field) move = int(input("Your move: " + str(c4.possible_moves()))) print_cond("player -1", enemy, "played", move, cond=verbose) c4.play(move) return c4.winner
def launch(self): # Launch Game and destroy configuration window connect = self._connect.get() width = self._width.get() height = self._height.get() self._window.destroy() players = [] for player in self._players: players.append(Player(player.id, player.entry.get(), player.color)) Display(Game(players, width, height, connect))
def trainGame(self, state_list, move_list, verbose=False): net_losses = [] for i in range(len(state_list) - 1, -1, -1): move = move_list[i] c4 = Game(height=self.height, width=self.width, field=state_list[i], on_move=1) net_input = Game.create_net_input(c4.field, move) net_output = self.qnet.eval( net_input) # calculate now before moves are played Q(s,a) print_cond("we are player 1 in state:\n", c4.field, cond=verbose) # next state but already inverted, we are player 1 c4.play(move) print_cond("and do action ", move, "which resulted end=", c4.winner, "\n", c4.field, cond=verbose) q_future = 0 reward = self.rewards[c4.winner] if c4.winner is None: # opponent plays random move, result also counts directly to reward assert c4.on_move == -1 move = self.ais[-1].next_move(c4) c4.play(move) reward = self.rewards[c4.winner] if c4.winner is None: assert c4.on_move == 1 move, q_max = c4.best_next_move(self.qnet) q_future = q_max net_target = np.array([reward + self.gamma * q_future ]).reshape(1, 1) print_cond("==> Q(s,a)=", net_output, cond=verbose) print_cond("==> r=", reward, " Q_=", q_future, cond=verbose) net_loss = self.qnet.train(net_input, net_target) net_losses.append(net_loss) return net_losses
def test_Player(): player1 = Player('X') player2 = Minimax('O', depth=2) g = Game((player1, player2)) g.run()
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. from connect4 import ( Game, Player, ) from random_rollouts import RandomRollout from mcts import MCTS # Enable this to have a game of randomrollout against itself # game = Game(RandomRollout(),RandomRollout()) # Enable this to play against RandomRollout yourself # game = Game(Player(), RandomRollout()) # Enable this to have MCTS-10 against MCTS-1000 # game = Game(MCTS(walks=10),MCTS(walks=1000)) # MCTS vs random rollouts game = Game(RandomRollout(),MCTS()) game.play_game()
def test_game(description, height, width, piece, column): game = Game(height=height, width=width) game.put_piece_in_column(piece=piece, column=column) assert game._columns == [[], [piece]]
def main(): g = Game() g.printState() player1 = g.players[0] player2 = g.players[1] win_counts = [0, 0, 0] # [p1 wins, p2 wins, ties] exit = False logger = logging.getLogger('mylogger') logger.setLevel(logging.DEBUG) fh = logging.FileHandler('test.log') ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) stepNum = 0 while not exit: logger.info("GAME START") while not g.finished: logger.info("STEP{0}".format(stepNum)) g.nextMove() stepNum += 1 g.findFours() g.printState() if g.winner == None: win_counts[2] += 1 elif g.winner == player1: win_counts[0] += 1 elif g.winner == player2: win_counts[1] += 1 printStats(player1, player2, win_counts) while True: logger.info("GAME OVER") play_again = str(input("Would you like to play again? ")) if play_again.lower() == 'y' or play_again.lower() == 'yes': print("start time:" + str(time.time())) g.newGame() g.printState() break elif play_again.lower() == 'n' or play_again.lower() == 'no': print("Thanks for playing!") exit = True break else: print("I don't understand... "),
def test_check_winner(): n_rows = 20 n_cols = 10 to_win = 5 player1 = Player('X') player2 = Player('O') g = Game((player1, player2), n_rows=n_rows, n_cols=n_cols, to_win=to_win) assert g.check_winner() is None # check horizontal win for col in range(g.to_win): g.board.insert(2 + col, 'X') assert g.check_winner() is player1 # check vertical win g = Game((player1, player2), n_rows=n_rows, n_cols=n_cols, to_win=to_win) for _ in range(g.to_win): g.board.insert(0, 'O') assert g.check_winner() is player2 # check positive diagonal win g = Game((player1, player2), n_rows=n_rows, n_cols=n_cols, to_win=to_win) for i in range(g.to_win): g.board.grid[g.board.n_rows - 1 - i][i] = 'O' assert g.check_winner() is player2 # check negative diagonal win g = Game((player1, player2), n_rows=n_rows, n_cols=n_cols, to_win=to_win) for i in range(g.to_win): g.board.grid[i][i] = 'O' assert g.check_winner() is player2
from connect4 import Game if __name__ == '__main__': game = Game() game.setup() verdict = 0 while verdict == 0: game.displayBoard() verdict = game.move() game.displayBoard() game.endGame(verdict)
def test_connect4(description, columns, row, column, connect4): game = Game(height=4, width=4) game._columns = columns assert game._connect4(column=0, row=0) is connect4