Пример #1
0
 def __init__(self, player1, player2):
     if not {player1.color, player2.color} == {WHITE, BLACK}:
         raise Exception("Must have one player of each color")
     self.players = [player1, player2]
     self.board = Board()
     self.dice = Dice()
     self.on_roll = 0  # starting player 1
Пример #2
0
    def apply(self, board: Board):
        if getRelativePointLocation(self.color, self.start) > self.die:
            raise IllegalMoveException("Move cannot be made given the die value " + str(self.die))
        elif getRelativePointLocation(self.color, self.start) < self.die:
            if board.farthestBack(self.color) != self.start:
                raise IllegalMoveException(
                    "You must move the farthest back piece off that you can with die " + str(self.die))

        scratch = board.__deepcopy__()

        # VALID MOVEMENT
        scratch.removeFromLocation(self.color, self.start)
        scratch.moveOff(self.color)

        return scratch
Пример #3
0
def generate_moves(board: Board, color: str, dice: Dice, verbose=False):
    root = MoveNode(color + " " + str(dice), board_after=board, deep=0)
    get_moves(color, dice.getDistances(), board.farthestBack(color), root)

    min_die = min(dice.getDice())
    max_die = max(dice.getDice())
    depth = 0
    used_dict = {min_die: set(), max_die: set()}
    moves_dict = {}
    for move in PreOrderIter(root):
        deep = move.deep
        if deep > depth:
            depth = deep

        if deep not in moves_dict:
            moves_dict[deep] = {move}
        else:
            moves_dict[deep].add(move)

        if depth == 1:
            used_dict[move.die].add(move)

    if depth == 1 and used_dict[min_die] and used_dict[max_die]:
        moves = used_dict[max_die]
    else:
        moves = moves_dict[depth]

    if verbose:
        print(board)
        print(dice)
        print(moves)

    return moves
Пример #4
0
    def get_input_vector(board=Board(), current_color=BLACK):
        """
             BLACK_OFF | BLACK_POINTS_CONTENT | BLACK_BAR | TURN | WHITE_BAR | WHITE_POINTS CONTENT | WHITE_OFF
                 1            24 * 4 = 96          1         2         1           24 * 4 = 96            1
        """
        black = []
        white = []
        for point, v in enumerate(board.pointsContent[1:-1], 1):
            if v > 0:
                white.extend((0, 0, 0, 0))
                if v == 1:
                    black.extend((1, 0, 0, 0))
                elif v == 2:
                    black.extend((1, 1, 0, 0))
                elif v == 3:
                    black.extend((1, 1, 1, 0))
                else:
                    black.extend((1, 1, 1, (v - 3) / 2))

            elif v < 0:
                black.extend((0, 0, 0, 0))
                if v == -1:
                    white.extend((1, 0, 0, 0))
                elif v == -2:
                    white.extend((1, 1, 0, 0))
                elif v == -3:
                    white.extend((1, 1, 1, 0))
                else:
                    white.extend((1, 1, 1, (abs(v) - 3) / 2))
            else:
                black.extend((0, 0, 0, 0))
                white.extend((0, 0, 0, 0))
        current_color = [1, 0] if current_color == BLACK else [0, 1]
        middle = black + [board.numBar(BLACK) / 2] + current_color + [board.numBar(WHITE) / 2] + white
        return tf.constant([[board.numOff(BLACK) / 15] + middle + [board.numOff(WHITE) / 15]])
    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        #Create the screen
        self.screen = pygame.display.get_surface()

        #Create a main menu
        self.menu = Menu(self.screen)

        #Create the game board
        topLeft = {'x': 40, 'y': 120}
        self.board = Board(topLeft, self.screen.get_width() - (topLeft['x'] * 2), self.screen.get_height() - (topLeft['y'] * 2), self.screen)

        #Create levels
        self.levelOne = Level(self.board, "Right Angles", [Munchable.ANGLE_RIGHT], [Munchable.ANGLE_ACUTE,Munchable.ANGLE_OBTUSE], 6)
        self.levelTwo = Level(self.board, "Acute Angles", [Munchable.ANGLE_ACUTE], [Munchable.ANGLE_RIGHT,Munchable.ANGLE_OBTUSE], 10)
        self.levelThree = Level(self.board, "Obtuse Angles", [Munchable.ANGLE_OBTUSE], [Munchable.ANGLE_ACUTE,Munchable.ANGLE_RIGHT], 12)

        #Set and generate the level
        self.board.setNewLevel(self.levelOne)

        #Create player and add it to the board
        player = Player(self.board, 0, 0)
        self.board.addPlayer(player, 2, 2)

        self.paused = False
Пример #6
0
    def apply(self, board: Board):
        if board.numAt(getOtherColor(self.color), self.end) > 1:
            raise IllegalMoveException("Other player occupies the location " + str(self.end))

        scratch = board.__deepcopy__()

        # VALID MOVEMENT, check if hit
        if scratch.numAt(getOtherColor(self.color), self.end) == 1:
            scratch.removeFromLocation(getOtherColor(self.color), self.end)
            scratch.moveToBar(getOtherColor(self.color))
            self.hit = True

        scratch.moveFromBar(self.color)
        scratch.moveToLocation(self.color, self.end)

        return scratch
Пример #7
0
    def test_0(self):
        b = Board()
        d = Dice(5, 1)
        m = generate_moves(b, "BLACK", d)

        print(b)
        print(m)
        self.assertEqual(len(m), 8)
Пример #8
0
 def __draw_piece(self, board: Board, x: int, y: int):
     piece = board.get_at_xy(y, x)
     if isinstance(piece, Empty):
         return
     str_piece = self.__show_piece(piece)
     piece_color = self.__white_piece_color if piece.get_color(
     ) == Color.WHITE else self.__black_piece_color
     self.__draw_label(piece_color, str_piece, self.__half_tile_size,
                       self.__half_tile_size, self.__piece_size)
Пример #9
0
 def play(self):
     board = Board.Board()
     while True:
         c, src, dst = next_step()
         isValid, isFinished = board.move(c, src, dst)
         self.__screen.blit(self.__background, (0, 0))
         board.getPieces(self)
         pygame.display.update()
         if isFinished:
             break
    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        #Create the screen
        self.screen = pygame.display.get_surface()

        #Create a main menu
        self.menu = Menu(self.screen)

        #Create the instruction screen
        self.instructionScreen = InstructionScreen(self.screen)

        #Create the game board
        topLeft = {'x': 40, 'y': 120}
        self.board = Board(topLeft,
                           self.screen.get_width() - (topLeft['x'] * 2),
                           self.screen.get_height() - (topLeft['y'] * 2),
                           self.screen)

        #Create levels
        self.levelOne = Level(self.board, "Right Angles",
                              [Munchable.ANGLE_RIGHT],
                              [Munchable.ANGLE_ACUTE, Munchable.ANGLE_OBTUSE],
                              6)
        self.levelTwo = Level(self.board, "Acute Angles",
                              [Munchable.ANGLE_ACUTE],
                              [Munchable.ANGLE_RIGHT, Munchable.ANGLE_OBTUSE],
                              10)
        self.levelThree = Level(self.board, "Obtuse Angles",
                                [Munchable.ANGLE_OBTUSE],
                                [Munchable.ANGLE_ACUTE, Munchable.ANGLE_RIGHT],
                                12)

        #Set and generate the level
        self.board.setNewLevel(self.levelOne)

        #Create player and add it to the board
        player = Player(self.board, 0, 0)
        self.board.addPlayer(player, 2, 2)

        self.paused = False
Пример #11
0
    def run(self):
        board = Board()
        is_piece_picked = False
        piece_src_position = None

        while True:
            for event in pygame.event.get():
                if event.type == MOUSEBUTTONUP:
                    button_up_pos = pygame.mouse.get_pos()
                    if not is_piece_picked:
                        which_piece_is_picked = self.getPieceByPosition(
                            board, button_up_pos)
                        if which_piece_is_picked != 0 and board.isTurnRight(
                                self.toBoardPos(button_up_pos)):
                            is_piece_picked = True
                            piece_src_position = button_up_pos
                            logger.info("pick an chess %s, src pos is %s",
                                        str(which_piece_is_picked),
                                        str(piece_src_position))
                    else:
                        src = self.toBoardPos(piece_src_position)
                        dst = self.toBoardPos(button_up_pos)
                        another_pick = self.getPieceByPosition(
                            board, button_up_pos)

                        # pick another self chess
                        if another_pick != 0 and board.isSameSide(src, dst):
                            which_piece_is_picked = another_pick
                            piece_src_position = button_up_pos
                            logger.info("pick another chess %s, src pos is %s",
                                        str(which_piece_is_picked),
                                        str(piece_src_position))
                            break
                        else:
                            isValid, isFinished = board.move(
                                which_piece_is_picked, src, dst)
                            if isValid:
                                is_piece_picked = False
                                piece_src_position = None
                            else:
                                logger.info('invalid move src %s, dst %s',
                                            str(src), str(dst))

                            if isFinished:
                                logger.info('finished.')

                if event.type == QUIT:
                    exit()

                self.__screen.blit(self.__background, (0, 0))
                for c in board.getPieces():
                    self.putPiece(c[0], c[1])
                pygame.display.update()
Пример #12
0
    def __init__(self, boardin, ply=3):
        self.stop = False
        self.watcher = None
        self.firstMove = None
        self.board = boardin
        self.ply = ply
        self.move = None
        self.move_log = []
        time.sleep(0)

        if Board.must_pass(self.board):
            print('Forced pass')
            new_board_move = Boardmove(self.board, 0)
            self.set_board_move(new_board_move)
            self.done()
            return

        mg = MoveGenerator(self.board)
        if not (mg.hasMoreElements()):
            return

        nextmove = mg.nextSet()
        new_board_move = Boardmove(self.board, nextmove)
        self.set_board_move(new_board_move)
        if not (mg.hasMoreElements()):
            print("Forced move")
            self.board.forced = True
            self.board.arbmove = nextmove
            self.done()
            return

        if Board.endgameDatabase is not None:
            self.set_board_move(self.board.principalVariation)
            self.done()
            return

        self.search()
Пример #13
0
    def build_board(length, width, content):
        board = Board(length, width)
        current_line = 0
        current_row = 0
        for line in content:
            pieces = line.split(',')
            for piece in pieces:
                color = Color.get_color(piece[0])

                # TODO hardcoded
                if len(piece) == 3:
                    board.add_piece(Position(current_line, current_row),
                                    PieceFactory.build_used_pawn(color))
                else:
                    board.add_piece(Position(current_line, current_row),
                                    PieceFactory.build_piece(piece[1], color))

                current_row += 1
            current_row = 0
            current_line += 1
        return board
Пример #14
0
    def test_0(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[1] = -3
        b.pointsContent[2] = 6
        b.pointsContent[3] = 4
        b.pointsContent[6] = 2
        b.pointsContent[4] = 1
        b.pointsContent[13] = -1
        b.pointsContent[19] = -4
        b.pointsContent[20] = 2
        b.pointsContent[22] = -1
        b.pointsContent[23] = -4
        b.pointsContent[24] = -2

        b.whiteCheckers = {1, 13, 19, 22, 23, 24}
        b.blackCheckers = {2, 3, 4, 6, 20}
        b.blackCheckersTaken = 0
        b.whiteCheckersTaken = 0

        d = Dice(4, 1)

        print(b)
        current = MoveNode("start", board_after=b, deep=0)
        ab = alpha_beta(current, 2, "BLACK", dice=d)
        mm = expectiminimax(current, 2, "BLACK", dice=d)
        print(ab)
        print(mm)
Пример #15
0
    def test_12(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[2] = 5
        b.pointsContent[3] = -1
        b.pointsContent[4] = 1
        b.pointsContent[5] = 1
        b.pointsContent[6] = 3
        b.pointsContent[13] = 1
        b.pointsContent[16] = -2
        b.pointsContent[18] = -2
        b.pointsContent[19] = -3
        b.pointsContent[20] = -2
        b.pointsContent[21] = -2
        b.pointsContent[22] = -2
        b.pointsContent[23] = -1
        b.pointsContent[24] = 3
        b.whiteCheckers = {3, 16, 18, 19, 20, 21, 22, 23}
        b.blackCheckers = {24, 13, 6, 5, 4, 2}
        b.whiteCheckersTaken = 0
        b.blackCheckersTaken = 1

        d = Dice(4, 1)
        m = generate_moves(b, "BLACK", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 3)
Пример #16
0
    def test_11(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[1] = -1
        b.pointsContent[2] = 1
        b.pointsContent[4] = 1
        b.pointsContent[5] = 2
        b.pointsContent[6] = 3
        b.pointsContent[8] = 1
        b.pointsContent[13] = 5
        b.pointsContent[18] = -1
        b.pointsContent[21] = -12
        b.pointsContent[24] = 2
        b.whiteCheckers = {1, 18, 21}
        b.blackCheckers = {24, 13, 8, 6, 5, 4, 2}
        b.whiteCheckersTaken = 1
        b.blackCheckersTaken = 0

        d = Dice(4, 2)
        m = generate_moves(b, "WHITE", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 4)
Пример #17
0
    def test_9(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[1] = -2
        b.pointsContent[6] = 5
        b.pointsContent[7] = 3
        b.pointsContent[8] = 4
        b.pointsContent[12] = -4
        b.pointsContent[13] = -1
        b.pointsContent[18] = 2
        b.pointsContent[19] = -3
        b.pointsContent[21] = -2
        b.pointsContent[23] = -2
        b.pointsContent[24] = -1

        b.whiteCheckers = {1, 12, 13, 19, 21, 23, 24}
        b.blackCheckers = {6, 7, 8, 18}
        b.whiteCheckersTaken = 0
        b.blackCheckersTaken = 1

        d = Dice(4, 1)
        m = generate_moves(b, "BLACK", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 5)
Пример #18
0
    def test_8(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[7] = -2
        b.pointsContent[12] = -5
        b.pointsContent[17] = -3
        b.pointsContent[19] = -5
        b.pointsContent[8] = 1
        b.pointsContent[3] = 3
        b.pointsContent[1] = 10
        b.pointsContent[0] = 1
        b.whiteCheckers = {7, 12, 17, 19}
        b.blackCheckers = {8, 3, 1}
        b.blackCheckersTaken = 0
        b.whiteCheckersTaken = 0

        d = Dice(2, 2)
        m = generate_moves(b, "BLACK", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 4)
Пример #19
0
class Backgammon:
    def __init__(self, player1, player2):
        if not {player1.color, player2.color} == {WHITE, BLACK}:
            raise Exception("Must have one player of each color")
        self.players = [player1, player2]
        self.board = Board()
        self.dice = Dice()
        self.on_roll = 0  # starting player 1

    def reset(self):
        self.board = Board()
        self.on_roll = 0

    def do_move(self, move):
        self.board.applyBoard(move.board_after)
        self.dice.roll()
        self.on_roll = (self.on_roll + 1) % 2

    def get_current_player(self):
        return self.players[self.on_roll]

    def start_game(self, verbose=False):
        player1_roll, player2_roll = 0, 0
        while player1_roll == player2_roll:
            player1_roll = random.randint(1, 6)
            player2_roll = random.randint(1, 6)
            if verbose:
                print(self.players[0], "rolls",
                      str(player1_roll) + ",", self.players[1], "rolls",
                      str(player2_roll) + ".")
        self.on_roll = 0 if player1_roll > player2_roll else 1
        self.dice.setRoll((player1_roll, player2_roll))

    def run(self, verbose=False):
        self.start_game(verbose=verbose)
        if verbose:
            print(self.board)
            print(str(self.players[self.on_roll]) + " goes first.")
        while True:
            if verbose:
                print("")
                print(
                    str(self.players[self.on_roll]) + " rolled " +
                    str(self.dice))
            move = self.players[self.on_roll].get_move(self)
            self.do_move(move)
            if verbose:
                print(self.board)
                print(move)
            winner, value = self.board.getWinner(game_value=True)
            if winner != NONE:
                if self.players[0].color == winner:
                    self.players[0].won(self.board, value)
                    self.players[1].lost(self.board, value)
                else:
                    self.players[0].lost(self.board, value)
                    self.players[1].won(self.board, value)
                if verbose:
                    print("Winner, " + winner)
                return winner, value
            ##################################################
            if verbose:
                print("")
                print(
                    str(self.players[self.on_roll]) + " rolled " +
                    str(self.dice))
            move = self.players[self.on_roll].get_move(self)
            self.do_move(move)
            if verbose:
                print(self.board)
                print(move)
            winner, value = self.board.getWinner(game_value=True)
            if winner != NONE:
                if self.players[0].color == winner:
                    self.players[0].won(self.board, value)
                    self.players[1].lost(self.board, value)
                else:
                    self.players[0].lost(self.board, value)
                    self.players[1].won(self.board, value)
                if verbose:
                    print("Winner, " + winner)
                return winner, value

    @staticmethod
    def train(network, iters, start_trial=0, verbose=False):
        p1, p2 = NeuralNetPlayer(BLACK, network,
                                 learning=True), NeuralNetPlayer(WHITE,
                                                                 network,
                                                                 learning=True)
        backgammon = Backgammon(p1, p2)
        for i in range(1, iters + 1):
            winner, _ = backgammon.run()
            backgammon.reset()
            print("\rGame", i + start_trial, "finished", end="")
            if i % 1000 == 0:
                p1.network.save()
                p1.network.save_to_text(str(i + start_trial) + ".txt")
                p1.learning = False
                print("After", i + start_trial, "rounds of training:")
                Backgammon.benchmark(p1, TatePlayer(WHITE), 15)
                p1.learning = True

    @staticmethod
    def benchmark(player1, player2, num_games):
        scores = {BLACK: 0, WHITE: 0}
        wins = {BLACK: 0, WHITE: 0}
        back = Backgammon(player1, player2)
        for i in range(num_games):
            winner, value = back.run(verbose=False)
            print("\rGame",
                  str(i + 1) + ":",
                  winner,
                  "wins a",
                  value,
                  "game",
                  end="")
            scores[winner] += value
            wins[winner] += 1
            back.reset()
        print(scores)
        print(wins)
        return scores
Пример #20
0
 def test_constructor(self):
     board = Board(8, 8)
Пример #21
0
 def test_tile_is_empty(self):
     # assert not board.tile_is_empty(Position(0, 0)), 'Tile not empty'
     # assert board.tile_is_empty(Position(0, 2))
     # TODO Assert raise
     board = Board(8, 8)
class NumberMunchersGame:

    #Game state determines where we are in the game
    #0 is menu, 1 is instructions screen, 2 is game
    gameState = 0

    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        #Create the screen
        self.screen = pygame.display.get_surface()

        #Create a main menu
        self.menu = Menu(self.screen)

        #Create the instruction screen
        self.instructionScreen = InstructionScreen(self.screen)

        #Create the game board
        topLeft = {'x': 40, 'y': 120}
        self.board = Board(topLeft,
                           self.screen.get_width() - (topLeft['x'] * 2),
                           self.screen.get_height() - (topLeft['y'] * 2),
                           self.screen)

        #Create levels
        self.levelOne = Level(self.board, "Right Angles",
                              [Munchable.ANGLE_RIGHT],
                              [Munchable.ANGLE_ACUTE, Munchable.ANGLE_OBTUSE],
                              6)
        self.levelTwo = Level(self.board, "Acute Angles",
                              [Munchable.ANGLE_ACUTE],
                              [Munchable.ANGLE_RIGHT, Munchable.ANGLE_OBTUSE],
                              10)
        self.levelThree = Level(self.board, "Obtuse Angles",
                                [Munchable.ANGLE_OBTUSE],
                                [Munchable.ANGLE_ACUTE, Munchable.ANGLE_RIGHT],
                                12)

        #Set and generate the level
        self.board.setNewLevel(self.levelOne)

        #Create player and add it to the board
        player = Player(self.board, 0, 0)
        self.board.addPlayer(player, 2, 2)

        self.paused = False

    def set_paused(self, paused):
        self.paused = paused

    # Called to save the state of the game to the Journal.
    def write_file(self, file_path):
        pass

    # Called to load the state of the game from the Journal.
    def read_file(self, file_path):
        pass

    #Event handling and logic goes here
    def events(self):
        # Pump PyGame messages.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            elif event.type == pygame.VIDEORESIZE:
                pygame.display.set_mode(event.size, pygame.RESIZABLE)

            if NumberMunchersGame.gameState == 0:
                if event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:
                    self.menu.events(event)

            elif NumberMunchersGame.gameState == 1:
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    self.instructionScreen.events(event)

            elif NumberMunchersGame.gameState == 2:
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    self.board.events(event)

    #Update logic goes here
    def update(self):
        if not self.paused:
            return

    #Rendering logic goes here
    def draw(self):
        # Clear Display
        self.screen.fill((0, 0, 0))

        # Draw the menu
        if NumberMunchersGame.gameState == 0:
            self.menu.draw()

        # Draw the instructions screen
        elif NumberMunchersGame.gameState == 1:
            self.instructionScreen.draw()

        # Draw the game
        elif NumberMunchersGame.gameState == 2:
            self.board.draw()

        # Flip Display
        pygame.display.flip()

        if self.board.getReset():
            NumberMunchersGame.gameState = 0
            self.board.setNewLevel(self.levelOne)
            self.board.resetBoard()

    # The main game loop.
    def run(self):
        self.running = True

        while self.running:
            # Pump GTK messages.
            #while Gtk.events_pending():
            #    Gtk.main_iteration()

            #Handle events
            self.events()

            #Handle game logic
            self.update()

            #Handle rendering
            self.draw()

            # Try to stay at 30 FPS
            self.clock.tick(30)
Пример #23
0
 def reset(self):
     self.board = Board()
     self.on_roll = 0
Пример #24
0
    def test_3(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[1] = -1
        b.pointsContent[12] = -6
        b.pointsContent[17] = -3
        b.pointsContent[19] = -5
        b.pointsContent[2] = 14
        b.pointsContent[7] = 1
        b.whiteCheckers = {1, 12, 17, 19}
        b.blackCheckers = {2, 7}
        b.blackCheckersTaken = 0
        b.whiteCheckersTaken = 0

        d = Dice(1, 2)
        m = generate_moves(b, "BLACK", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 3)
Пример #25
0
    def test_4(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[1] = -1
        b.pointsContent[2] = 2
        b.pointsContent[4] = 1
        b.pointsContent[5] = 1
        b.pointsContent[6] = 3
        b.pointsContent[8] = 1
        b.pointsContent[12] = -5
        b.pointsContent[13] = 5
        b.pointsContent[17] = -2
        b.pointsContent[19] = -4
        b.pointsContent[20] = -1
        b.pointsContent[22] = -1
        b.pointsContent[24] = 2
        b.whiteCheckers = {1, 12, 17, 19, 20, 22}
        b.blackCheckers = {24, 13, 8, 6, 5, 4, 2}
        b.whiteCheckersTaken = 1
        b.blackCheckersTaken = 0

        d = Dice(4, 2)
        m = generate_moves(b, "WHITE", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 5)
class NumberMunchersGame:

    #Game state determines where we are in the game
    #0 is menu, 1 is game
    gameState = 0

    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        #Create the screen
        self.screen = pygame.display.get_surface()

        #Create a main menu
        self.menu = Menu(self.screen)

        #Create the game board
        topLeft = {'x': 40, 'y': 120}
        self.board = Board(topLeft, self.screen.get_width() - (topLeft['x'] * 2), self.screen.get_height() - (topLeft['y'] * 2), self.screen)

        #Create levels
        self.levelOne = Level(self.board, "Right Angles", [Munchable.ANGLE_RIGHT], [Munchable.ANGLE_ACUTE,Munchable.ANGLE_OBTUSE], 6)
        self.levelTwo = Level(self.board, "Acute Angles", [Munchable.ANGLE_ACUTE], [Munchable.ANGLE_RIGHT,Munchable.ANGLE_OBTUSE], 10)
        self.levelThree = Level(self.board, "Obtuse Angles", [Munchable.ANGLE_OBTUSE], [Munchable.ANGLE_ACUTE,Munchable.ANGLE_RIGHT], 12)

        #Set and generate the level
        self.board.setNewLevel(self.levelOne)

        #Create player and add it to the board
        player = Player(self.board, 0, 0)
        self.board.addPlayer(player, 2, 2)

        self.paused = False

    def set_paused(self, paused):
        self.paused = paused

    # Called to save the state of the game to the Journal.
    def write_file(self, file_path):
        pass

    # Called to load the state of the game from the Journal.
    def read_file(self, file_path):
        pass

    #Event handling and logic goes here
    def events(self):
        # Pump PyGame messages.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            elif event.type == pygame.VIDEORESIZE:
                pygame.display.set_mode(event.size, pygame.RESIZABLE)

            if NumberMunchersGame.gameState == 0:
                if event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:
                    self.menu.events(event)

            elif NumberMunchersGame.gameState == 1:
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    self.board.events(event)

    #Update logic goes here
    def update(self):
        if not self.paused:
            return

    #Rendering logic goes here
    def draw(self):
        # Clear Display
        self.screen.fill((0, 0, 0))

        # Draw the menu
        if NumberMunchersGame.gameState == 0:
            self.menu.draw()

        # Draw the game
        elif NumberMunchersGame.gameState == 1:
            self.board.draw();

        # Flip Display
        pygame.display.flip()

        if self.board.getReset():
            NumberMunchersGame.gameState = 0
            self.board.setNewLevel(self.levelOne)
            self.board.resetBoard()

    # The main game loop.
    def run(self):
        self.running = True

        while self.running:
            # Pump GTK messages.
            #while Gtk.events_pending():
            #    Gtk.main_iteration()

            #Handle events
            self.events()

            #Handle game logic
            self.update()

            #Handle rendering
            self.draw()

            # Try to stay at 30 FPS
            self.clock.tick(30)
Пример #27
0
    def test_5(self):
        b = Board()
        b.pointsContent = [0] * 26
        b.pointsContent[1] = -2
        b.pointsContent[12] = -5
        b.pointsContent[17] = -3
        b.pointsContent[19] = -5
        b.pointsContent[24] = 2
        b.pointsContent[13] = 5
        b.pointsContent[4] = 3
        b.pointsContent[6] = 5
        b.whiteCheckers = {12, 17, 19}
        b.blackCheckers = {24, 13, 6, 4}
        b.whiteCheckersTaken = 2
        b.blackCheckersTaken = 0

        d = Dice(4, 6)
        m = generate_moves(b, "WHITE", d)
        print(b)
        print(m)

        self.assertEqual(len(m), 1)
Пример #28
0
def index():
    board_class = Board()
    board = utils.PiecesOnBoard(board_class.myPieces,
                                board_class.opponentPieces)
    return render_template("index.html", board=board)