Example #1
0
def get_input(turn: int, player: str, board: game.Board):
    m_c = input("Turn: %s, Player: %s -- move and comment: " %
                (turn, player)).split(" ")

    if len(m_c) != 2 and len(m_c) != 1:
        print("only input move and comment, like 'b4 !!'")
        return get_input(turn, player, board)

    move, *comment = m_c

    if not board.check_legality(move):
        print("this is not a legal move")
        return get_input(turn, player, board)

    if board.check_for_check(move) and move.count("+") != 1:
        print("incorrect notation for check - this will be fixed")
        move.replace("+", "")
        move += "+"
        print("move is now %s" % move)
        return (move, comment)

    if board.check_for_mate(move) and move.count("+") != 2:
        print("incorrect notation for checkmate - this will be fixed")
        move.replace("+", "")
        move += "++"
        print("move is now %s" % move)
        return (move, comment)

    if (comment):
        return (move, comment)
    else:
        return (move, "-")
Example #2
0
    def __init__(self):
        self.__globals = Globals()
        self.__files = FileManager()
        Logic()

        pg.init()
        pg.font.init()
        pg.display.set_caption("Chessr")
        self.__screen = pg.display.set_mode(self.__globals.get_window_size())
        pg.display.set_icon(self.__files.load_image("icon.png", True))

        self.__groups = Groups()
        Spritesheet()
        self.__clock = pg.time.Clock()
        self.__board = Board()

        running = True
        while running:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = False
                    continue
                if event.type == pg.MOUSEBUTTONDOWN:
                    self.__board.pressed(event)
                if event.type == pg.MOUSEBUTTONUP: self.__board.released(event)
            self.__board.update()
            self.__groups.update()
            self.__screen.fill((40, 40, 40))
            self.__groups.draw(self.__screen)
            pg.display.flip()
            self.__clock.tick(self.__globals.get_fps())

        pg.quit()
Example #3
0
    def __init__(self, top_level: tk.Toplevel, on_game_exit: Callable):
        super().__init__(top_level)  # This calls Frame's __init__
        self.top_level = top_level
        self.on_game_exit = on_game_exit
        self.pack(padx=10, pady=10, expand=True)

        self.canvas_width = 700

        self.top_level.wm_protocol("WM_DELETE_WINDOW", self.exit)

        self.canvas = tk.Canvas(self, width=self.canvas_width, height=self.canvas_width, background="#ffe48a")  # , highlightthickness=0)
        self.canvas.grid(row=0, column=0, columnspan=3)
        self.canvas.addtag_all("all")

        self.canvas.bind("<Button-1>", self.on_mouse_pressed)
        self.canvas.bind("<ButtonRelease-1>", self.on_mouse_released)
        self.canvas.bind("<Motion>", self.on_mouse_moved)

        self.bind("<Configure>", self.on_resize)

        self.dont_resize = True

        self.var_player1_pieces_left = tk.StringVar(self, "White pieces: 9")
        self.lbl_player1_pieces_left = tk.Label(self, textvariable=self.var_player1_pieces_left, font="TkDefaultFont 10 bold")
        self.var_player2_pieces_left = tk.StringVar(self, "Black pieces: 9")
        self.lbl_player2_pieces_left = tk.Label(self, textvariable=self.var_player2_pieces_left, font="TkDefaultFont 10 bold")

        self.lbl_player1_pieces_left.grid(row=1, column=0)
        self.lbl_player2_pieces_left.grid(row=1, column=2)

        self.var_current_player = tk.StringVar(self, "White's turn")
        tk.Label(self, textvariable=self.var_current_player, font="TkDefaultFont 10 bold").grid(row=1, column=1)

        self.board = Board(self.canvas, self.canvas_width)
        self.game_over = False
Example #4
0
def fight(p1, p1_table, p2, p2_table, nb_playouts=1000, verbose=True):
    board = Board()
    if p1_table:
        transpositionT1 = {}
    if p2_table:
        transpositionT2 = {}
    while (not board.finished):
        if verbose:
            print(board.board)
            print("Turn " + str(board.turn))

        if board.turn == RED:
            if p1_table:
                move = getattr(board, p1)(nb_playouts, transpositionT1)
            else:
                move = getattr(board, p1)(nb_playouts)
        elif board.turn == YELLOW:
            if p2_table:
                move = getattr(board, p2)(nb_playouts, transpositionT2)
            else:
                move = getattr(board, p2)(nb_playouts)

        board.play(move)
    if verbose:
        print(board.board)
        print("Winner :" + str(board.winner))
    return board.winner
Example #5
0
def load_game():
    game = Board(cols=8, rows=8)
    white_queen = Queen(Vec2I(3, 0), Team.WHITE, monkey_stack=12)
    black_queen = Queen(Vec2I(4, 7), Team.BLACK, monkey_stack=12)
    game.add_entity(white_queen)
    game.add_entity(black_queen)
    return game
Example #6
0
def interpret_game(path):
    game_data = read_game_file(path)

    white_queen = Queen(game_data['white_queen'],
                        Team.WHITE,
                        monkey_stack=game_data['stack'])
    black_queen = Queen(game_data['black_queen'],
                        Team.BLACK,
                        monkey_stack=game_data['stack'])

    board = Board(cols=game_data['cols'], rows=game_data['rows'])
    board.add_entity(white_queen)
    board.add_entity(black_queen)

    board.draw()

    for command in game_data['moves']:
        board.play_command(command)

    return board
Example #7
0
        try:
            move_from_ls[0] = letters.index(move_from_ls[0].lower())
            move_to_ls[0] = letters.index(move_to_ls[0].lower())
            move_from = Vec2I(int(move_from_ls[0]), int(move_from_ls[1]))
            move_to = Vec2I(int(move_to_ls[0]), int(move_to_ls[1]))
        except ValueError:
            print('Please specify a letter then a number with no space between them. Example: d0 and d3')
            continue

        command = Command(move_from, move_to)
        return command


if __name__ == '__main__':
    board = Board(cols=8, rows=8)

    game_interface = MonkeyQueenGameInterface(board)

    white_queen = Queen(Vec2I(3, 0), Team.WHITE, monkey_stack=12)
    black_queen = Queen(Vec2I(4, 7), Team.BLACK, monkey_stack=12)

    board.add_entity(white_queen)
    board.add_entity(black_queen)

    graphics = UI(board)
    graphics.open_window()

    AI = [Team.WHITE, Team.BLACK]

    last_move = None
Example #8
0
class Game(ABC, tk.Frame):

    def __init__(self, top_level: tk.Toplevel, on_game_exit: Callable):
        super().__init__(top_level)  # This calls Frame's __init__
        self.top_level = top_level
        self.on_game_exit = on_game_exit
        self.pack(padx=10, pady=10, expand=True)

        self.canvas_width = 700

        self.top_level.wm_protocol("WM_DELETE_WINDOW", self.exit)

        self.canvas = tk.Canvas(self, width=self.canvas_width, height=self.canvas_width, background="#ffe48a")  # , highlightthickness=0)
        self.canvas.grid(row=0, column=0, columnspan=3)
        self.canvas.addtag_all("all")

        self.canvas.bind("<Button-1>", self.on_mouse_pressed)
        self.canvas.bind("<ButtonRelease-1>", self.on_mouse_released)
        self.canvas.bind("<Motion>", self.on_mouse_moved)

        self.bind("<Configure>", self.on_resize)

        self.dont_resize = True

        self.var_player1_pieces_left = tk.StringVar(self, "White pieces: 9")
        self.lbl_player1_pieces_left = tk.Label(self, textvariable=self.var_player1_pieces_left, font="TkDefaultFont 10 bold")
        self.var_player2_pieces_left = tk.StringVar(self, "Black pieces: 9")
        self.lbl_player2_pieces_left = tk.Label(self, textvariable=self.var_player2_pieces_left, font="TkDefaultFont 10 bold")

        self.lbl_player1_pieces_left.grid(row=1, column=0)
        self.lbl_player2_pieces_left.grid(row=1, column=2)

        self.var_current_player = tk.StringVar(self, "White's turn")
        tk.Label(self, textvariable=self.var_current_player, font="TkDefaultFont 10 bold").grid(row=1, column=1)

        self.board = Board(self.canvas, self.canvas_width)
        self.game_over = False

    @abstractmethod
    def on_mouse_pressed(self, event):
        pass

    @abstractmethod
    def on_mouse_released(self, event):
        pass

    @abstractmethod
    def on_mouse_moved(self, event):
        pass

    def on_resize(self, event):
        smallest = min(event.width, event.height - 22)

        try:
            scale = smallest / self.canvas_width
        except ZeroDivisionError:
            return

        self.canvas_width = smallest
        self.board.canvas_width = smallest
        if not self.dont_resize:
            self.canvas.config(width=smallest, height=smallest)
        self.config(width=smallest, height=smallest)
        self.dont_resize = False

        if scale == 0:
            return

        # Rescale all the objects tagged with the "all" tag
        self.canvas.scale("all", 0, 0, scale, scale)

        self.board.on_window_resize(smallest)

    def check_for_game_over(self):
        if not self.game_over and self.board.game_over:
            if self.board.winner != TIE:
                messyge = f"{'White' if self.board.winner == PLAYER1 else 'Black'} has won!"
            else:
                messyge = "Tie between both players!"

            messagebox.showinfo(title="Game Over", message=messyge, parent=self.top_level)
            self.game_over = True

    def update_gui(self):
        self.var_player1_pieces_left.set(f"White pieces: {self.board.white_pieces}")
        self.var_player2_pieces_left.set(f"Black pieces: {self.board.black_pieces}")
        self.var_current_player.set("White's turn" if self.board.turn == PLAYER1 else "Black's turn")

        player1_pieces = int(self.var_player1_pieces_left.get()[-1])
        player2_pieces = int(self.var_player2_pieces_left.get()[-1])

        if player1_pieces == player2_pieces == 0:
            self.lbl_player1_pieces_left.grid_remove()
            self.lbl_player2_pieces_left.grid_remove()

    def exit(self):
        self.top_level.destroy()
        self.on_game_exit()
Example #9
0
from src.game.board import Board
from src.game.entities import Monkey, Queen, Team
from src.game.game_exception import *
from src.game.command import Command
from src.game.geo import Vec2I

ROWS = 8
COLS = 8

white_queen = Queen(Vec2I(3, 0), Team.WHITE, monkey_stack=8)
black_queen = Queen(Vec2I(4, 7), Team.BLACK, monkey_stack=8)

board = Board(cols=COLS, rows=ROWS)
board.add_entity(white_queen)
board.add_entity(black_queen)

board.draw()

while True:
    str_from = input('Piece from (x, y): ')
    str_from = str_from.split(',')
    pos_from = Vec2I.parse_from_list(str_from)

    str_to = input('Piece to (x, y): ')
    str_to = str_to.split(', ')
    pos_to = Vec2I.parse_from_list(str_to)

    command = Command(pos_from, pos_to)

    try:
        board.play_command(command)
Example #10
0
class Game:
    def __init__(self):
        self._game_board = None
        self._board_indexes = None
        self._goal = None
        self._move_count = 0
        self._weighted_score = 0
        self.init_board(size=4, goal=2048)

    def init_board(self, size, goal):
        self._game_board = Board(size=size)
        self._board_indexes = Game._game_board_indexes(
            self._game_board.get_size())
        self._goal = goal

    @classmethod
    def _game_board_indexes(cls, size) -> np.ndarray:
        board_index = np.ndarray(shape=(size, size), dtype=object)
        for r in range(board_index.shape[0]):
            for c in range(board_index.shape[1]):
                board_index[r, c] = (r, c)
        return board_index

    def get_board(self) -> Board:
        return self._game_board

    def get_move_count(self) -> int:
        return self._move_count

    def get_weighted_score(self) -> float:
        return self._weighted_score

    def get_score(self) -> int:
        return self._game_board.get_score()

    def display(self):
        print(self._game_board.get_board())
        print("current total score: %d" % self._game_board.get_score())
        print("current move count: %d" % self._move_count)
        print("current weighed score : %f" % self.get_weighted_score())
        print("========================================================")

    def get_new_pos(self) -> (int, int):
        return self._game_board.get_new_pos()

    # def test_board(self, board):
    #     self._game_board.test_board(board)

    def do_action(self, action: str):
        """
        First, extract lines according to user's input, within each line holds the coordinate of each tile
        Then, move and merge tiles
        :param action:
        :return:
        """
        lines = self._get_lines(action=action)

        self._game_board.merge_tile(
            lines=lines, merge_to_left=Action.left_direction(action))

        self._move_count += 1

        self._weighted_score = float(self._game_board.get_score()) / math.log(
            float(self._move_count + 1), 2.)

    def _get_lines(self, action: str) -> list:
        lines = []
        if action in [Action.left.get_value(), Action.right.get_value()]:
            lines = self._get_row_lines(indexes=self._board_indexes)
        elif action in [Action.up.get_value(), Action.down.get_value()]:
            # a vertical operation, transpose the board, then call _get_row_lines
            index_trans = np.transpose(self._board_indexes)
            lines = self._get_row_lines(indexes=index_trans)
        elif action in [
                Action.upLeft.get_value(),
                Action.downRight.get_value()
        ]:
            lines = self._get_diagonal_lines(indexes=self._board_indexes)
        else:
            # a forward slash operation, flip the board vertically and call _get_diagonal_lines
            index_flip = np.fliplr(self._board_indexes)
            lines = self._get_diagonal_lines(indexes=index_flip)
        return lines

    def _get_row_lines(self, indexes: np.ndarray) -> list:
        lines = []
        # a horizontal operation, get coordinate of each tile from each row
        for i in range(indexes.shape[0]):
            lines.append(indexes[i, :])
        return lines

    def _get_diagonal_lines(self, indexes: np.ndarray) -> list:
        # get the diagonal of the board first
        lines = [np.diagonal(indexes)]
        for i in range(1, indexes.shape[0] - 1):
            # shrink the board to the down left corner by 1 tile, then get its diagonal
            lines.append(np.diagonal(indexes[i:, :(indexes.shape[1] - i)]))
            # shrink the board to the up right corner by 1 tile, then get its diagonal
            lines.append(np.diagonal(indexes[:(indexes.shape[1] - i), i:]))
        return lines

    def valid_action(self, action: str) -> bool:
        if action in self.valid_actions():
            return True
        return False

    def valid_actions(self) -> list:
        valid_actions = []
        for act in Action.__members__.values():
            lines = self._get_lines(action=act.get_value())
            if self._game_board.movable(lines=lines,
                                        to_left=Action.left_direction(
                                            act.get_value())):
                valid_actions.append(act.get_value())
        return valid_actions

    @property
    def game_over(self) -> (bool, bool):
        if np.any(self._game_board.get_board() == self._goal):
            return True, True
        if len(self.valid_actions()) == 0:
            self._weighted_score = -1
            return True, False
        return False, False
Example #11
0
 def init_board(self, size, goal):
     self._game_board = Board(size=size)
     self._board_indexes = Game._game_board_indexes(
         self._game_board.get_size())
     self._goal = goal
Example #12
0
    if len(sys.argv) == 2:
        print('Game Mode: Play game file')

        game_file = sys.argv[1]
        game_data = read_game_file(game_file)

        board_cols = game_data['cols']
        board_rows = game_data['rows']

        queen_stack = game_data['stack']
        white_queen_pos = game_data['white_queen']
        black_queen_pos = game_data['black_queen']
        command_queue = game_data['moves']

        # Default mode
        game = Board(board_cols, board_rows)
        game.add_entity(
            Queen(white_queen_pos, Team.WHITE, monkey_stack=queen_stack))
        game.add_entity(
            Queen(black_queen_pos, Team.BLACK, monkey_stack=queen_stack))

        game_from_file = True
    else:
        game = Board(8, 8)
        game.add_entity(Queen(Vec2I(3, 0), Team.WHITE, monkey_stack=8))
        game.add_entity(Queen(Vec2I(4, 7), Team.BLACK, monkey_stack=8))

    pygame.init()

    HEIGHT = 800
    WIDTH = 1000  # 800 for game 200 for info column