Exemplo n.º 1
0
Arquivo: app.py Projeto: p4t0p/game
def game():
    """
        New Game
    """

    new_game = Game()
    return jsonify(new_game.to_json())
Exemplo n.º 2
0
 def __init__(self, skill_level):
     self.window = pygame.display.set_mode(
         (WIDTH + 2 * BOARD_EDGE, HEIGHT + 2 * BOARD_EDGE))
     pygame.display.set_caption("Chess")
     self.clock = pygame.time.Clock()
     self.game = Game(self.window, skill_level)
     self.game_over = False
Exemplo n.º 3
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)
    DEPTH = 3

    while run:
        clock.tick(FPS)
        if game.turn == BLACK:
            start = time.time()
            value, new_board = minimax(game.board.get_board(), DEPTH, True, game)
            game.ai_move(new_board)
            print("TIME: ", time.time() - start)

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)

                if col <= 7:
                    game.select((8 * row + col))

            keys = pygame.key.get_pressed()
            if keys[pygame.K_r]:
                game.reset()

        game.update()
    pygame.quit()
Exemplo n.º 4
0
    def test_player_move_fails_not_in_progress(self):
        """Test exception is thrown if the game is over and 
        a player tries to move"""
        game = Game()
        game._status = constants.CHECKMATE

        with pytest.raises(InvalidMoveError):
            game.player_move(Position(0, 1), Position(0, 2))
Exemplo n.º 5
0
    def __init__(self, ai=None, fen=None, fps=30):
        """ Initialises game loop """

        self.chess_game = Game(fen=fen)
        self.ai = ai
        self.FPS = fps
        self.fpsClock = pygame.time.Clock()
        self.start()
Exemplo n.º 6
0
def test_checkmate():
    """Can't initialize a new game with checkmate."""

    game = Game()

    assert not game.is_check('white'), ("Not checkmate in first round.")
    assert not game.is_check('black'), ("Not checkmate in first round.")
    assert not game.is_checkmate('white'), ("Not checkmate in first round.")
    assert not game.is_checkmate('black'), ("Not checkmate in first round.")
Exemplo n.º 7
0
 def test_get_moves_stalemate(self, board, try_move):
     try_move.return_value = True
     game = Game()
     game._board = board
     mocked_board_moves = {}
     board.in_check.return_value = False
     board.get_moves.return_value = mocked_board_moves
     all_game_moves = game.get_moves(constants.WHITE)
     self.assertEqual(game.status, constants.STALEMATE)
Exemplo n.º 8
0
class App:
    def __init__(self, curses=True):
        if curses:
            self.game = CursesGame()
        else:
            self.game = Game()

    def run(self):
        self.game.run()
Exemplo n.º 9
0
def test_alpha_beta_agent_policy():
    """How does the agent handle naive examples."""
    agent = AlphaBetaAgent(color='black', depth=2)
    game = Game(current_color='white')
    game.move((7, 1), (1, 1))
    move = agent.policy(game)
    assert move == ((0, 2), (1, 1)), (
        f"Agent should take horse with bishop. But it's policy is {move}, "
        f"with actions values:\n{str(agent)}\n{game}"
    )
Exemplo n.º 10
0
def test_simulation(idx):
    """Test that a randomly simulated game doesn't fail."""
    game = Game(
        white_player=RandomAgent,
        black_player=RandomAgent,
    )
    try:
        game.play()
    except Exception as exception:
        print(game.board)
        raise exception
Exemplo n.º 11
0
 def test_try_move_without_capture(self, board):
     rook_position = Position(4, 4)
     rook = Rook(board, constants.WHITE, rook_position)
     board.in_check.return_value = False
     game = Game()
     game._board = board
     self.assertTrue(game.try_move(rook, Position(5, 4)))
     self.assertEqual(rook.position, rook_position)
     board.in_check.return_value = True
     self.assertFalse(game.try_move(rook, Position(5, 4)))
     self.assertEqual(rook.position, rook_position)
Exemplo n.º 12
0
    def test_get_moves_no_special(self, board, try_move):

        invalid_position = Position(3, 3)

        def my_side_effect(*args):
            if args[1] == invalid_position:
                return False
            return True

        try_move.side_effect = my_side_effect
        game = Game()
        game._board = board
        rook = Rook(board, constants.WHITE, Position(4, 4))
        bishop = Bishop(board, constants.WHITE, Position(1, 1))
        knight = Knight(board, constants.WHITE, Position(7, 0))
        mocked_board_moves = {
            rook: {
                constants.MOVES: [Position(5, 4),
                                  Position(3, 4)],
                constants.SPECIAL_MOVES: {}
            },
            bishop: {
                constants.MOVES: [Position(2, 2), invalid_position],
                constants.SPECIAL_MOVES: {}
            },
            knight: {
                constants.MOVES: [],
                constants.SPECIAL_MOVES: {}
            }
        }
        valid_moves = {
            rook: {
                constants.MOVES: [Position(5, 4),
                                  Position(3, 4)],
                constants.SPECIAL_MOVES: {}
            },
            bishop: {
                constants.MOVES: [Position(2, 2)],
                constants.SPECIAL_MOVES: {}
            },
            knight: {
                constants.MOVES: [],
                constants.SPECIAL_MOVES: {}
            }
        }
        board.get_moves.return_value = mocked_board_moves
        all_game_moves = game.get_moves(constants.WHITE)
        self.assertEqual(len(mocked_board_moves), len(all_game_moves))
        for key in valid_moves.keys():
            self.assertIn(key, all_game_moves)
            self.assertEqual(len(valid_moves[key]), len(all_game_moves[key]))
            for move in mocked_board_moves[key]:
                self.assertIn(move, all_game_moves[key])
        self.assertEqual(game.status, constants.IN_PROGRESS)
Exemplo n.º 13
0
def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(WIN)

    while run:
        clock.tick(FPS)

        if game.stalemate():
            print('Stalemate!\nWhite - 1/2 | Black - 1/2\nGame over.')
            run = False
        elif game.checkmate():
            winner = 'White'
            if game.turn == WHITE:
                winner = 'Black'
            print(f'Checkmate!\n{winner} wins!\nGame over.')
            run = False

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_mouse_row_col(pos)
                game.select(row, col)

        game.update()

    pygame.quit()
Exemplo n.º 14
0
def test_cozio_s_mate():
    """"""
    game = Game([
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(6)] + [Pawn('black'), Empty()],
        [Empty() for _ in range(5)] +
        [Queen('black'), King('black'), Empty()],
        [Empty() for _ in range(7)] + [Queen('white')],
        [Empty() for _ in range(6)] + [King('white'), Empty()],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 15
0
 def __init__(self, square, state):
     self.game = Game()
     if state == 'yes' or state == 'Yes':
         self.game.load()
     else:
         self.game.create()
     self.main = Tk()
     self.w = Canvas(self.main, width=square, height=square + square / 8)
     self.w.pack()
     self.w.bind('<Button-3>', self.first_click)
     self.w.bind('<Button-1>', self.second_click)
     self.square = square
     self.small_square = square / 8
     self.weak_reference = []
     self.quit = False
Exemplo n.º 16
0
def test_blackburne_s_mate():
    """"""
    game = Game([
        [Empty() for _ in range(5)] +
        [Tower('black'), King('black'), Empty()],
        [Empty() for _ in range(7)] + [Bishop('white')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(6)] + [Horse('white'), Empty()],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty(), Bishop('white')] + [Empty() for _ in range(6)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 17
0
def test_arabian_mate():
    """"""
    game = Game([
        [Empty() for _ in range(7)] + [King('black')],
        [Empty() for _ in range(7)] + [Tower('white')],
        [Empty() for _ in range(5)] +
        [Horse('white'), Empty(), Empty()],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 18
0
 def test_try_move_with_capture(self, board):
     white_rook_position = Position(4, 4)
     white_rook = Rook(board, constants.WHITE, white_rook_position)
     to_position = Position(5, 4)
     black_rook = Rook(board, constants.BLACK, to_position)
     board.in_check.return_value = False
     game = Game()
     game._board = board
     self.assertTrue(game.try_move(white_rook, to_position))
     self.assertEqual(white_rook.position, white_rook_position)
     self.assertEqual(black_rook.position, to_position)
     board.in_check.return_value = True
     self.assertFalse(game.try_move(white_rook, to_position))
     self.assertEqual(white_rook.position, white_rook_position)
     self.assertEqual(black_rook.position, to_position)
Exemplo n.º 19
0
def test_anastasia_s_mate():
    """"""
    game = Game([
        [Empty() for _ in range(8)],
        [Empty() for _ in range(4)] +
        [Horse('white'), Empty(),
         Pawn('black'), King('black')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(7)] + [Tower('white')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [King('white')] + [Empty() for _ in range(7)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 20
0
def test_black_swine_mate():
    """"""
    game = Game([
        [Empty() for _ in range(5)] +
        [Tower('black'), King('black'), Empty()],
        [Empty()
         for _ in range(6)] + [Tower('white'), Tower('white')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 21
0
    def test_player_move_fails_invalid_move(self, board, mock_get_moves):
        rook_position = Position(1, 1)
        rook = Rook(board, constants.WHITE, rook_position)
        board.get_piece.return_value = rook

        mock_get_moves.return_value = {
            rook: {
                constants.MOVES: [Position(0, 1),
                                  Position(1, 2)],
                constants.SPECIAL_MOVES: {}
            }
        }
        game = Game()
        game._board = board
        with pytest.raises(InvalidMoveError):
            game.player_move(rook.position, Position(2, 2))
Exemplo n.º 22
0
def test_box_mate():
    """"""
    game = Game([
        [Tower('white'), Empty(), Empty()] + [King('black')] +
        [Empty() for _ in range(4)],
        [Empty() for _ in range(8)],
        [Empty()
         for _ in range(3)] + [King('white')] + [Empty() for _ in range(4)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 23
0
def test_anderssen_s_mate():
    """"""
    game = Game([
        [Empty()
         for _ in range(6)] + [King('black'), Tower('white')],
        [Empty() for _ in range(6)] + [Pawn('white'), Empty()],
        [Empty() for _ in range(5)] +
        [King('white'), Empty(), Empty()],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 24
0
def test_bishop_and_knight_mate():
    """"""
    game = Game([
        [Empty() for _ in range(7)] + [King('black')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(5)] +
        [Bishop('white'), King('white'),
         Horse('white')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 25
0
Arquivo: app.py Projeto: p4t0p/game
def move():
    """
        Player Move
    """

    try:
        game = Game(request.json['field'], {
            'turn': request.json['turn'],
            'eaten': request.json['eaten'],
            'check': request.json['check'],
        })
        game.move(request.json['move'])
        
        return jsonify(game.to_json())
    except Exception as e:
        # traceback.print_exception(e)
        return jsonify({'error': str(e)})
Exemplo n.º 26
0
def test_damiano_s_bishop_mate():
    """"""
    game = Game([
        [Empty() for _ in range(5)] +
        [King('black'), Empty(), Empty()],
        [Empty() for _ in range(5)] +
        [Queen('white'), Empty(), Empty()],
        [Empty()
         for _ in range(6)] + [Bishop('white'), Empty()],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(7)] + [King('white')],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 27
0
def test_bodens_mate():
    """"""
    game = Game([
        [Empty(), Empty()] + [King('black'), Tower('black')] +
        [Empty() for _ in range(4)],
        [Empty()
         for _ in range(3)] + [Pawn('black')] + [Empty() for _ in range(4)],
        [Bishop('white')] + [Empty() for _ in range(7)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(5)] +
        [Bishop('white'), Empty(), Empty()],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 28
0
 def test_player_move_success(self, mock_get_moves):
     rook_position = Position(1, 1)
     rook = Rook(None, constants.WHITE, rook_position)
     test_board = {'black_pieces': [rook]}
     mock_get_moves.return_value = {
         rook: {
             constants.MOVES:
             [Position(0, 1),
              Position(1, 2),
              Position(2, 2)],
             constants.SPECIAL_MOVES: {}
         }
     }
     board = set_up_test_board(new_game=False, test_board=test_board)
     game = Game()
     game._board = board
     game.player_move(rook.position, Position(2, 2))
     self.assertEqual(rook.position, Position(2, 2))
Exemplo n.º 29
0
def test_back_rank_mate():
    """"""
    game = Game([
        [Empty() for _ in range(3)] +
        [Tower('white'),
         Empty(), Empty(),
         King('black'),
         Empty()],
        [Empty() for _ in range(5)] +
        [Pawn('black'), Pawn('black'),
         Pawn('black')],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
        [Empty() for _ in range(8)],
    ])
    assert game.is_check('black'), print(game)
    assert game.is_checkmate('black'), print(game)
Exemplo n.º 30
0
 def __init__(self, game, user, new_game=True):
     """
     Initialize game controller
     """
     self.game = game
     self.user = user
     self.chess_engine = ChessEngine()
     self.my_player = Player.objects.get(game=self.game, user=self.user)
     self.opponent = Player.objects.filter(game=self.game).exclude(user=self.user)[0]
     if new_game:
         self.start_game()
Exemplo n.º 31
0
 def test_player_move_fails_wrong_turn(self, board):
     rook_position = Position(1, 1)
     board.get_piece.return_value = Rook(board, constants.BLACK,
                                         rook_position)
     game = Game()
     game._board = board
     game._turn = constants.WHITE
     with pytest.raises(InvalidMoveError):
         game.player_move(rook_position, Position)
Exemplo n.º 32
0
 def __init__(self, curses=True):
     if curses:
         self.game = CursesGame()
     else:
         self.game = Game()
Exemplo n.º 33
0
#! /usr/bin/python

from chess.game import Game
from chess.utils import *

game = Game()
turn = "white"

mode = "termbox"

if mode == "command":
	while True:
		if game.get_all_moves(turn) == []:
			if turn == "black":
				print("Checkmate, white is victorious.")
			if turn == "white":
				print("Checkmate, black is victorious.")
			exit()
		new_move = input(">> ")
		if new_move == "q" or new_move == "quit" or new_move == "exit":
			if input("Are you sure? (y/[N]) >> ").lower() == "y":
				print("Goodbye.")
				exit()
			else:
				print("\n")
				continue
		
		elif new_move == "?" or new_move == "list" or new_move == "help":
			print(game.get_all_moves(turn))
			continue