Example #1
0
    def test_is_winning_row_3(self):
        board_size = 3
        board_3 = Board(board_size)
        board_3.board = [['x', 'x', 'x'], ['o', '.', '.'], ['.', 'o', '.']]

        self.assertTrue(board_3.is_winning_row('x'))
        self.assertFalse(board_3.is_winning_row('o'))
Example #2
0
    def test_place(self):
        board = Board()

        board.place(1, "X")

        assert board.get(1) == "X"
        assert board.get(2) == None
Example #3
0
 def test_game_not_over(self):
     board_size = 3
     game_manager = GameManager(self.a1, self.a2, board_size)
     board = Board(board_size)
     board.board = [['o', '.', '.'], ['x', 'x', '.'], ['o', '.', '.']]
     game_manager.board = board
     self.assertFalse(game_manager.game_over())
Example #4
0
    def initGameCallBack(self):

        if isinstance(self.interFrame, Frame):
            self.interFrame.destroy()
            self.timer.destroy()
            self.counter.destroy()

        if isinstance(self.gameFrame, Frame):
            self.gameFrame.destroy()

        storage = Storage()
        self.mines = storage.get("mines")
        h = storage.get("height")
        w = storage.get("width")
        self.isGameStarted = False

        self.tiles = [[j for j in range(w)] for i in range(h)]
        self.bombs = set()
        self.bombsPrediction = set()
        self.tilesAmount = w * h

        self.board = Board(w, h, self.mines)

        self.root.bind_class('Label', '<Button-1>', self.openTileEvent)
        self.root.bind_class('Label', '<Button-2>', self.flagTileEvent)
        self.root.bind('<KeyPress>', self.keyboardEvent)

        self.code = ""
        self.__createFrame()
        self.__initInterface()
Example #5
0
    def __min_value(self, state: Board, alpha: int, beta: int, depth: int, player: Player):
        """
        Get next worst state for given state based on specified parameters.

        :param state: Board state from which algorithm will start looking for best/worst move.
        :param depth: Maximum tree depth that will be visited.
        :param player: Player for whom moves will be calculated.
        :return: Tuple containing information whether next move gives additional move and next move itself.
        """
        if depth == 0 or state.no_more_moves():
            return self.evaluator.rate_board_state(state, self.__player), False, state
        value = float('inf')
        moves = state.calculate_possible_states(player)
        self.moves_count += len(moves)
        outer_additional_move = False
        outer_state = state
        for additional_move, move in moves:
            if additional_move:
                v_prime, _, _ = self.__min_value(move, alpha, beta, depth - 1, player)
            else:
                v_prime, _, _ = self.__max_value(move, alpha, beta, depth - 1, player.next())
            if v_prime < value:
                value = v_prime
                outer_additional_move = additional_move
                outer_state = move
            if alpha is not None and v_prime <= alpha:
                return value, outer_additional_move, outer_state
            if beta is None or v_prime < beta:
                beta = v_prime
        return value, outer_additional_move, outer_state
Example #6
0
 def test_king_capture_covered_piece(self):
     king = King("e4", "white")
     board = Board([king, Knight("e5", "black"), Bishop("a1", "black")])
     board.create_board()
     output = king.move_to(board, "e5", "black")
     expected_output = (False, "illegal move: king in check")
     self.assertEqual(expected_output, output)
Example #7
0
class Game:
    def __init__(self):
        self.bag = Bag()
        self.board = Board()
        self.trie = Trie.words()

        tiles1, tiles2 = [], []
        for _ in range(7):
            tiles1.append(self.bag.draw_tile())
            tiles2.append(self.bag.draw_tile())
        self.player1 = Ai("Player 1", tiles1)
        self.player2 = Ai("Player 2", tiles2)
        self.cur_player = self.player1
        self.skipped_turns = 0

    def play(self):
        while True:
            self.play_one_move()
            self.board.print_b()
            print(self.cur_player.tiles)
            print(self.cur_player.recent_score)
            print("----------")
            if self.skipped_turns > 5 or not self.cur_player.tiles:
                break
            time.sleep(3)

    def play_one_move(self):
        if self.skipped_turns > 5 or not self.cur_player.tiles:
            return False
        self.cur_player = self.player1 if self.cur_player == self.player2 else self.player2
        successful_play = self.cur_player.make_play(self.trie, self.board)
        if not successful_play:
            if len(self.cur_player.tiles) == 7:
                self.exchange_tiles()
            self.skipped_turns += 1
        else:
            self.replenish_tiles(self.cur_player)
            self.skipped_turns = 0
        return True

    def replenish_tiles(self, player):
        to_replen = 7 - len(player.tiles)
        while self.bag.has_tiles() and to_replen > 0:
            new_tile = self.bag.draw_tile()
            player.tiles.append(new_tile)
            to_replen -= 1

    def exchange_tiles(self):
        to_exchange = random.randrange(1, len(self.cur_player.tiles))
        exchange_list = []
        while self.bag.has_tiles() and to_exchange > 0:
            to_remove = random.choice(self.cur_player.tiles)
            self.cur_player.tiles.remove(to_remove)
            exchange_list.append(to_remove)

            new_tile = self.bag.draw_tile()
            self.cur_player.tiles.append(new_tile)
            to_exchange -= 1
        for t in exchange_list:
            self.bag.add_tile(t)
Example #8
0
class Player():
    def __init__(self):
        self.board = Board()
        self.ships = dict()
        self.ships['carrier'] = Ship(5)
        self.ships['battleship'] = Ship(4)
        self.ships['cruiser'] = Ship(3)
        self.ships['submarine'] = Ship(3)
        self.ships['destroyer'] = Ship(2)

    def mark_hit(self, x, y):
        for name, ship in self.ships.items():
            try:
                ship.coordinates.index((x, y))
                if ship.mark_hit():
                    return 'You sunk my %s!' % name
                return 'Direct hit!'
            except:
                continue

    def has_lost(self):
        for name, ship in self.ships.items():
            if not ship.is_sunk():
                return False
        return True

    def display_board(self):
        left_banner = figlet.renderText('Your Shots')
        left_grid = self.board.display_offense()
        right_banner = figlet.renderText('Your Ships')
        right_grid = self.board.display_defense()
        return side_by_side(left_banner, left_grid, right_banner, right_grid)
Example #9
0
 def test_board_equality_returns_false(self):
     pawn_a = Pawn(1, 0, 1, True)
     pawn_b = Pawn(1, 0, 2, True)
     king = King(1, 4, 0, True)
     board_a = Board([pawn_a, king])
     board_b = Board([pawn_b, king])
     self.assertFalse(board_a == board_b)
Example #10
0
class Tetris(QMainWindow):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        """initiates application UI"""

        self.tboard = Board(self)
        self.setCentralWidget(self.tboard)

        self.statusbar = self.statusBar()
        self.tboard.msg2Statusbar[str].connect(self.statusbar.showMessage)

        self.tboard.start()

        self.resize(180 * 3, 380 * 3)
        #self.center()
        self.setWindowTitle('Tetris')
        self.show()

    def center(self):
        """centers the window on the screen"""

        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
Example #11
0
 def test_game_end(self):
     # Can't move
     b = Board()
     b._board = [
         2, 4, 2, 4,
         4, 2, 4, 2,
         2, 4, 2, 4,
         4, 2, 4, 2
     ]
     self.assertEqual(True, b.is_terminal())
     # Zero check
     b._board = [
         2, 4, 2, 4,
         4, 2, 4, 2,
         2, 4, 2, 4,
         4, 2, 0, 2
     ]
     self.assertEqual(False, b.is_terminal())
     # Right or left
     b._board = [
         2, 4, 2, 4,
         4, 2, 4, 2,
         2, 4, 8, 4,
         4, 2, 2, 2
     ]
     self.assertEqual(False, b.is_terminal())
     # Up or down
     b._board = [
         2, 4, 2, 4,
         4, 2, 4, 2,
         2, 4, 8, 4,
         4, 2, 8, 2
     ]
     self.assertEqual(False, b.is_terminal())
Example #12
0
 def test_king_capture_uncovered_piece(self):
     king = King("e4", "white")
     board = Board([king, Knight("e5", "black"), Bishop("a2", "black")])
     board.create_board()
     output = king.move_to(board, "e5", "black")
     expected_output = (True, "legal move carried out")
     self.assertEqual(expected_output, output)
    def __init__(self,
                 window,
                 player1,
                 player2,
                 data_dir_path,
                 Q_learn=None,
                 Q={},
                 alpha=0.3,
                 gamma=0.9):

        self.data_dir_path = data_dir_path
        self.data_file_path = data_dir_path + "/"

        self.window = window
        self.user_interface = UserInterface(window, self)
        self.board = Board()
        self.evaluator = GameEvaluator()
        self.is_q_learn_mode = False

        self.player1 = player1
        self.player2 = player2
        self.current_player = player1
        self.other_player = player2

        self.games, self.game_stats, self.game_story = self.prepare_stats()
        self.Q_learn = QLearning(self.player1, self.player2)
Example #14
0
    def test_is_winning_second_diagonal(self):
        board_size = 3
        board_3 = Board(board_size)
        board_3.board = [['.', 'o', 'x'], ['.', 'x', '.'], ['x', '.', 'o']]

        self.assertTrue(board_3.is_winning_second_diagonal('x'))
        self.assertFalse(board_3.is_winning_second_diagonal('o'))
Example #15
0
 def setUp(self):
     self.board_3x3 = Board(3)
     self.board_5x5 = Board(5)
     self.game = Game()
     self.game.board = Board(3)
     self.game.player1 = Player("Toothless", "X")
     self.game.player2 = Player("Hiccup", "O")
Example #16
0
def test_out_of_bounds_check():
    b = Board()
    assert b.is_oob(0) == False
    assert b.is_oob(30) == False
    assert b.is_oob(63) == False
    assert b.is_oob(64) == True
    assert b.is_oob(-1) == True
Example #17
0
class Background(QWidget):
    def __init__(self, theme, parent=None):
        super(Background, self).__init__(parent)

        self.theme = theme

        self.board = Board(self.theme, self)
        self.pad = 20

    def paintEvent(self, event):
        painter = QPainter()

        painter.begin(self)
        self.theme.render(painter, "kdiamond-background")
        painter.end()

    def resizeEvent(self, event):
        width = event.size().width() - self.pad
        height = event.size().height() - self.pad

        size = min(width, height)
        self.board.resize(QSize(size, size))

        xPos = (width - size + self.pad) / 2
        yPos = (height - size + self.pad) / 2
        self.board.move(xPos, yPos)
Example #18
0
 def test_actual_round(self):
     """Verify actual round"""
     board = Board(4, 300, 20, 100, 1000, 1)
     board.actual_round = 2
     self.assertEqual(board.actual_round, 2)
     board.actual_round = 1
     self.assertEqual(board.actual_round, 2)
Example #19
0
 def test_game_over_full(self):
     board_size = 3
     game_manager = GameManager(self.a1, self.a2, board_size)
     board = Board(board_size)
     board.board = [['o', 'o', 'x'], ['x', 'x', 'o'], ['o', 'x', 'o']]
     game_manager.board = board
     self.assertTrue(game_manager.game_over())
Example #20
0
 def __init__(self):
     self.board = Board()
     self.ships = dict()
     self.ships['carrier'] = Ship(5)
     self.ships['battleship'] = Ship(4)
     self.ships['cruiser'] = Ship(3)
     self.ships['submarine'] = Ship(3)
     self.ships['destroyer'] = Ship(2)
Example #21
0
    def __init__(self):
        self.run = True
        self.player = Player()
        self.board = Board(os.path.join("..", "worlds", "world.txt"))
        self.screen = pygame.display.set_mode(Game.RESOLUTION)
        self.clock = pygame.time.Clock()

        self.execute()
Example #22
0
 def __init__(self, board=None, color_to_move=None):
     if board is None:
         self.board = Board(MovesTracker())
         self.board.set_up_board_for_new_game()
         self.color_to_move = WHITE_COLOR
     else:
         self.board = board
         self.color_to_move = color_to_move
Example #23
0
 def test_pawn_cant_go_diagonal_if_own_piece_is_there(self):
     with self.assertRaises(CannotCaptureOwnPieceError):
         new_board = Board([
             Pawn(1, 4, 4, True),
             Pawn(1, 5, 5, True),
             King(1, 4, 0, True)
         ])
         new_board.move_white_pawn_1(Position(5, 5))
Example #24
0
 def play(self, nested_array):
     if nested_array == None:
         nested_array = Board().draw_board()
     else:
         Board().draw_board()
     if not self.is_human:
         return self.computer(nested_array)
     return self.human(nested_array)
Example #25
0
def test_is_empty_check():
    test_board = [None for _ in range(64)]
    test_board[10] = "0q"

    b = Board(test_board)

    assert b.is_empty(10) == False
    assert b.is_empty(11) == True
Example #26
0
class MovesTests(unittest.TestCase):
    def setUp(self):
        self.board = Board(8, 8)

    def test_movepiece(self):
        self.board.move_piece((1, 1), (2, 1))
        self.assertEqual(self.board.get_pos_val((1, 1)), '     ')
        self.assertEqual(self.board.get_pos_val((1, 2)), 'PB   ')
Example #27
0
 def test_would_cause_king_to_be_in_check_does_not_throw_exception(self):
     new_board = Board([
         Rook(1, 4, 1, True),
         King(1, 4, 0, True),
         Rook(1, 4, 6, False),
         King(1, 4, 7, False)
     ])
     new_board.move_white_rook_1(Position(4, 2))
Example #28
0
 def restart_game(self):
     self.menu = Menu()
     self.board = Board()
     self.players = []
     self.number_players = 0
     self.board.restart_board()
     self.previous_before_playing()
     self.start_play()
Example #29
0
 def test_get_surrounding(self):
     y = 10
     x = 10
     data = self.get_json_data()
     board = Board()
     tile_map = data["map"]["tiles"]
     result = board.get_surrounding(x, y, tile_map) != False
     self.assertEqual(result, True)
Example #30
0
 def test_creation(self):
     """testing board creationg"""
     my_board = Board(2, 2)
     self.assertTrue(my_board.width == 2)
     self.assertTrue(my_board.width == my_board.height)
     self.assertEqual(my_board.get_tile(X=0, Y=0), 0)
     self.assertEqual(my_board.get_tile(X=0, Y=1), 0)
     self.assertEqual(my_board.get_tile(X=1, Y=0), 0)
     self.assertEqual(my_board.get_tile(X=1, Y=1), 0)
Example #31
0
def test_piece_color():
    test_board = [None for _ in range(64)]
    test_board[10] = "0q"
    test_board[11] = "1q"

    b = Board(test_board)

    assert b.piece_color(10) == Piece.WHITE
    assert b.piece_color(11) == Piece.BLACK
Example #32
0
def test_piece_type():
    test_board = [None for _ in range(64)]
    test_board[10] = "0q"
    test_board[11] = "1n"

    b = Board(test_board)

    assert b.piece_type(10) == Piece.QUEEN
    assert b.piece_type(11) == Piece.KNIGHT
Example #33
0
class ANewBoard(unittest.TestCase):
    def setUp(self):
        self.board = Board(3, 3)

    def test_is_empty(self):
        expected_board = 3 * "...\n"
        self.assertEqual(expected_board, str(self.board))

    def test_has_no_falling_blocks(self):
        self.assertFalse(self.board.has_falling_pieces())

    def test_cannot_tick(self):
        with self.assertRaises(IllegalStateException):
            self.board.tick()
Example #34
0
class TestBoard(unittest.TestCase):

  def setUp(self):
    self.board = Board(3)

  def testItCreatesAThreeByThreeBoard(self):
    expected = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]

    self.assertEquals(expected, self.board.slots)

  def testItReplacesSlot(self):
    index, mark = '5', 'X'
    self.board.replace_slot(index, mark)

    self.assertEquals(mark, self.board.slots.pop(int(index)-1))
Example #35
0
    def __init__(self, theme, parent=None):
        super(Background, self).__init__(parent)

        self.theme = theme

        self.board = Board(self.theme, self)
        self.pad = 20
Example #36
0
 def test_moves(self):
     """testing queen's invalid moves"""
     queen = Queen()
     self.board = Board(10, 10)
     queen.set_position(5, 5)
     self.board.set_tile(1, 5, 5)
     valid_moves_4 = queen.valid_moves(self.board)
     self.assertEqual(len(valid_moves_4), 35)
Example #37
0
 def setUp(self):
     self.board = Board(3, 3)
     self.board.drop(Piece('X'))
     self.board.tick()
     self.board.tick()
     self.board.tick()
     self.board.drop(Piece('Y'))
     self.board.tick()
     self.expected_board = "...\n" + ".Y.\n" + ".X.\n"
Example #38
0
class WhenABlockReachesTheBottom(unittest.TestCase):
    def setUp(self):
        self.board = Board(3, 3)
        self.board.drop(Piece('X'))
        self.board.tick()
        self.board.tick()

    def test_block_is_still_falling_on_the_last_row(self):
        self.assertTrue(self.board.has_falling_pieces())
        expected_board = 2 * "...\n" + ".X.\n"
        self.assertEqual(expected_board, str(self.board))

    def test_block_stops_when_it_hits_the_bottom(self):
        self.board.tick()
        self.assertFalse(self.board.has_falling_pieces())
        expected_board = 2 * "...\n" + ".X.\n"
        self.assertEqual(expected_board, str(self.board))
        with self.assertRaises(IllegalStateException):
            self.board.tick()
 def setUp(self):
   self.board = Board(['1', '2', '3', '4', '5', '6', '7', '8', '9'])
   self.mock_io = Mock()
   self.mock_ai = Mock()
   self.mock_board_analyzer = Mock()
   self.moves = [2, 3]
   self.mock_io.get_move.side_effect = self.moves
   self.game_over_values = [False, True]
   self.mock_board_analyzer.game_over.side_effect = self.game_over_values
   self.engine = GameEngine(self.mock_io, self.mock_ai, self.mock_board_analyzer)
Example #40
0
 def test_valid_moves(self):
     """testing queen's valid moves"""
     queen = Queen()
     self.board.set_tile(1, 0, 0)
     valid_moves_2 = queen.valid_moves(self.board)
     self.assertEqual(len(valid_moves_2), 3)
     self.board = Board(3, 3)
     self.board.set_tile(1, 0, 0)
     valid_moves_3 = queen.valid_moves(self.board)
     self.assertEqual(len(valid_moves_3), 6)
Example #41
0
class BoardTest(TestCase):

    def setUp(self):
        self.board = Board()

    def test_standard_tuning(self):
        self.assertEquals(self.board.fretboard, standard_board)

    def test_other_tuning(self):
        board = Board('abcdef')
        self.assertEquals(board.fretboard, abcdef_board)

    def test_none_tuning(self):
        self.assertRaises(BadTuningError, Board, None)

    def test_empty_tuning(self):
        self.assertRaises(BadTuningError, Board, '')

    def test_int_tuning(self):
        self.assertRaises(BadTuningError, Board, 1)

    def test_get_note_from_string_6(self):
        expected = ('a', 2)
        self.assertEquals(expected, self.board.get_note(6, 5))

    def test_get_note_from_string_5(self):
        expected = ('c', 3)
        self.assertEquals(expected, self.board.get_note(5, 3))

    def test_get_note_from_string_4(self):
        expected = ('g#', 3)
        self.assertEquals(expected, self.board.get_note(4, 6))

    def test_get_note_from_string_3(self):
        expected = ('a', 3)
        self.assertEquals(expected, self.board.get_note(3, 2))

    def test_get_note_from_string_2(self):
        expected = ('c#', 4)
        self.assertEquals(expected, self.board.get_note(2, 2))

    def test_get_note_from_string_1(self):
        expected = ('b', 4)
        self.assertEquals(expected, self.board.get_note(1, 7))

    def test_get_note_none_string(self):
        self.assertRaises(StringNotInBoardError, self.board.get_note, None, 3)

    def test_get_note_none_fret(self):
        self.assertRaises(StringNotInBoardError, self.board.get_note, 1, None)

    def test_find_note(self):
        expected = [('5', 1), ('6', 6)] 
        self.assertEquals(expected, self.board.find_note('a#', 2))

    def test_find_unexistent_note(self):
        self.assertRaises(NoteNotFoundError, self.board.find_note, 'h', 3)
Example #42
0
 def post(self):
     user = users.get_current_user()
     dimension = int(self.request.POST['dimension'])
     board = Board()
     board.player1 = user
     board.dimension = dimension
     board.put()
     token = create_channel(str(board.key().id()) + user.user_id())
     self.response.out.write(simplejson.dumps({'board_id': board.key().id(),
                                               'token': token}))
Example #43
0
class TestBoardMethods(unittest.TestCase):
    """testing methods for board"""
    def setUp(self):
        self.board = Board(2, 2)

    def test_creation(self):
        """testing board creationg"""
        my_board = Board(2, 2)
        self.assertTrue(my_board.width == 2)
        self.assertTrue(my_board.width == my_board.height)
        self.assertEqual(my_board.get_tile(X=0, Y=0), 0)
        self.assertEqual(my_board.get_tile(X=0, Y=1), 0)
        self.assertEqual(my_board.get_tile(X=1, Y=0), 0)
        self.assertEqual(my_board.get_tile(X=1, Y=1), 0)

    def test_set_tile(self):
        """ test set tile """
        self.board.set_tile(val=-1, X=0, Y=1)
        self.assertEqual(self.board.get_tile(X=0, Y=1), -1)

    def test_invalid_tile(self):
        """get tile test"""
        error = self.board.get_tile(X=10, Y=10)
        self.assertEqual(error, -1)
        error = self.board.get_tile(X=-1, Y=0)
        self.assertEqual(error, -1)
        error = self.board.get_tile(X=0, Y=-1)
        self.assertEqual(error, -1)
Example #44
0
class WhenAPieceIsDropped(unittest.TestCase):
    def setUp(self):
        self.board = Board(6, 8)

    def test_t_shape_starts_from_top_middle(self):
        self.board.drop(tetrominoe.T_SHAPE)
        self.assertEqual("....T...\n" + \
                         "...TTT..\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n", str(self.board))

    def test_o_shape_starts_from_top_middle(self):
        self.board.drop(tetrominoe.O_SHAPE)
        self.assertEqual("...OO...\n" + \
                         "...OO...\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n", str(self.board))

    def test_i_shape_starts_from_top_middle(self):
        self.board.drop(tetrominoe.I_SHAPE)
        self.assertEqual("..IIII..\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n", str(self.board))

    def test_l_shape_starts_from_top_middle(self):
        self.board.drop(tetrominoe.L_SHAPE)
        self.assertEqual("...LLL..\n" + \
                         "...L....\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n" + \
                         "........\n", str(self.board))
Example #45
0
def play_game(strategies):
  assert len(strategies) == NUM_PLAYERS

  board = Board(NUM_PLAYERS, strategies)
  last_moves = []

  while not board.game_over:
    # Give each strategy a chance to make a move before checking for game over
    # again.
    while board.current_player_index < len(strategies):
      strategies[board.current_player_index].play_turn(board, last_moves)
      last_moves = board.moves_played_this_turn
      board.end_turn()

    board.current_player_index = 0
    board.end_round()

  board.compute_victor()
  print "Rounds:", board.rounds

  for strategy in strategies:
    strategy.log_end_game(board.victor)

  return board
Example #46
0
class WhenABlockIsDropped(unittest.TestCase):
    def setUp(self):
        self.board = Board(3, 3)
        self.board.drop(Piece('X'))

    def test_a_block_is_falling(self):
        self.assertTrue(self.board.has_falling_pieces())

    def test_block_starts_from_the_top_middle(self):
        expected_board = ".X.\n" + 2 * "...\n"
        self.assertEqual(expected_board, str(self.board))

    def test_block_moves_down_one_row_per_tick(self):
        self.board.tick()
        expected_board = "...\n" + ".X.\n" + "...\n"
        self.assertEqual(expected_board, str(self.board))

    def test_at_most_one_block_may_be_falling_at_a_time(self):
        with self.assertRaises(IllegalStateException):
            self.board.drop(Piece('Y'))
        expected_board = ".X.\n" + 2 * "...\n"
        self.assertEqual(expected_board, str(self.board))
Example #47
0
 def get(self):
     board_id = self.request.get('board')
     token = ''
     other_player = ''
     user = users.get_current_user()
     logout_url = users.create_logout_url("/")
     board_dimention = ''
     if board_id:
         board = Board.get_by_id(int(board_id))
         if board:
             board_dimention = board.dimension
             if board.may_join(user):
                 token = create_channel(str(board.key().id()) + user.user_id())
                 other_player = board.player1
                 key = get_other_player_channel_key(board, user)
                 channel.send_message(key, simplejson.dumps({'type':'join', 'user':get_user_dump(user, format='dict')}))
             else:
                 self.redirect('/')
         else:
             self.redirect('/')
     path = os.path.join('templates', 'pvk.html')
     self.response.out.write(template.render(path, {'token': token, 'board_id': board_id, 'me_user': get_user_dump(user),
                                                    'board_dimention': board_dimention, 'logout_url': logout_url,
                                                    'other_player': get_user_dump(other_player)}))
Example #48
0
class TestQueenMethods(unittest.TestCase):
    """testing methods for board"""
    def setUp(self):
        self.board = Board(2, 2)

    def test_valid_moves(self):
        """testing queen's valid moves"""
        queen = Queen()
        self.board.set_tile(1, 0, 0)
        valid_moves_2 = queen.valid_moves(self.board)
        self.assertEqual(len(valid_moves_2), 3)
        self.board = Board(3, 3)
        self.board.set_tile(1, 0, 0)
        valid_moves_3 = queen.valid_moves(self.board)
        self.assertEqual(len(valid_moves_3), 6)
    def test_moves(self):
        """testing queen's invalid moves"""
        queen = Queen()
        self.board = Board(10, 10)
        queen.set_position(5, 5)
        self.board.set_tile(1, 5, 5)
        valid_moves_4 = queen.valid_moves(self.board)
        self.assertEqual(len(valid_moves_4), 35)
Example #49
0
 def setUp(self):
     TestCase.setUp(self)
     self.b = Board()
Example #50
0
class TestTicTacToe(TestCase):
    
    def setUp(self):
        TestCase.setUp(self)
        self.b = Board()

    def test_update(self):
        update = self.b.update('5', 'X')
        self.assertEqual(self.b.spaces['5'], 'X',  "Space '5' should be X")
        
    def test_available_spaces(self):
        self.b.spaces['5'] = 'O'
        self.b.spaces['9'] = 'X'
        spaces = self.b.available_spaces()
        self.assertEqual(spaces, ['1','2','3','4','6','7', '8'], 
                         "Avalaible spaces incorrect. Returned {0}".format(spaces))

    def test_get_available_edges(self):
        self.b.spaces['2'] = 'O'
        self.b.spaces['4'] = 'X'
        edges = self.b.available_edges()
        self.assertEqual(edges, ['6','8'], 
                         "Avalaible edges incorrect. Returned {0}".format(edges))

    def test_get_available_corners(self):
        self.b.spaces['7'] = 'O'
        self.b.spaces['9'] = 'X'
        corners = self.b.available_corners()
        self.assertEqual(corners, ['1','3'], 
                         "Avalaible corners incorrect. Returned {0}".format(corners))

    def test_check_for_win(self):
        check = self.b.check_for_win(['X', 'X', 'X'] )
        self.assertTrue(check, "Should be true")

    def test_check_for_win_false(self):
        check = self.b.check_for_win(['X', 'X', ''])
        self.assertFalse(check, "Should be false")

    def test_get_winner(self):
        self.b.spaces['1'] = 'X'
        self.b.spaces['2'] = 'X'
        self.b.spaces['3'] = 'X'
        winner = self.b.get_winner()
        self.assertEqual(winner, 'X', "Winner should be 'X'")
    
    def test_get_winner_none(self):
        self.b.spaces['1'] = 'X'
        self.b.spaces['2'] = 'X'
        self.b.spaces['3'] = ''
        winner = self.b.get_winner()
        self.assertEqual(winner, None, "Winner should be 'None'")

    def test_is_first_move(self):
        fm = self.b.is_first_move(self.b.available_spaces())
        self.assertTrue(fm, "Should be true")
        
    def test_is_first_move_false(self):
        self.b.spaces['1'] = 'X'
        fm = self.b.is_first_move(self.b.available_spaces())
        self.assertFalse(fm, "Should be false")

    def test_is_move_valid(self):
        self.b.spaces['1'] = 'X'
        self.b.spaces['2'] = 'X'
        vm = self.b.is_move_valid('3', self.b.available_spaces())
        self.assertTrue(vm, 'Should be true')
        
    def test_is_move_valid_false(self):
        self.b.spaces['1'] = 'X'
        self.b.spaces['2'] = 'X'
        vm = self.b.is_move_valid('2', self.b.available_spaces())
        self.assertFalse(vm, 'Should be false')
Example #51
0
class TestTicTacToe(TestCase):
    def setUp(self):
        TestCase.setUp(self)
        self.p = Player('X')
        self.c = ComputerPlayer('O')
        self.b = Board()

    #
    # - Test Human Player Object
    #
    def test_player_mark(self):
        move = self.p.mark
        self.assertEqual(move, 'X', "Player mark should be 'X'")

    def test_player_first_move(self):
        move = self.p.move(first_move=True)
        self.assertEqual(move, move, "Should return input from player")

    def test_player_subsequent_move(self):
        move = self.p.move()
        self.assertEqual(move, move, "Should return input from player")


    #
    # - Test Computer Player/AI Object
    #
    def test_computer_mark(self):
        m = self.c.mark
        self.assertEqual(m, 'O', "Computer mark should be 'X'")

    def test_counter_first_move_center(self):
        move = self.c.counter_first_move('4', self.b.center, self.b.corners)
        self.assertEqual(move, '5', "Should be '5'")

    def test_counter_first_move_corner(self):
        move = self.c.counter_first_move('5', self.b.center, self.b.corners)
        self.assertTrue(move in self.b.corners, "Should be a corner")

    def test_counter_second_move_edge(self):
        move = self.c.counter_second_move('1', '4', self.b.edges, self.b.corners, self.b.check_edges)
        self.assertTrue(move in self.b.edges, "Should be an edge")

    def test_counter_second_move_corner(self):
        move = self.c.counter_second_move('4', '7', self.b.edges, self.b.corners, self.b.check_edges)
        self.assertTrue(move in self.b.corners, "Should be a corner")

    def test_counter_second_move_two_edges(self):
        self.b.spaces['2'] = self.p.mark
        self.b.spaces['6'] = self.p.mark
        self.b.spaces['5'] = self.c.mark
        move = self.c.counter_second_move('2', '6', self.b.available_edges(), self.b.available_corners(), self.b.check_edges)
        self.assertEqual(move, '3', "Should be '3'. returned {0}".format(move))

    def test_computer_move_none(self):
        move = self.c.move([])
        self.assertEqual(move, None, "Should be None")

    def test_computer_move(self):
        move = self.c.move(self.b.available_spaces())
        self.assertTrue(move in self.b.available_spaces(), 
                        "Should be one of {0}".format(self.b.available_spaces()))

    def test_prevent_win(self):
        self.b.spaces['1'] = self.p.mark
        self.b.spaces['2'] = self.p.mark
        self.b.spaces['3'] = ' '
        space = self.c.prevent_win(self.b.spaces, self.p.mark, self.b.possible_wins)
        self.assertEqual(space, '3', "Space to update should be '3'")

    def test_prevent_win_none(self):
        self.b.spaces['1'] = self.p.mark
        self.b.spaces['2'] = ' '
        self.b.spaces['3'] = ' '
        space = self.c.prevent_win(self.b.spaces, self.p.mark, self.b.possible_wins)
        self.assertEqual(space, None, "Space to update should be None")

    def test_go_for_win(self):
        self.b.spaces['1'] = self.c.mark
        self.b.spaces['5'] = self.c.mark
        self.b.spaces['9'] = ' '
        space = self.c.go_for_win(self.b.spaces, self.c.mark, self.b.possible_wins)
        self.assertEqual(space, '9', "Space to update should be '9'")

    def test_go_for_win_none(self):
        self.b.spaces['1'] = ' '
        self.b.spaces['5'] = self.c.mark
        self.b.spaces['9'] = ' '
        space = self.c.go_for_win(self.b.spaces, self.c.mark, self.b.possible_wins)
        self.assertEqual(space, None, "Space to update should be None")
        
    def tearDown(self):
        TestCase.tearDown(self)
class TestGameEngine(unittest.TestCase):

  def setUp(self):
    self.board = Board(['1', '2', '3', '4', '5', '6', '7', '8', '9'])
    self.mock_io = Mock()
    self.mock_ai = Mock()
    self.mock_board_analyzer = Mock()
    self.moves = [2, 3]
    self.mock_io.get_move.side_effect = self.moves
    self.game_over_values = [False, True]
    self.mock_board_analyzer.game_over.side_effect = self.game_over_values
    self.engine = GameEngine(self.mock_io, self.mock_ai, self.mock_board_analyzer)

  def test_start_displays_board(self):
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.mock_io.assert_has_calls([call.display_board(self.board)])

  def test_start_gets_player_move(self):
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.mock_io.assert_has_calls([call.get_move(self.board)])

  def test_start_puts_move_on_the_board(self):
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.assertEqual(self.board.get_square(self.moves[0]), 'X')

  def test_start_checks_if_game_is_over(self):
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.mock_board_analyzer.assert_has_calls([call.game_over(self.board)])

  def test_start_displays_game_over_message_when_game_is_over(self):
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.mock_io.assert_has_calls(
        [call.display_game_over_message(self.mock_board_analyzer.winner)])

  def test_place_move_allows_two_players_to_play(self):
    game_over_values = [False, False, True]
    self.mock_board_analyzer.game_over.side_effect = game_over_values
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.assertEqual(self.board.get_square(self.moves[0]), 'X')
    self.assertEqual(self.board.get_square(self.moves[1]), 'O')

  def test_place_move_does_not_allow_move_to_be_placed_in_same_square(self):
    self.moves = [2, 2]
    self.mock_io.get_move.side_effect = self.moves
    game_over_values = [False, False, True]
    self.mock_board_analyzer.game_over.side_effect = game_over_values
    self.mock_board_analyzer.square_is_available.side_effect = [True, False]
    self.engine.start(src.game.PLAYER_VS_PLAYER, self.board)
    self.assertEqual(self.board.get_square(self.moves[0]), 'X')
    self.assertEqual(self.board.get_square(self.moves[1]), 'X')

  def test_place_move_allows_ai_to_move_second(self):
    ai_moves = [5]
    self.mock_ai.get_move.side_effect = ai_moves
    game_over_values = [False, False, True]
    self.mock_board_analyzer.game_over.side_effect = game_over_values
    self.engine.start(src.game.PLAYER_VS_AI, self.board)
    self.mock_ai.assert_has_calls([call.get_move(self.board, self.mock_ai.PLAYER_O)])

  def test_start_allows_ai_to_play_against_itself(self):
    ai_moves = [5, 6]
    self.mock_ai.get_move.side_effect = ai_moves
    game_over_values = [False, False, True]
    self.mock_board_analyzer.game_over.side_effect = game_over_values
    self.engine.start(src.game.AI_VS_AI, self.board)
    self.mock_ai.assert_has_calls([call.get_move(self.board, self.mock_ai.PLAYER_X),
                                   call.get_move(self.board, self.mock_ai.PLAYER_O)])
Example #53
0
 def setUp(self):
     self.board = Board(3, 3)
     self.board.drop(Piece('X'))
     self.board.tick()
     self.board.tick()
Example #54
0
class WhenABlockLandsOnAnotherBlock(unittest.TestCase):
    def setUp(self):
        self.board = Board(3, 3)
        self.board.drop(Piece('X'))
        self.board.tick()
        self.board.tick()
        self.board.tick()
        self.board.drop(Piece('Y'))
        self.board.tick()
        self.expected_board = "...\n" + ".Y.\n" + ".X.\n"

    def test_block_is_still_falling_right_above_the_other_block(self):
        self.assertTrue(self.board.has_falling_pieces())
        self.assertEqual(self.expected_board, str(self.board))

    def test_block_stops_when_it_hits_another_block(self):
        self.board.tick()
        self.assertFalse(self.board.has_falling_pieces())
        self.assertEqual(self.expected_board, str(self.board))
        with self.assertRaises(IllegalStateException):
            self.board.tick()
Example #55
0
class TestBoard(unittest.TestCase):

  def setUp(self):
    self.board = Board()

  def test_put_mark_in_square_is_true_when_the_square_has_not_been_taken(self):
    self.assertTrue(self.board.put_mark_in_square(src.game.PLAYER_ONE, 1))

  def test_put_mark_in_square_is_false_when_the_square_has_already_been_taken(self):
    self.board.put_mark_in_square(src.game.PLAYER_ONE, 1)
    self.assertFalse(self.board.put_mark_in_square(src.game.PLAYER_ONE, 1))

  def test_square_is_available_is_true_when_x_or_o_has_not_taken_it(self):
    self.assertTrue(self.board.square_is_available(1))

  def test_square_is_available_is_false_when_it_has_been_taken(self):
    self.board.put_mark_in_square(src.game.PLAYER_ONE, 1)
    self.assertFalse(self.board.square_is_available(0))

  def test_squares_returns_the_number_of_squares_on_the_board(self):
    self.assertEqual(9, self.board.number_of_squares())

  def test_get_square_returns_the_contents_of_the_given_square(self):
    self.assertEqual('1', self.board.get_square(1))
    self.board.put_mark_in_square(src.game.PLAYER_ONE, 1)
    self.assertEqual(src.game.PLAYER_ONE, self.board.get_square(1))

  def test_get_available_squares_returns_an_array_of_the_squares_not_taken(self):
    self.board.put_mark_in_square(src.game.PLAYER_ONE, 1)
    self.board.put_mark_in_square(src.game.PLAYER_ONE, 3)
    self.board.put_mark_in_square(src.game.PLAYER_ONE, 5)
    self.assertEqual([2, 4, 6, 7, 8, 9], self.board.get_available_squares())

  def test_no_open_squares_should_be_true_when_all_squares_have_been_taken(self):
    for square in range(9):
      self.board.put_mark_in_square(src.game.PLAYER_ONE, square + 1)
    self.assertTrue(self.board.no_open_squares())

  def test_no_open_squares_should_be_false_when_any_square_has_not_been_taken(self):
    for square in range(8):
      self.board.put_mark_in_square(src.game.PLAYER_ONE, square + 1)
    self.assertFalse(self.board.no_open_squares())
Example #56
0
def get_board_from_id(board_id):
    if id:
        return Board.get_by_id(int(board_id))
    return None
Example #57
0
 def setUp(self):
   self.board = Board()
Example #58
0
def get_board_from_request(request):
    board_id = request.get('board')
    if board_id:
        return Board.get_by_id(int(board_id))
    return None
Example #59
0
 def setUp(self):
     TestCase.setUp(self)
     self.p = Player('X')
     self.c = ComputerPlayer('O')
     self.b = Board()
Example #60
0
    else:
        counter = c.counter_second_move(first_move,
                                         second_move, 
                                         b.available_edges(), 
                                         b.available_corners(),
                                         b.check_edges,
                                         )
        b.update(counter, c.mark)
    return counter

if __name__ == '__main__':
    start_new_game()
    mark = set_marks()
    p = Player(mark["player_mark"])
    c = ComputerPlayer(mark["computer_mark"])
    b = Board()

    first_move = player_move()
    counter_move(first_move)
    b.display()
    second_move = player_move()

    prevent = c.prevent_win(b.spaces, p.mark, b.possible_wins)
    if prevent is None:
        counter = counter_move(first_move, second_move)
    else:
        b.update(prevent, c.mark)
    b.display()

    for space in b.available_spaces():
        player_move()