def test_init_success(self):
        # Tests successful Avatar constructor
        player = PlayerEntity('seth', Color.WHITE)

        self.assertEqual(player.name, 'seth')
        self.assertEqual(player.color, Color.WHITE)
        self.assertEqual(player.score, 0)
        self.assertEqual(player.places, [])
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super(RemotePlayerProxyTests, self).__init__(*args, **kwargs)
        self.port = 3003

        # Initialize some players for testing
        self.__p1 = PlayerEntity("John", Color.RED)
        self.__p2 = PlayerEntity("George", Color.WHITE)
        self.__p3 = PlayerEntity("Gary", Color.BLACK)
        self.__p4 = PlayerEntity("Jeanine", Color.BROWN)

        # Initialize board for testing
        self.__b = Board.homogeneous(5, 5, 3)

        # Initialize sockets for testing
        self.dummy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.mock_socket = mock.Mock()
        self.sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    def test_score_success(self):
        # Tests successful score setter & getter
        player = PlayerEntity('iBot', Color.WHITE)

        # Increment player's score by 10
        player.score += 10

        # Run check
        self.assertEqual(player.score, 10)
Ejemplo n.º 4
0
    def test_state_to_json_success1(self):
        # Successful state to json. State is one in which
        # all avatars have been placed
        state = State(Board.homogeneous(4, 4, 3), [
            PlayerEntity('bob', Color.WHITE),
            PlayerEntity('bob', Color.BROWN),
            PlayerEntity('bob', Color.BLACK)
        ])

        # Player 1 place
        state.place_avatar(Color.WHITE, Position(0, 1))
        # Player 2 place
        state.place_avatar(Color.BROWN, Position(1, 0))
        # Player 3 place
        state.place_avatar(Color.BLACK, Position(1, 1))
        # Player 1 place
        state.place_avatar(Color.WHITE, Position(1, 2))
        # Player 2 place
        state.place_avatar(Color.BROWN, Position(2, 0))
        # Player 3 place
        state.place_avatar(Color.BLACK, Position(2, 1))
        # Player 1 place
        state.place_avatar(Color.WHITE, Position(2, 2))
        # Player 2 place
        state.place_avatar(Color.BROWN, Position(3, 1))
        # Player 3 place
        state.place_avatar(Color.BLACK, Position(3, 2))

        # Get jsonified version
        result = _state_to_json(state)

        # Make up expected json
        expected_json = {
            'players': [
                {'score': 0, 'places': [[0, 1], [1, 2], [2, 2]], 'color': 'white'},
                {'score': 0, 'places': [[1, 0], [2, 0], [3, 1]], 'color': 'brown'},
                {'score': 0, 'places': [[1, 1], [2, 1], [3, 2]], 'color': 'black'}
            ],
            'board': [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]
        }

        self.assertDictEqual(result, expected_json)
    def test_swap_places_success1(self):
        # Tests a successful swap_places
        player = PlayerEntity('seth', Color.WHITE)

        # Add places
        player.add_place(Position(1, 0))
        player.add_place(Position(2, 0))

        # Swap
        player.swap_places(Position(1, 0), Position(2, 1))
        self.assertEqual(player.places, [Position(2, 1), Position(2, 0)])

        # Swap
        player.swap_places(Position(2, 0), Position(2, 2))
        self.assertEqual(player.places, [Position(2, 1), Position(2, 2)])
    def test_add_place_success1(self):
        # Tests a series of successful add_place calls
        player = PlayerEntity('seth', Color.WHITE)

        player.add_place(Position(1, 0))
        self.assertEqual(player.places, [Position(1, 0)])

        player.add_place(Position(2, 0))
        self.assertEqual(player.places, [Position(1, 0), Position(2, 0)])

        player.add_place(Position(5, 3))
        self.assertEqual(
            player.places,
            [Position(1, 0), Position(2, 0),
             Position(5, 3)])
Ejemplo n.º 7
0
    def test_state_to_json_success3(self):
        # Successful state to json. State is one in which
        # no avatars have been placed
        state = State(Board.homogeneous(4, 4, 3), [
            PlayerEntity('bob', Color.WHITE),
            PlayerEntity('bob', Color.BROWN),
            PlayerEntity('bob', Color.BLACK)
        ])

        # Get jsonified version
        result = _state_to_json(state)

        # Make up expected json
        expected_json = {
            'players': [
                {'score': 0, 'places': [], 'color': 'white'},
                {'score': 0, 'places': [], 'color': 'brown'},
                {'score': 0, 'places': [], 'color': 'black'}
            ],
            'board': [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]
        }

        self.assertDictEqual(result, expected_json)
    def test_swap_places_fail3(self):
        # Tests a failing swap_places due to invalid src (non existent)
        player = PlayerEntity('seth', Color.WHITE)

        player.add_place(Position(1, 0))
        player.add_place(Position(2, 0))

        with self.assertRaises(ValueError):
            player.swap_places(Position(1, 1), Position(2, 1))
    def test_swap_places_fail2(self):
        # Tests a failing swap_places due to invalid dst (type-wise)
        player = PlayerEntity('seth', Color.WHITE)

        player.add_place(Position(1, 0))
        player.add_place(Position(2, 0))

        with self.assertRaises(TypeError):
            player.swap_places(Position(1, 0), '')
Ejemplo n.º 10
0
    def __init__(self, *args, **kwargs):
        super(PlayerTests, self).__init__(*args, **kwargs)

        # Initialize boards
        self.__board1 = Board.homogeneous(2, 5, 3)

        # Initialize some players for testing
        self.__p1 = PlayerEntity("John", Color.RED)
        self.__p2 = PlayerEntity("George", Color.WHITE)
        self.__p3 = PlayerEntity("Gary", Color.BLACK)

        self.__p4 = PlayerEntity("Bot X", Color.RED)
        self.__p5 = PlayerEntity("Bot Y", Color.BROWN)
        self.__p6 = PlayerEntity("Bot Z", Color.BLACK)
        self.__p7 = PlayerEntity("Bot W", Color.WHITE)

        # ========================== STATE 1 ==========================

        # Initialize a premature state
        self.__state1 = State(self.__board1,
                              [self.__p4, self.__p5, self.__p6, self.__p7])

        # ========================== STATE 2 ==========================

        # Initialize a finalized state where at least two more rounds are possible
        self.__state2 = State(self.__board1, [self.__p1, self.__p2, self.__p3])
        # Place all avatars
        # Player 1 place
        self.__state2.place_avatar(Color.RED, Position(4, 2))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE, Position(0, 1))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK, Position(2, 1))
        # Player 1 place
        self.__state2.place_avatar(Color.RED, Position(1, 0))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE, Position(2, 0))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK, Position(3, 1))
        # Player 1 place
        self.__state2.place_avatar(Color.RED, Position(1, 1))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE, Position(4, 1))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK, Position(3, 0))
Ejemplo n.º 11
0
    def __init__(self, *args, **kwargs):
        super(GameTreeTests, self).__init__(*args, **kwargs)

        # Initialize boards
        self.__board1 = Board.homogeneous(5, 5, 3)
        self.__board2 = Board.homogeneous(3, 5, 2)
        self.__board3 = Board({
            Position(0, 0): Tile(5),
            Position(0, 1): Tile(3),
            Position(0, 2): Tile(2),
            Position(1, 0): Tile(2),
            Position(1, 1): Tile(3),
            Position(1, 2): Tile(2),
            Position(2, 0): Tile(3),
            Position(2, 1): Tile(4),
            Position(2, 2): Tile(1),
            Position(3, 0): Tile(1),
            Position(3, 1): Tile(1),
            Position(3, 2): Tile(5),
            Position(4, 0): Tile(2),
            Position(4, 1): Tile(3),
            Position(4, 2): Tile(4)
        })

        # Initialize some players for testing
        self.__p1 = PlayerEntity("John", Color.RED)
        self.__p2 = PlayerEntity("George", Color.WHITE)
        self.__p3 = PlayerEntity("Gary", Color.BLACK)
        self.__p4 = PlayerEntity("Jeanine", Color.BROWN)
        self.__p5 = PlayerEntity("Obama", Color.RED)
        self.__p6 = PlayerEntity("Fred", Color.BROWN)
        self.__p7 = PlayerEntity("Stewart", Color.WHITE)
        self.__p8 = PlayerEntity("Bobby Mon", Color.BLACK)
        self.__p9 = PlayerEntity("Bob Ross", Color.WHITE)
        self.__p10 = PlayerEntity("Eric Khart", Color.BROWN)
        self.__p11 = PlayerEntity("Ionut", Color.RED)

        # ========================== STATE 1 ==========================

        # Initialize a premature state
        self.__state1 = State(self.__board1,
                              [self.__p1, self.__p2, self.__p3, self.__p4])

        # ========================== STATE 2 ==========================

        # Initialize a finalized state where at least two more rounds are possible
        self.__state2 = State(self.__board1, [self.__p1, self.__p2, self.__p3])
        # Place all avatars
        # Player 1 place
        self.__state2.place_avatar(Color.RED, Position(4, 0))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE, Position(0, 1))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK, Position(2, 2))
        # Player 1 place
        self.__state2.place_avatar(Color.RED, Position(1, 0))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE, Position(2, 0))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK, Position(3, 2))
        # Player 1 place
        self.__state2.place_avatar(Color.RED, Position(1, 1))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE, Position(4, 1))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK, Position(3, 0))

        # Make up tree for this state
        self.__tree2 = GameTree(self.__state2)

        # ========================== STATE 3 ==========================
        # Setup state that is one move away from game over
        self.__state3 = State(
            self.__board2,
            players=[self.__p5, self.__p6, self.__p7, self.__p8])

        # Set up the board with placements s.t. only 2 moves can be made
        # Player 1
        self.__state3.place_avatar(Color.RED, Position(3, 0))
        # Player 2
        self.__state3.place_avatar(Color.BROWN, Position(0, 0))
        # Player 3
        self.__state3.place_avatar(Color.WHITE, Position(1, 0))
        # Player 4
        self.__state3.place_avatar(Color.BLACK, Position(2, 0))
        # Player 1
        self.__state3.place_avatar(Color.RED, Position(3, 1))
        # Player 2
        self.__state3.place_avatar(Color.BROWN, Position(0, 1))
        # Player 3
        self.__state3.place_avatar(Color.WHITE, Position(1, 1))
        # Player 4
        self.__state3.place_avatar(Color.BLACK, Position(2, 1))
        # Make move 1 for p1
        self.__state3.move_avatar(Position(3, 1), Position(4, 1))

        # Make up tree for this state
        self.__tree3 = GameTree(self.__state3)

        # ========================== STATE 4 ==========================
        # Setup state that is game over
        self.__state4 = copy.deepcopy(self.__state3)

        # Make final move
        self.__state4.move_avatar(Position(2, 0), Position(4, 0))

        # Make up tree for this state
        self.__tree4 = GameTree(self.__state4)

        # ========================== STATE 5 ==========================
        # Setup state that includes heterogeneous board
        self.__state5 = State(self.__board3,
                              players=[self.__p9, self.__p10, self.__p11])

        # Player 1
        self.__state5.place_avatar(Color.WHITE, Position(2, 0))
        # Player 2
        self.__state5.place_avatar(Color.BROWN, Position(0, 1))
        # Player 3
        self.__state5.place_avatar(Color.RED, Position(0, 2))
        # Player 1
        self.__state5.place_avatar(Color.WHITE, Position(1, 0))
        # Player 2
        self.__state5.place_avatar(Color.BROWN, Position(1, 2))
        # Player 3
        self.__state5.place_avatar(Color.RED, Position(0, 0))
        # Player 1
        self.__state5.place_avatar(Color.WHITE, Position(3, 1))
        # Player 2
        self.__state5.place_avatar(Color.BROWN, Position(2, 1))
        # Player 3
        self.__state5.place_avatar(Color.RED, Position(3, 2))

        # Make up tree for this state
        self.__tree5 = GameTree(self.__state5)
Ejemplo n.º 12
0
    def __init__(self, rows: int, cols: int, players: [IPlayer], fish_no: int = None) -> None:
        """
        Initializes a referee for a game with a board of size row x col and a given (ordered) list of IPlayer
        objects.

        :param rows: row dimension of the board
        :param cols: column dimension of the board
        :param players: list of IPlayer objects sorted in increasing order of age
        :param fish_no: Number of fish to be placed on each tile on the board
        :return: None
        """
        # Validate params
        if not isinstance(rows, int) or rows <= 0:
            raise TypeError('Expected positive int for rows!')

        if not isinstance(cols, int) or cols <= 0:
            raise TypeError('Expected positive int for cols!')

        if not isinstance(players, list):
            raise TypeError('Expected list for players!')

        # Make sure list consists of only IPlayer objects
        if not all(isinstance(x, IPlayer) for x in players):
            raise TypeError('All player list objects have to of type IPlayer!')

        # Make sure we weren't given too many players
        if len(players) < ct.MIN_PLAYERS or len(players) > ct.MAX_PLAYERS:
            raise ValueError(f'Invalid player length; length has to be between {ct.MIN_PLAYERS} and'
                             f' {ct.MAX_PLAYERS}')

        # Make sure dimensions are large enough to accommodate all players
        if cols * rows < len(players):
            raise ValueError('Board dimensions are too small to accomodate all players!')

        # Make sure fish is between 1 and 5 or is equal to None (default value, means that the user didn't specify a
        # fish number.
        if fish_no is not None and \
                (not isinstance(fish_no, int) or fish_no < ct.MIN_FISH_PER_TILE or fish_no > ct.MAX_FISH_PER_TILE):
            raise ValueError('Expected positive int between 1 and 5 inclusive for fish!')

        # Set properties
        self.__players: [IPlayer] = players
        self.__avatars_per_player = 6 - len(players)

        # Make up list of IPlayer holding failing players
        self.__failing_players: [IPlayer] = []
        # Make up list of IPlayer holding cheating players
        self.__cheating_players: [IPlayer] = []

        # Initialize game update callbacks as a list of callable items called every time
        # the state of the game changes
        self.__game_update_callbacks = []

        # Initializes game over callbacks as a list of callable items called at the end
        # of the game together with the game report
        self.__game_over_callbacks = []

        # Make up a board
        self.__board = self.__make_board(cols, rows, fish_no)

        # Send player's color information
        self.__notify_player_colors()

        # Make up state from board & list of PlayerEntity objects
        self.__state = State(self.__board, [PlayerEntity(p.name, p.color) for p in players])
        # Initialize game tree placeholder
        self.__game_tree = None

        # Make up flag to indicate whether the game has started
        self.__started = False
        # Make up flag to indicate whether the game has ended
        self.__game_over = False
        # Initialize empty game report that will be fleshed out at game end
        self.__report = {}
        # Initialize empty list of IPlayer to hold winners (player(s) with the highest score in the game)
        self.__winners = []
        # Initialize empty list of IPlayer to hold losers
        self.__losers = []
Ejemplo n.º 13
0
    def __init__(self, *args, **kwargs):
        super(StrategyTests, self).__init__(*args, **kwargs)

        # Initialize boards
        self.__board1 = Board.homogeneous(2, 5, 3)
        self.__board2 = Board.homogeneous(3, 5, 2)
        self.__board3 = Board({
            Position(0, 0): Tile(5),
            Position(0, 1): Tile(3),
            Position(0, 2): Tile(2),
            Position(1, 0): Tile(2),
            Position(1, 1): Tile(3),
            Position(1, 2): Tile(2),
            Position(2, 0): Tile(3),
            Position(2, 1): Tile(4),
            Position(2, 2): Tile(1),
            Position(3, 0): Tile(1),
            Position(3, 1): Tile(1),
            Position(3, 2): Tile(5),
            Position(4, 0): Tile(2),
            Position(4, 1): Tile(3),
            Position(4, 2): Tile(4)
        })

        self.__board4 = Board({
            Position(0, 0): Tile(5),
            Position(0, 1): Tile(3),
            Position(0, 2): Hole(),
            Position(1, 0): Tile(2),
            Position(1, 1): Tile(3),
            Position(1, 2): Hole(),
            Position(2, 0): Hole(),
            Position(2, 1): Tile(4),
            Position(2, 2): Hole(),
            Position(3, 0): Tile(1),
            Position(3, 1): Tile(1),
            Position(3, 2): Tile(5),
            Position(4, 0): Hole(),
            Position(4, 1): Tile(3),
            Position(4, 2): Tile(4)
        })

        self.__board5 = Board.homogeneous(2, 5, 5)

        # Initialize some players for testing
        self.__p1 = PlayerEntity("John", Color.RED)
        self.__p2 = PlayerEntity("George", Color.WHITE)
        self.__p3 = PlayerEntity("Gary", Color.BLACK)
        self.__p4 = PlayerEntity("Jeanine", Color.BROWN)
        self.__p5 = PlayerEntity("Obama", Color.RED)
        self.__p6 = PlayerEntity("Fred", Color.BROWN)
        self.__p7 = PlayerEntity("Stewart", Color.WHITE)
        self.__p8 = PlayerEntity("Bobby Mon", Color.BLACK)
        self.__p9 = PlayerEntity("Bob Ross", Color.RED)
        self.__p10 = PlayerEntity("Eric Khart", Color.BROWN)
        self.__p11 = PlayerEntity("Ionut", Color.BLACK)
        self.__p12 = PlayerEntity("Bot 1", Color.RED)
        self.__p13 = PlayerEntity("Bot 2", Color.BROWN)
        self.__p14 = PlayerEntity("Bot 3", Color.WHITE)
        self.__p15 = PlayerEntity("Bot X", Color.RED)
        self.__p16 = PlayerEntity("Bot Y", Color.BROWN)
        self.__p17 = PlayerEntity("Bot Z", Color.BLACK)
        self.__p18 = PlayerEntity("Bot W", Color.WHITE)
        self.__p19 = PlayerEntity("a", Color.RED)
        self.__p20 = PlayerEntity("b", Color.BROWN)
        self.__p21 = PlayerEntity("c", Color.WHITE)
        self.__p22 = PlayerEntity("d", Color.BLACK)

        # ========================== STATE 1 ==========================

        # Initialize a premature state
        self.__state1 = State(self.__board1, [self.__p15, self.__p16, self.__p17, self.__p18])

        # ========================== STATE 2 ==========================

        # Initialize a finalized state where at least two more rounds are possible
        self.__state2 = State(self.__board1, [self.__p1, self.__p2, self.__p3])
        # Place all avatars
        # Player 1 place
        self.__state2.place_avatar(Color.RED,  Position(4, 2))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE,  Position(0, 1))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK,  Position(2, 1))
        # Player 1 place
        self.__state2.place_avatar(Color.RED,  Position(1, 0))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE,  Position(2, 0))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK,  Position(3, 1))
        # Player 1 place
        self.__state2.place_avatar(Color.RED,  Position(1, 1))
        # Player 2 place
        self.__state2.place_avatar(Color.WHITE,  Position(4, 1))
        # Player 3 place
        self.__state2.place_avatar(Color.BLACK,  Position(3, 0))

        # Make up game tree for state 2
        self.__tree2 = GameTree(self.__state2)

        # ========================== STATE 3 ==========================
        # Setup state that is one move away from game over
        self.__state3 = State(self.__board2, players=[
            self.__p5,
            self.__p6,
            self.__p7,
            self.__p8])

        # Player 1
        self.__state3.place_avatar(Color.RED,  Position(3, 0))
        # Player 2
        self.__state3.place_avatar(Color.BROWN,  Position(0, 0))
        # Player 3
        self.__state3.place_avatar(Color.WHITE,  Position(1, 0))
        # Player 4
        self.__state3.place_avatar(Color.BLACK,  Position(2, 0))
        # Player 1
        self.__state3.place_avatar(Color.RED,  Position(3, 1))
        # Player 2
        self.__state3.place_avatar(Color.BROWN,  Position(0, 1))
        # Player 3
        self.__state3.place_avatar(Color.WHITE,  Position(1, 1))
        # Player 4
        self.__state3.place_avatar(Color.BLACK,  Position(2, 1))
        # Make move 1 for p1
        self.__state3.move_avatar(Position(3, 1), Position(4, 1))

        # Player 1 has a score of 3 now
        # Make up tree for state 3
        self.__tree3 = GameTree(self.__state3)

        # ========================== STATE 4 ==========================
        # Setup state that is game over
        self.__state4 = self.__state3.deepcopy()

        # Make final move on behalf of Player 4
        self.__state4.move_avatar(Position(2, 0), Position(4, 0))
        # Player 4 has a score of 3 now

        # Make up tree for state 4
        self.__tree4 = GameTree(self.__state4)

        # ========================== STATE 5 ==========================
        # Setup state that includes heterogeneous board
        self.__state5 = State(self.__board3, players=[
            self.__p9,
            self.__p10,
            self.__p11])

        # Player 1
        self.__state5.place_avatar(Color.RED,  Position(2, 0))
        # Player 2
        self.__state5.place_avatar(Color.BROWN,  Position(0, 1))
        # Player 3
        self.__state5.place_avatar(Color.BLACK,   Position(0, 2))
        # Player 1
        self.__state5.place_avatar(Color.RED,  Position(1, 0))
        # Player 2
        self.__state5.place_avatar(Color.BROWN,  Position(1, 2))
        # Player 3
        self.__state5.place_avatar(Color.BLACK,   Position(0, 0))
        # Player 1
        self.__state5.place_avatar(Color.RED,  Position(3, 1))
        # Player 2
        self.__state5.place_avatar(Color.BROWN,  Position(2, 1))
        # Player 3
        self.__state5.place_avatar(Color.BLACK,   Position(3, 2))

        # Make up tree for state 5
        self.__tree5 = GameTree(self.__state5)

        # ========================== STATE 6 ==========================
        # Setup state that includes heterogeneous board riddled with a lot of holes
        # and with no avatars on it
        self.__state6 = State(self.__board4, players=[
            self.__p12,
            self.__p13,
            self.__p14])

        # ========================== STATE 7 ==========================
        # Setup state that includes heterogeneous board and players in specified positions

        self.__state7 = State(self.__board5, players=[
            self.__p19,
            self.__p20,
            self.__p21,
            self.__p22])

        # Player 1
        self.__state7.place_avatar(Color.RED, Position(0, 0))
        # Player 2
        self.__state7.place_avatar(Color.BROWN, Position(0, 1))
        # Player 3
        self.__state7.place_avatar(Color.WHITE, Position(0, 2))
        # Player 4
        self.__state7.place_avatar(Color.BLACK, Position(0, 3))
        # Player 1
        self.__state7.place_avatar(Color.RED, Position(0, 4))
        # Player 2
        self.__state7.place_avatar(Color.BROWN, Position(1, 0))
        # Player 3
        self.__state7.place_avatar(Color.WHITE, Position(1, 1))
        # Player 4
        self.__state7.place_avatar(Color.BLACK, Position(1, 2))

        self.__tree7 = GameTree(self.__state7)
_window = Tk()
_window.wm_title('Game state')

# Make up frame within window
frame = Frame(_window, width=505, height=400)
# Set window to use gridview
frame.grid(row=0, column=0)

# Build board
# b = Board.homogeneous(1, rows=10, cols=4)

b = Board.homogeneous(3, 5, 3)

# Build state
state = State(
    b, [PlayerEntity("John", Color.RED),
        PlayerEntity("Johnny", Color.WHITE)])

# Place a bunch of avatars
state.place_avatar(Color.RED, Position(0, 0))
state.place_avatar(Color.WHITE, Position(0, 1))

state.place_avatar(Color.RED, Position(0, 2))
state.place_avatar(Color.WHITE, Position(1, 0))

state.place_avatar(Color.RED, Position(1, 1))
state.place_avatar(Color.WHITE, Position(1, 2))

state.place_avatar(Color.RED, Position(2, 0))
state.place_avatar(Color.WHITE, Position(2, 1))
# Move player 1 avatar
Ejemplo n.º 15
0
def main_loop():
    global display, start_time, fall_delay, map_display, block_above, block_under, block_index, wrl, xs, ys,\
        just_started
    ys = 0
    xs = 0
    font = pygame.font.SysFont("UbuntuMono", 13)  # Fonts should be inited after pygame.init()
    start_time = 0
    clk = pygame.time.Clock()
    if wrl.player.coords[1] < 12:
        xboundmax=(wrl.player.coords[1] + 12)
    else:
        xboundmax=((wrl.player.coords[1]-(wrl.player.coords[1]*2))+12)
    xboundmin=0
    if wrl.player.coords[1] < 8:
        yboundmax=(wrl.player.coords[0])
    else:
        yboundmax=((wrl.player.coords[0]-(wrl.player.coords[0]*2))+8)
    yboundmin=0
    player_health=20
    while True:
        has_displayed=0
        if wrl.player.coords[1] < 12:
            xboundmax=(wrl.player.coords[1] + 12)
        else:
            xboundmax=((wrl.player.coords[1]-(wrl.player.coords[1]*2))+12)
        xboundmin=0
        if wrl.player.coords[0] < 8:
             yboundmax=(wrl.player.coords[0] + 8)
        else:
            yboundmax=((wrl.player.coords[0]-(wrl.player.coords[0]*2))+8)
        yboundmin=0

        clk.tick(20)
        if pygame.time.get_ticks() - start_time >= 50:
            wrl.tick()
        start_time = pygame.time.get_ticks()
        px = wrl.player.coords[1]
        py = wrl.player.coords[0]
        block_under = wrl.level[px][py]
        block_above = wrl.level[px][py - 1] if py < 0 else -1
        prev_pos = wrl.player.coords[:]  # lists are mutable
        for event in pygame.event.get():
            if event.type == QUIT:
                save(SAVE_FILE)
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                keys = pygame.key.get_pressed()
                just_started = False
                # W KEY - UP
                if event.key == K_w and wrl.player.coords[0] in range(1, MAP_X) and (
                            not wrl.player.falling or wrl.player.god_mode):
                    wrl.player.coords[0] -= 1
                    yboundmax += 1
                    if yboundmin != 0:
                        yboundmin += 1
                    if not wrl.level[wrl.player.coords[1]][wrl.player.coords[0]] in block.BLOCK_NONSOLID and not keys[
                        K_LSHIFT] and \
                            not wrl.player.god_mode:
                        wrl.player.coords = prev_pos
                    if keys[K_LSHIFT]:
                        bx, by = wrl.player.coords[1], wrl.player.coords[0]
                        wrl.destroy_block(bx, by)
                        # S KEY - DOWN
                elif event.key == K_s and wrl.player.coords[0] in range(0, MAP_X - 1):
                    wrl.player.coords[0] += 1
                    yboundmax -= 1
                    if yboundmin != 0:
                        yboundmin -= 1
                    if not wrl.level[wrl.player.coords[1]][wrl.player.coords[0]] in block.BLOCK_NONSOLID and not keys[K_LSHIFT]:
                        wrl.player.coords = prev_pos
                    if keys[K_LSHIFT]:
                        bx, by = wrl.player.coords[1], wrl.player.coords[0]
                        wrl.destroy_block(bx, by)
                        # A KEY - LEFT
                elif event.key == K_a and wrl.player.coords[1] in range(1, MAP_Y):
                    wrl.player.falling = False
                    fall_delay = 0
                    wrl.player.coords[1] -= 1
                    xboundmax += 1
                    if xboundmin != 0:
                        xboundmin += 1

                    if not wrl.level[wrl.player.coords[1]][wrl.player.coords[0]] in block.BLOCK_NONSOLID and not keys[
                        K_LSHIFT]:
                        wrl.player.coords = prev_pos
                    if keys[K_LSHIFT]:
                        bx, by = wrl.player.coords[1], wrl.player.coords[0]
                        wrl.destroy_block(bx, by)
                    wrl.player.set_walk(0)
                        # D KEY - RIGHT
                elif event.key == K_d and wrl.player.coords[1] in range(0, MAP_Y - 1):
                    wrl.player.falling = False
                    fall_delay = 0
                    wrl.player.coords[1] += 1
                    xboundmax -= 1
                    if xboundmax <= -24: 
                        xboundmin -= 1
                    if not wrl.level[wrl.player.coords[1]][wrl.player.coords[0]] in block.BLOCK_NONSOLID and not keys[
                        K_LSHIFT]:
                        wrl.player.coords = prev_pos
                    if keys[K_LSHIFT]:
                        bx, by = wrl.player.coords[1], wrl.player.coords[0]
                        wrl.destroy_block(bx, by)
                    wrl.player.set_walk(1)
                        # Z KEY - PLACE BLOCK
                elif event.key == K_z:
                    # print "Debug: placing block at %d %d, previous was %d" % (px, py, wrl.level[px][py])
                    if (wrl.player.inventory[
                            wrl.player.current_block] > 0 or wrl.player.god_mode) and block_under == block.BLOCK_AIR:
                        wrl.level[px][py] = block.BLOCK_INVENTORY[wrl.player.current_block]
                        if not wrl.player.god_mode:
                            wrl.player.inventory[wrl.player.current_block] -= 1
                            # X KEY - DESTROY BLOCK STANDING ON
                elif event.key == K_x:
                    if wrl.level[px][py] in block.BLOCK_INVENTORY:
                        if block_under in block.BLOCK_INVENTORY:
                            block_index = block.BLOCK_INVENTORY.index(block_under)
                            wrl.player.inventory[block_index] += 1
                            wrl.level[px][py] = block.BLOCK_AIR
                            # 1 KEY - SCROLL INVENTORY
                elif event.key == K_1:
                    wrl.player.current_block = (wrl.player.current_block + 1) % len(block.BLOCK_INVENTORY)
                    # ESC KEY - RESET
                elif event.key == K_ESCAPE:
                    xboundmax, xboundmin, yboundmax, yboundmin = 0, 0, -10, 0
                    wrl.new_world(MAP_X, MAP_Y)
                      # F1 KEY - GODMODE
                elif event.key == K_F1:
                    wrl.player.god_mode = not wrl.player.god_mode
                    # E KEY - EXPLODE
                elif event.key == K_e and wrl.player.god_mode:
                    wrl.explode(px, py, 5, False)
                    # N KEY - DESPAWN ENTITY
                elif event.key == K_n: #and wrl.player.god_mode:
                    if len(wrl.entities) > 1:
                        wrl.remove_entity(len(wrl.entities) - 1)  # last
                        # M KEY - SPAWN ENTITY
                elif event.key == K_m: #and wrl.player.god_mode:
                    ent = PlayerEntity(bounding_box=(0, 0, MAP_X, MAP_Y), name="Testificate")
                    wrl.spawn_entity(ent)
                    ent.coords = wrl.player.coords
                    # F5 KEY - SCREENSHOT (possibly bugged)
                elif event.key == K_F5:
                    screenshot()

        map_display.fill(Color(154, 198, 255, 0))
        for x in range(MAP_X):
            for y in range(MAP_Y):
                map_display.blit(block.BLOCK_TEXTURES[wrl.level[x][y]], (x * 32, y * 32))

        debug_text = "Coords: %d, %d   %d fps, block: " % (
                wrl.player.coords[0], wrl.player.coords[1], clk.get_fps()) + "**%d, %d**" % (xboundmax, yboundmax) + " player_health: %d " % (player_health)
        inventory_text = (" x %d" % wrl.player.inventory.get(wrl.player.current_block,
                                                             -1)) + " " + block.BLOCK_NAMES.get(
             block.BLOCK_INVENTORY[wrl.player.current_block], "unknown")
        debug_label = font.render(debug_text, True, COLORS['white'], COLORS['black'])
        inventory_label = font.render(inventory_text, True, COLORS['white'], COLORS['black'])
        display.blit(debug_label, (0, 0))
        display.blit(block.BLOCK_TEXTURES[block.BLOCK_INVENTORY[wrl.player.current_block]], (0, 25 * TILESIZE + 5))
        display.blit(inventory_label, (32, MAP_Y * TILESIZE + 5))
        if block_under in block.BLOCK_DEADLY and not wrl.player.god_mode:
            player_health -= 0.20
            if player_health <= 0:
                game_over()
        if player_health <= 20.0:
            player_health=player_health+0.05
        for ent in wrl.entities:
            ent.render(map_display, TILESIZE, TILESIZE)
        pygame.display.update()
        display.fill(0)
        if xboundmax <= 0 and xboundmax <= -12:
            fx=(xboundmax*32)
            has_displayed=1 
            if xboundmax < -23: fx = -736
        else: fx = 0
        if yboundmax <= 0 and yboundmax <= -8:
            fy=(yboundmax*32)
        else: fy = 0
        display.blit(map_display, (fx, fy))
        display.fill(0x101010, (0, 600 - 48, 800, 600))
        display.blit(block.BLOCK_TEXTURES[block.BLOCK_INVENTORY[wrl.player.current_block]], (8, 600 - 40))
        display.blit(inventory_label, (40, 600 - 32))
    def test_score_fail2(self):
        # Tests failing score due to invalid type
        player = PlayerEntity('iBot', Color.WHITE)

        with self.assertRaises(TypeError):
            player.score = 'whaa'
    def test_init_fail1(self):
        # Tests failing constructor due to invalid name

        with self.assertRaises(TypeError):
            PlayerEntity(23, Color.BLACK)
 def test_init_fail2(self):
     # Tests failing constructor due to invalid color
     with self.assertRaises(TypeError):
         PlayerEntity('T-Bone', 'BLACK')
    def test_add_place_fail1(self):
        # Tests a failing add_place due to invalid position (type-wise)
        player = PlayerEntity('seth', Color.WHITE)

        with self.assertRaises(TypeError):
            player.add_place('ok')
Ejemplo n.º 20
0
def initialize_state(json_obj: dict) -> State:
    """
    Initializes a State object from the given json representation of a state.

    :param json_obj: json object (dictionary) containing player list and board
    :return: the state described by the json obj as a State object
    """
    if not isinstance(json_obj, dict):
        raise TypeError('Expected dict for json_obj!')

    if 'players' not in json_obj.keys():
        raise ValueError('Expected players in object!')

    if 'board' not in json_obj.keys():
        raise ValueError('Expected board in object!')

    # Retrieve player list
    player_list = json_obj['players']
    board_json = json_obj['board']

    # Get board from json
    board = initialize_board(board_json)

    # Initialize empty collection to hold players
    players = []

    # Initialize collection to hold player ids and their
    # avatar placements
    player_placements = {}

    # Cycle over each json object in the json list
    for player in player_list:
        # Make up Player object
        new_player = PlayerEntity("", _str_to_color(player['color']))

        # Update player score to whatever the current score is in the state
        new_player.score = player['score']

        # Add player object to players list
        players.append(new_player)

        # Insert placement
        player_placements.update(
            {_str_to_color(player['color']): player['places']})

    # Make up state with board and players
    state = State(board, players)

    # Determine the maximum number of avatars for a single player
    avatars_per_player_no = max(
        map(lambda x: len(x), player_placements.values()))

    # For each i in the number of avatars per player
    for i in range(avatars_per_player_no):
        # For each player, place i-th avatar if possible
        for p_color, p_placements in player_placements.items():
            # Retrieve current player's i-th avatar
            try:
                placement = player_placements[p_color][i]

                # Convert to Position object
                position_to_place = Position(placement[0], placement[1])

                # Place current player's avatar at position
                state.place_avatar(p_color, position_to_place)
            except IndexError:
                continue

    return state