Exemple #1
0
def main_human():
    game = Game(players=[
        HumanPlayer(name="Fedor", symbol_class=X),
        HumanPlayer(name="Julia", symbol_class=O),
    ])
    Game(players="Bentsi")
    game.run()
Exemple #2
0
def main():
    player_first = ''
    player_second = ''
    print("Меню".center(32, '*'))
    print("1. знакомится с правилами игры")
    print("2. Играть с другим человеком")
    print("3. Играть с роботом")
    print("4. посмотреть игру двух роботов")
    print("5. Для выхода из программы нажмите '-1' ")
    while True:
        choice_you = choice()
        if choice_you == 1:
            with open("tictactoe/rules_of_the_game", "r", encoding='utf-8') as file:
                rules_the_game = file.read()
                print(rules_the_game)
                return 0
        elif choice_you == 2:
            player_first, player_second = main_human()
        elif choice_you == -1:
            return 0
        elif choice_you == 3:
            player_first, player_second = main_robotic_human()
        elif choice_you == 4:
            player_first, player_second = main_robotic()
        game = Game(player_one=player_first, player_two=player_second)
        game.run()
Exemple #3
0
 def __init__(self):
     self.game = Game()
     self.score = {
         "X": +1,
         "O": -1,
         "tie": 0
     }
 def setUp(self):
     self.mock_cli_input = MockCLIInput()
     self.mock_cli_output = MockCLIOutput()
     self.ui = UIWrapper(self.mock_cli_output)
     self.rules = Rules()
     self.game = Game(Player("X", self.mock_cli_input, self.ui), Player("O", MockCLIInput(), self.ui), self.ui, Validations(), self.rules, Board())
     self.engine = create_engine(TEST_DB_ADDRESS)
     self.db = Database(self.engine)
Exemple #5
0
    def test_is_won_in_columns(self):
        game = Game(None, None)
        game.board.clean_marks()
        self.assertFalse(game.is_won())

        game.board.mark_cell(3, 1)
        game.board.mark_cell(6, 1)
        game.board.mark_cell(9, 1)
        self.assertTrue(game.is_won())
Exemple #6
0
    def test_is_won_in_diagonals_from_left_to_right_diagonal(self):
        game = Game(None, None)
        game.board.clean_marks()
        self.assertFalse(game.is_won())

        game.board.mark_cell(1, 1)
        game.board.mark_cell(5, 1)
        game.board.mark_cell(9, 1)
        self.assertTrue(game.is_won())
Exemple #7
0
 def test_ask_cells_for_tied_game(self):
     selected_cells = [1, 5, 9, 2, 8, 7, 3, 6, 4]
     game = Game(lambda _: selected_cells.pop(), self.print_function)
     game.board.clean_marks()
     game.ask_cells()
     self.assertFalse(game.is_won())
     expected_printed_messages = ' The game is over and this is a tie!!'
     messages = self.returned_string.split('\n')
     win_message = messages[len(messages) - 2]
     self.assertEqual(win_message, expected_printed_messages)
Exemple #8
0
 def test_run_3(self):
     input_stream = StringIO(
         'John Doe\nMichael Doe\n2\n6\n2\n8\n5\n4\n7\n3\n1\n9\n')
     output_stream = StringIO()
     game = Game(input_stream=input_stream, output_stream=output_stream)
     output_stream.truncate(0)
     output_stream.seek(0)
     game.run()
     with open(join(dirname(__file__), 'sample2.txt')) as file:
         sample = file.read()
     self.assertEqual(output_stream.getvalue(), sample)
Exemple #9
0
    def test_ask_cells_for_won_game(self):
        game = Game(lambda n: 3, self.print_function)
        game.board.clean_marks()
        game.board.mark_cell(1, 1)
        game.board.mark_cell(2, 1)

        game.ask_cells()
        self.assertTrue(game.is_won())
        expected_printed_messages = ' Player 1 wins the game!!'
        messages = self.returned_string.split('\n')
        win_message = messages[len(messages) - 2]
        self.assertEqual(win_message, expected_printed_messages)
Exemple #10
0
    def test_get_selected_cell_with_marked_cell_selection(self):
        expected_option = 2
        selected_options = [2, 1]
        game = Game(lambda n: selected_options.pop(), self.print_function)
        game.board.clean_marks()
        game.board.mark_cell(1, 1)
        option = game.get_selected_cell()
        self.assertEqual(option, expected_option)

        expected_printed_messages = 'Player 1s turn\n'
        expected_printed_messages += 'The cell is already marked, please select another one\n'
        expected_printed_messages += 'Player 1s turn\n'
        self.assertEqual(self.returned_string, expected_printed_messages)
Exemple #11
0
    def beginTeaching(self, episodes):
        """ Loop through game iterations with a teaching agent. """
        teacher = Teacher()
        # Train for alotted number of episodes
        while self.games_played < episodes:
            game = Game(self.agent, teacher=teacher)
            game.start()
            self.games_played += 1
            # Monitor progress
            if self.games_played % 1000 == 0:
                print("Games played: %i" % self.games_played)

        plot_agent_reward(self.agent.rewards)
 def beginTeaching(self, episodes):
     """ Loop through game iterations with a teaching agent. """
     teacher = Teacher()
     # Train for alotted number of episodes
     while self.games_played < episodes:
         game = Game(self.agent, teacher=teacher)
         game.start()
         self.games_played += 1
         # Monitor progress
         if self.games_played % 1000 == 0:
             print("Games played: %i" % self.games_played)
     # save final agent
     self.agent.save(self.path)
Exemple #13
0
 def test_run_2(self):
     input_stream = StringIO('John Doe\nMichael Doe\n2\n1')
     output_stream = StringIO()
     game = Game(n=1,
                 input_stream=input_stream,
                 output_stream=output_stream)
     output_stream.truncate(0)
     output_stream.seek(0)
     game.run()
     self.assertEqual(
         output_stream.getvalue(),
         ' 1 \n\n' + 'John Doe, choose a box to place an \'X\' into:\n>> \n'
         'That is not a valid box.\n'
         'John Doe, choose a box to place an \'X\' into:\n>> \n\n'
         ' X \n\n' + 'Congratulations John Doe! You have won.\n')
 def playIncompleteGameAIPlaysSecond(self):
     ai_game = Game(Player("X", self.mock_cli_input, self.ui),
                    AIMinimax("O", Rules()), self.ui, Validations(),
                    Rules(), Board())
     ai_game._board.make_move(1, self.game._player1._symbol)
     ai_game._board.make_move(3, self.game._player2._symbol)
     self.db.add_game_to_database(ai_game)
Exemple #15
0
    def test_print_winner_message(self):
        game = Game(None, self.print_function)
        game.print_winner_message()
        self.assertEqual(self.returned_string, ' Player 1 wins the game!!\n')

        game.switch_player()
        self.returned_string = ''
        game.print_winner_message()
        self.assertEqual(self.returned_string, ' Player 2 wins the game!!\n')
Exemple #16
0
 def test_init(self):
     input_stream = StringIO('John Doe\nMichael Doe\n')
     output_stream = StringIO()
     game = Game(input_stream=input_stream, output_stream=output_stream)
     self.assertEqual(game.names, ['John Doe', 'Michael Doe'])
     self.assertEqual(
         output_stream.getvalue(),
         'Enter name for Player 1:\n>> \nEnter name for Player 2:\n>> \n')
Exemple #17
0
    def recreate_game_object(self, saved_game):
        cli_input = CLIInput()
        ui = UIWrapper(CLIOutput())
        board_obj = self.create_board_object(saved_game)
        player_x_obj = self.create_player_x_object(saved_game, cli_input, ui)
        player_o_obj = self.create_player_o_object(saved_game, cli_input, ui)

        game_obj = Game(player_x_obj, player_o_obj, ui, Validations(), Rules(), board_obj, saved_game.id)
        return game_obj
Exemple #18
0
    def beginTeaching(self, episodes):
        """ Loop through game iterations with a teaching agent. """
        teacher = Teacher()
        # Train for alotted number of episodes
        while self.games_played < episodes:
            game = Game(self.agent, teacher=teacher)
            game.start()
            self.games_played += 1
            # Monitor progress
            if self.games_played % 1000 == 0:
                print("Games played: %i" % self.games_played)

        plot_agent_reward(self.agent.rewards)

        if args.agent_type == "q":
            self.agent.save_agent(self.qlearner_agent_path)
        elif args.agent_type == "s":
            self.agent.save_agent(self.sarsa_agent_path)
 def setUp(self):
     self.mock_cli_input = MockCLIInput()
     self.output = MockCLIOutput()
     self.player1 = Player("X", MockCLIInput(), self.output)
     self.player2 = Player("O", MockCLIInput(), self.output)
     self.rules = Rules()
     self.board = Board()
     self.game = Game(Player("X", self.mock_cli_input, self.output),
                      Player("O", MockCLIInput(), self.output), self.output,
                      Validations(), self.rules, self.board)
     self.engine = create_engine(TEST_DB_ADDRESS)
     self.db = Database(self.engine)
Exemple #20
0
    def beginPlaying(self):
        """ Loop through game iterations with a human player. """
        print("Welcome to Tic-Tac-Toe. You are 'X' and the computer is 'O'.")

        def play_again():
            print("Games played: %i" % self.games_played)
            while True:
                play = input("Do you want to play again? [y/n]: ")
                if play == 'y' or play == 'yes':
                    return True
                elif play == 'n' or play == 'no':
                    return False
                else:
                    print("Invalid input. Please choose 'y' or 'n'.")

        while True:
            game = Game(self.agent)
            game.start()
            self.games_played += 1
            if not play_again():
                print("OK. Quitting.")
                break
Exemple #21
0
    def beginPlaying(self):
        """ Loop through game iterations with a human player. """
        print("Welcome to Tic-Tac-Toe. You are 'X' and the computer is 'O'.")

        def play_again():
            print("Games played: %i" % self.games_played)
            while True:
                play = input("Do you want to play again? [y/n]: ")
                if play == 'y' or play == 'yes':
                    return True
                elif play == 'n' or play == 'no':
                    return False
                else:
                    print("Invalid input. Please choose 'y' or 'n'.")

        while True:
            game = Game(self.agent)
            game.start()
            self.games_played += 1
            if not play_again():
                print("OK. Quitting.")
                break
Exemple #22
0
    def setUp(self):
        app.testing = True
        self.data = {
            'player': 'x',
            'opponent': 'o',
            'winner': False,
            'board': {
                'top-left': {
                    'value': ''
                },
                'top-center': {
                    'value': ''
                },
                'top-right': {
                    'value': ''
                },
                'middle-left': {
                    'value': ''
                },
                'middle-center': {
                    'value': ''
                },
                'middle-right': {
                    'value': ''
                },
                'bottom-left': {
                    'value': ''
                },
                'bottom-center': {
                    'value': ''
                },
                'bottom-right': {
                    'value': ''
                },
            }
        }

        self.game = Game(self.data)
def main():
    player_first = ""
    player_second = ""
    print("Menu".center(32, ' '))
    print("1. Check rules of the game" + "\n" + "2. Human VS Human" + "\n" +
          "3. Human VS Robot" + "\n" + "4. Robot VS Robot" + "\n" +
          "5. To exist the game push the '5' ")
    while True:
        your_choice = choice()
        if your_choice == 1:
            with open("rules_of_the_game.txt", "r", encoding='utf-8') as f:
                rules_of_the_game = f.read()
                print(rules_of_the_game)
                return main()
        elif your_choice == 2:
            player_first, player_second = main_human()
        elif your_choice == 3:
            player_first, player_second = main_robot_human()
        elif your_choice == 4:
            player_first, player_second = main_robots()
        elif your_choice == 5:
            return 0
        game = Game(player_one=player_first, player_two=player_second)
        game.run()
 def setUp(self):
     self.engine = create_engine(TEST_DB_ADDRESS)
     self.db = Database(self.engine)
     self.mock_cli_input = MockCLIInput()
     self.mock_cli_output = MockCLIOutput()
     self.ui = UIWrapper(self.mock_cli_output)
     self.game = Game(Player("X", self.mock_cli_input, self.ui),
                      Player("O", self.mock_cli_input, self.ui), self.ui,
                      Validations(), Rules(), Board())
     self.setup_game = SetupGame(self.mock_cli_input, self.mock_cli_output,
                                 self.engine)
     meta = MetaData(bind=self.engine)
     self.game_table = Table("saved_games",
                             meta,
                             autoload=True,
                             autoload_with=self.engine)
Exemple #25
0
def main():
    print("pycrosses, v1.0")
    try:
        while True:
            while True:
                try:
                    human_players = int(input("How many human players? [2]> "))
                    human_players = human_players if human_players <= 2 else 2
                    break
                except ValueError:
                    print("Not a number")

            player_names = [
                input(f"Enter player {i + 1} name> ")
                for i in range(human_players)
            ]

            game = Game(players=[])
            symbols = cycle([X, O])
            for v in player_names:
                game.add_player(HumanPlayer(name=v,
                                            symbol_class=next(symbols)))

            for _ in range(2 - human_players):
                game.add_player(
                    RoboticPlayer(symbol_class=next(symbols), gamestate=game))

            game.run()
            answer = input("Play again? y/n> ")
            if (answer == 'y'):
                continue
            break
    except EOFError:
        exit(1)
    except KeyboardInterrupt:
        exit(1)
Exemple #26
0
 def test_print_game_instructions(self):
     game = Game(None, self.print_function)
     game.print_game_instructions()
     printed_messages = self.returned_string.split('\n')
     expected_message = 'Select the number of the cell that you want to mark'
     self.assertEqual(printed_messages[0], expected_message)
Exemple #27
0
 def test_print_tied_game_message(self):
     game = Game(None, self.print_function)
     game.print_tied_game_message()
     self.assertEqual(self.returned_string,
                      ' The game is over and this is a tie!!\n')
import tensorflow as tf
import numpy as np
from collections import deque
from tictactoe.deep_q_network import DeepQNetwork
from tictactoe.game import Game

# initialize game env
env = Game()

# initialize tensorflow
sess1 = tf.Session()
sess2 = tf.Session()
optimizer = tf.train.RMSPropOptimizer(learning_rate=0.0001, decay=0.9)
writer1 = tf.train.SummaryWriter("logs/value_network1", sess1.graph)
writer2 = tf.train.SummaryWriter("logs/value_network2", sess2.graph)

# prepare custom tensorboard summaries
episode_reward1 = tf.Variable(0.)
episode_reward2 = tf.Variable(0.)
tf.scalar_summary("Last 100 Episodes Average Episode Reward for player 1", episode_reward1)
tf.scalar_summary("Last 100 Episodes Average Episode Reward for player 2", episode_reward2)
summary_vars1 = [episode_reward1]
summary_vars2 = [episode_reward2]

summary_placeholders1 = [tf.placeholder("float") for i in range(len(summary_vars1))]
summary_placeholders2 = [tf.placeholder("float") for i in range(len(summary_vars2))]
summary_ops1 = [summary_vars1[i].assign(summary_placeholders1[i]) for i in range(len(summary_vars1))]
summary_ops2 = [summary_vars2[i].assign(summary_placeholders2[i]) for i in range(len(summary_vars2))]

# define policy neural network
state_dim = 9
Exemple #29
0
def main_robotic_human():
    game = Game(players=[
        HumanPlayer(name="Fedor", symbol_class=X),
    ])
    game.add_player(RoboticPlayer(symbol_class=O, gamestate=game))
    game.run()
Exemple #30
0
def main_robotic():
    game = Game(players=[])
    game.add_player(RoboticPlayer(symbol_class=X, gamestate=game))
    game.add_player(RoboticPlayer(symbol_class=O, gamestate=game))
    game.run()
Exemple #31
0
 def test_is_trio_equal(self):
     self.assertFalse(Game.is_trio_equal('X', 'X', 'O'))
     self.assertFalse(Game.is_trio_equal('X', 'O', 'X'))
     self.assertFalse(Game.is_trio_equal('O', 'X', 'X'))
     self.assertTrue(Game.is_trio_equal('X', 'X', 'X'))
Exemple #32
0
 def test_get_selected_cell(self):
     expected_option = 1
     game = Game(lambda n: expected_option, self.print_function)
     game.board.clean_marks()
     option = game.get_selected_cell()
     self.assertEqual(option, expected_option)