Example #1
0
    def handle_message_sub(self,game_dic):
        print("Message du publisher")
        game_dic = json.loads(game_dic)
        if 'team' in game_dic:
            self.team = gm.Team(game_dic['team'])
        else:
            self.team = gm.Team()
        if 'board' in game_dic:
            self.board = gm.Board(game_dic['board'])
        else:
            self.board = gm.Board()
        if 'turn' in game_dic:
            self.turn = game_dic['turn']
        else:
            self.turn = None

        self.draw_game()
        if self.game_started:
            self.show_buttons(self.turn['current_player'] == self.username)
            if self.board.clues == 0:
                self.but_give_clue.setEnabled(False)
            else:
                if self.turn['current_player'] == self.username:
                    self.but_give_clue.setEnabled(True)

        # if end of game, launch end of game popup
        if self.game_started and self.turn['endgame_message'] is not None:
            msg = QMessageBox()
            print("end of game")

            pix = QPixmap("images/token/Hanabi")
            pix = pix.scaled(300,300,Qt.KeepAspectRatio)
            msg.setIconPixmap(pix)
            msg.setText(self.turn['endgame_message'])

            msg.setFont(QFont("Ink Free", 20))
            msg.setInformativeText("Nombre de tours : " + str(int((self.turn["turn_count"]-1)/len(self.team.player_dic))))
            msg.setWindowTitle("Fin de la partie")
            but_ok = QPushButton()
            but_ok.setObjectName("end_ok")
            but_ok.setStyleSheet(self.styleSheet() + "QPushButton#end_ok "
                                                   "{border: none; text-decoration: none; image: url(images/token/OK.png); min-height: 100px; min-width: 300px;} "
                                                   "QPushButton#end_ok:hover "
                                                   "{border: none; text-decoration: underline; image: url(images/token/OK_hover.png);}")

            msg.addButton(but_ok, QMessageBox.YesRole)
            but_ok.clicked.connect(self.end_button)
            msg.exec()
Example #2
0
def file_to_board(board_file_path,
                  rows_num,
                  cols_num,
                  X="X",
                  O="O",
                  empty="_",
                  splitter="\t"):
    '''
    :param board_file_path:
    :param X: X representation in the file
    :param O:
    :param empty:
    :return: A game.Board() object, filled with the file's setting
    '''
    board = game.Board(width=cols_num, height=rows_num)
    board.init_board()
    with open(board_file_path, "r") as board_file:
        rows = board_file.read().splitlines()
        assert len(rows) == rows_num
        for i, row in enumerate(rows):
            cols = row.split(splitter)
            assert len(cols) == cols_num
            for j, col in enumerate(cols):
                move = i * cols_num + j
                if col == X:
                    board.do_move_manual(move, 1)
                elif col == O:
                    board.do_move_manual(move, 2)

    return board
Example #3
0
def main(stdscr):
    stdscr.clear()
    curses.use_default_colors()
    x = 0
    y = 0

    board = game.Board()
    state = 0
    while not state:
        board.curses_print(stdscr, y, x)
        move = {
            55: 0,
            56: 1,
            57: 2,
            52: 3,
            53: 4,
            54: 5,
            49: 6,
            50: 7,
            51: 8
        }[stdscr.getch()]
        state = board.play(move)
        stdscr.refresh()

    if state == 1:
        stdscr.addstr(y + 8, x, "X won")
    if state == 2:
        stdscr.addstr(y + 8, x, "O won")
    if state == 3:
        stdscr.addstr(y + 8, x, "Draw")

    stdscr.getch()
Example #4
0
def test_illegal_move_too_long_black():
    board = game.Board()
    board.set_color(0)
    board.perform_move((6, 1))
    board.snd_player.sumo_levels[0] = 1
    with pytest.raises(game.GameException, match='Move exceeds max range'):
        board.perform_move((6, 7))
Example #5
0
 def test_check_donkey(self):
     for level in xrange(1, 5):
         board = game.Board(0, 3, level)
         for i, donkey in enumerate(board.Donkey):
             assert board.checkDonkey(donkey.posX, donkey.posY)
             assert board.board[donkey.posX][donkey.posY] == game.DONKEYCHAR
             assert board.checkBlocking(donkey.posX, donkey.posY)
Example #6
0
 def test_checkIfWinHorizontal_first_row(self):
     brett = game.Board()
     for column in range(game.COLUMNS):
         brett.place(0, column, 1)
     self.assertEqual(1, brett.checkIfWinHorizontal())
     brett.place(0, 0, -1)
     self.assertEqual(0, brett.checkIfWinHorizontal())
Example #7
0
def ai_q_game():
    board = game.Board(20, 20, display)
    ai = ai_q_module.AI(board)

    while True:
        ai.train(2000)
        ai.show_game()
Example #8
0
    def __init__(self, init_model=None):
        self.board_width = 5
        self.board_height = 5
        self.show_board = True
        self.n_in_row = 4
        self.n_playout = 400  # num of simulations for each move
        self.c_puct = 5
        self.self_play_batch_size = 1
        self.number_game_play_training = 1500
        self.buffer_size = 10000
        self.learning_rate = 2e-3
        self.epochs = 5
        self.batch_size = 128

        self._is_selfplay = 0
        self.init_model = True

        self.buffer = deque(maxlen=self.buffer_size)

        self.board = game.Board(self.board_width, self.board_height,
                                self.n_in_row)
        if self.init_model:
            self.policy_value_net = policy.PolicyValueNet(
                self.board_width, self.board_height,
                "current_policy_5_5_4_level_6.model")
        else:
            self.policy_value_net = policy.PolicyValueNet(
                self.board_width, self.board_height)
        # print("llll")
        self.mcts_player = mcts.MCTS_Player(
            self.policy_value_net.policy_value_fn,
            c_put=self.c_puct,
            n_playout=self.n_playout,
            _is_selfplay=self._is_selfplay)
Example #9
0
def ai_game():
    ai = ai_module.AI()

    needs_train = True
    while needs_train:
        crashed = False
        frame = 0
        board = game.Board(20, 20, display)
        ai.train_once(board)
        needs_train = False
        while not crashed:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    crashed = True

            if frame >= 5:
                ai.control(board)
                if board.update():
                    crashed = True
                    needs_train = True
                frame = 0
            frame += 1
            board.draw()
            pygame.display.update()
            clock.tick(60)
Example #10
0
    def test_checkIfFull_forFull(self):
        brett = game.Board()
        for row in range(game.ROWS):
            for column in range(game.COLUMNS):
                brett.place(row, column, 1)

        self.assertEqual(True, brett.isFull())
Example #11
0
 def test_check_donkey(self):
     for test in range(30):
         level = random.randint(1, 7)
         board = game.Board(0, 3, level)
         for i in range(game.ROWS):
             for j in range(game.COLUMNS):
                 if board.board[i][j] == game.DONKEYCHAR:
                     assert board.checkDonkey(i, j)
Example #12
0
 def test_place_donkey(self):
     for test in range(30):
         for level in range(1, 2):
             board = game.Board(0, 3, level)
             for i in range(5):
                 board.placeDonkey()
                 assert i + level + 1 == self.donkeys(board.board)
                 assert i + level + 1 == len(board.Donkey)
Example #13
0
 def join_game(self):
     dic_cmd = {'username': self.username}
     message = self.client.make_message(dic_cmd)
     # message = self.client.socket.recv()
     # game_dic = json.loads(message)
     self.team = gm.Team(message['team'])
     self.board = gm.Board(message['board'])
     self.turn = message['turn']
Example #14
0
def test_illegal_move_over_stone_diagonal():
    board = game.Board()
    board.set_color(0)
    board.perform_move((5, 0))
    board.perform_move((2, 3))
    board.perform_move((4, 5))
    with pytest.raises(game.GameException, match='Cannot move through pieces'):
        board.perform_move((5, 6))
Example #15
0
def preset_board():
    board = game.Board()
    board.set_color(0)
    board.perform_move((5, 0))
    board.perform_move((4, 5))
    board.perform_move((5, 6))
    board.perform_move((4, 3))
    return board
Example #16
0
def test_get_legal_moves():
    board = game.Board()
    board.set_color(0)
    board.perform_move((6, 0))
    assert set(board.get_legal_moves()) == {(1, 2), (2, 2), (3, 2), (4, 2),
                                            (5, 2), (6, 2), (1, 1), (2, 0),
                                            (1, 3), (2, 4), (3, 5), (4, 6),
                                            (5, 7)}
def generate_states(board=game.Board([[0, 0, 0], [0, 0, 0], [0, 0, 0]])):
    states = [board.board]
    for move in board.valid_moves():
        tmp = board.copy()
        if (tmp.play(move)):
            continue
        states.extend(generate_states(tmp))
    return states
Example #18
0
 def test_coin(self):
     for test in range(30):
         number = 0
         board = game.Board(0, 3, 1)
         for i in range(game.ROWS):
             for j in range(game.COLUMNS):
                 number += (board.board[i][j] == game.COINCHAR)
         assert number == 20
Example #19
0
def test_sumo_move_just_in_range():
    board = game.Board()
    board.set_color(0)
    board.fst_player.sumo_levels[0] = 1
    try:
        board.perform_move((2, 0))
    except game.GameException:
        pytest.fail('Legal moves raised an BoardException')
Example #20
0
def createRandomBoard():
    """
    Create a Board with a random population of dots in our test.
    :return: Board object
    """
    r = game.RandomGen({'a': .25, 'b': .25, 'c': .25, 'd': .25})
    b = game.Board(8, 8, r)
    return b
Example #21
0
 def test_princess(self):
     for test in range(30):
         number = 0
         board = game.Board(0,3,1)
         for i in range(game.ROWS):
             for j in range(game.COLUMNS):
                 number += (board.board[i][j] == game.PRINCESSCHAR)
         assert number == 1
Example #22
0
 def server_response(self, width, height, n_match, state, current_player,
                     last_move):
     print("Hello")
     temp_board = game.Board(width, height, n_match, False, state,
                             current_player, last_move)
     t_move, prob = self.mcts_player.get_action(temp_board, 1e-3, 1)
     temp_board.do_move(t_move)
     temp_board.graphic_display()
Example #23
0
    def __init__(self):
        print("Initializing game...")

        isPlaying = True  # Keep track of the game state (playing/game over)

        board = game.Board()  # Initalize the board

        # Choose gameplay input
        #agent = RandomAgent()       # This agent selects a random possible move
        #agent = BasicAgent()        # This agent selects a move closer to the dot
        #agent = BetterAgent()       # This agent selects a move closer to the dot, but farther from its tail and the edge
        agent = UserAgent()  # This records and processes user input

        # Choose a visualizer
        #visualizer = BoardPrinter() # Select a visualiser (terminal)
        visualizer = BoardDrawer()  # Select a visualiser (view screen)

        high_scores = High_Scores()

        while (isPlaying):
            start = time.time()

            # Visualize this step
            visualizer.drawBoard(board)

            # Check if the game is over
            isPlaying = not board.is_game_over()

            # Get the next move
            next_move = agent.get_direction(board)

            # Perform the move
            board.move(next_move)

            if not isPlaying:
                print("Ended with score:", board.score)
                break

            end = time.time()
            frame_time = end - start
            sleep_time = self.TIME_PER_FRAME - frame_time
            if frame_time > 0 and sleep_time > 0:
                time.sleep(sleep_time)

        # Update high scores and save them
        high_scores.add_highscore(board.score)
        high_scores.write_highscores()

        is_watching_score = True
        while is_watching_score:

            visualizer.show_end_screen(board)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    is_watching_score = False

            time.sleep(0.05)
Example #24
0
def test_is_winning_move_diagonal():
    b = game.Board(4, 4)
    for i in range(4):
        for j in range(i):
            b.play(i, 'o')
        b.play(i, 'x')
    assert b.is_winning_move(3, 3, 'x')
    assert b.is_winning_move(0, 0, 'x')
    assert b.is_winning_move(1, 1, 'x')
Example #25
0
 def test_ceiling(self):
     board = game.Board(4, 4, [(0, 0), (1, 2)])
     self.assertListEqual([0, 2, 4, 4], board.ceiling)
     board.lock([(0, 1), (1, 1), (2, 2)])
     self.assertListEqual([0, 1, 2, 4], board.ceiling)
     board.lock([(2, 1), (3, 1)])
     self.assertListEqual([0, 1, 1, 1], board.ceiling)
     board.clear_row(1)
     self.assertListEqual([1, 2, 2, 4], board.ceiling)
Example #26
0
def initialize():
    size = config['Board'].gettuple('board-size')
    step = config['Board'].getint('step')
    offset = config['Board'].getint('offset')

    pygame.init()
    pygame.display.set_caption('Smart Snake')
    board = game.Board(size, step, offset)
    clock = pygame.time.Clock()
    return board, clock
Example #27
0
def test_illegal_move_over_stone_straight():
    board = game.Board()
    board.set_color(0)
    board.perform_move((5, 0))
    board.perform_move((1, 2))
    board.perform_move((5, 2))
    board.perform_move((1, 7))
    board.perform_move((4, 5))
    with pytest.raises(game.GameException, match='Cannot move through pieces'):
        board.perform_move((6, 2))
Example #28
0
def test_new_board():
    game.Board(3, 3).ascii() == t("""
    ...
    ...
    ...
    """)

    game.Board(4, 3).ascii() == t("""
    ....
    ....
    ....
    """)

    game.Board(3, 4).ascii() == t("""
    ...
    ...
    ...
    ...
    """)
Example #29
0
    def test_blocking(self):
        for test in range(30):
            board = game.Board(0, 3, 1)
            pos = self.get_blocking(board)
            pos_x = pos[0]
            pos_y = pos[1]

            fireball = Fireball(pos_x - 1, pos_y, 1)
            #print pos, self.get_fireball(board)
            board.moveFireball(fireball)
Example #30
0
 def test_close_to_filled(self):
     board = game.Board(5, 5, [(1, 2), (2, 2)])
     s = board.close_to_filled(1)
     self.assertSetEqual(
         set([(0, 1), (1, 1), (2, 1), (3, 2), (0, 2), (1, 2), (2, 2),
              (0, 3), (1, 3), (2, 3)]), s)
     s = board.close_to_filled(1, False)
     self.assertSetEqual(
         set([(0, 1), (1, 1), (2, 1), (3, 2), (0, 2), (0, 3), (1, 3),
              (2, 3)]), s)