Beispiel #1
0
def change_level(params):
    game = params[0]
    board = Board(
        size=[250, 30],
        ui_borders="",
        ui_board_void_cell=bg_color + "  " + Graphics.Style.RESET_ALL,
        player_starting_position=[25, 0],
        DISPLAY_SIZE_WARNINGS=False,
    )
    board.ui_border_bottom = Graphics.Sprites.RADIOACTIVE + " "
    board.sprouted_count = 0
    # Let's use a nice curve to increase the trap number.
    board.available_traps = int(10 + 10 * g.current_level * 0.2)
    board.max_traps_number = board.available_traps
    for i in range(0, board.size[0]):
        board.place_item(
            Wall(model=block_color() + "  " + Utils.Style.RESET_ALL,
                 type="platform"),
            board.size[1] - 1,
            i,
        )
    generate_level(game, board)
    game.score += 50 * game.current_level
    new_level = game.current_level + 1
    game.add_board(new_level, board)
    game.change_level(new_level)
    game.move_player(Constants.RIGHT, 3)
    game.player.last_y = game.player.pos[0]
    game.player.last_x = game.player.pos[1]
    g.player.max_y = g.player.pos[0]
    g.player.dy = gravity_speed
    g.obj_stack = []
Beispiel #2
0
    def load_board(self, filename, lvl_number=0):
        """Load a saved board

        Load a Board saved on the disk as a JSON file. This method creates a new Board object, populate it with all the elements (except a Player) and then return it.

        If the filename argument is not an existing file, the open function is going to raise an exception.

        This method, load the board from the JSON file, populate it with all BoardItem included, check for sanity, init the board with BoardItemVoid and then associate the freshly created board to a lvl_number.
        It then create the NPCs and add them to the board.

        :param filename: The file to load
        :type filename: str
        :param lvl_number: The level number to associate the board to. Default is 0.
        :type lvl_number: int
        :returns: a newly created board (see :class:`gamelib.Board.Board`)
        
        Example::

            mynewboard = game.load_board( 'awesome_level.json', 1 )
            game.change_level( 1 )
        """
        with open(filename, 'r') as f:
            data = json.load(f)
        local_board = Board()
        data_keys = data.keys()
        if "name" in data_keys:
            local_board.name = data["name"]
        if 'size' in data_keys:
            local_board.size = data['size']
        if 'player_starting_position' in data_keys:
            local_board.player_starting_position = data[
                'player_starting_position']
        if 'ui_border_top' in data_keys:
            local_board.ui_border_top = data['ui_border_top']
        if 'ui_border_bottom' in data_keys:
            local_board.ui_border_bottom = data['ui_border_bottom']
        if 'ui_border_left' in data_keys:
            local_board.ui_border_left = data['ui_border_left']
        if 'ui_border_right' in data_keys:
            local_board.ui_border_right = data['ui_border_right']
        if 'ui_board_void_cell' in data_keys:
            local_board.ui_board_void_cell = data['ui_board_void_cell']
        # Now we need to recheck for board sanity
        local_board.check_sanity()
        # and re-initialize the board (mainly to attribute a new model to the void cells as it's not dynamic).
        local_board.init_board()
        # Then add board to the game
        self.add_board(lvl_number, local_board)

        # Define an internal function to transform directions string into constants
        def _string_to_constant(s):
            if type(s) is int:
                return s
            elif s == "UP":
                return Constants.UP
            elif s == "DOWN":
                return Constants.DOWN
            elif s == "RIGHT":
                return Constants.RIGHT
            elif s == "LEFT":
                return Constants.LEFT
            elif s == "DRUP":
                return Constants.DRUP
            elif s == "DRDOWN":
                return Constants.DRDOWN
            elif s == "DLDOWN":
                return Constants.DLDOWN
            elif s == "DLUP":
                return Constants.DLUP

        def _ref2obj(ref):
            obj_keys = ref.keys()
            local_object = BoardItemVoid()
            if 'Wall' in ref['object']:
                local_object = Structures.Wall()
            elif 'Treasure' in ref['object']:
                local_object = Structures.Treasure()
                if 'value' in obj_keys:
                    local_object.value = ref['value']
                if 'size' in obj_keys:
                    local_object._size = ref['size']
            elif 'GenericStructure' in ref['object']:
                local_object = Structures.GenericStructure()
                if 'value' in obj_keys:
                    local_object.value = ref['value']
                if 'size' in obj_keys:
                    local_object._size = ref['size']
                if 'pickable' in obj_keys:
                    local_object.set_pickable(ref['pickable'])
                if 'overlappable' in obj_keys:
                    local_object.set_overlappable(ref['overlappable'])
            elif 'Door' in ref['object']:
                local_object = Structures.Door()
                if 'value' in obj_keys:
                    local_object.value = ref['value']
                if 'size' in obj_keys:
                    local_object._size = ref['size']
                if 'pickable' in obj_keys:
                    local_object.set_pickable(ref['pickable'])
                if 'overlappable' in obj_keys:
                    local_object.set_overlappable(ref['overlappable'])
                if 'restorable' in obj_keys:
                    local_object.set_restorable(ref['restorable'])
            elif 'GenericActionableStructure' in ref['object']:
                local_object = Structures.GenericActionableStructure()
                if 'value' in obj_keys:
                    local_object.value = ref['value']
                if 'size' in obj_keys:
                    local_object._size = ref['size']
                if 'pickable' in obj_keys:
                    local_object.set_pickable(ref['pickable'])
                if 'overlappable' in obj_keys:
                    local_object.set_overlappable(ref['overlappable'])
            elif 'NPC' in ref['object']:
                local_object = NPC()
                if 'value' in obj_keys:
                    local_object.value = ref['value']
                if 'size' in obj_keys:
                    local_object._size = ref['size']
                if 'hp' in obj_keys:
                    local_object.hp = ref['hp']
                if 'max_hp' in obj_keys:
                    local_object.max_hp = ref['max_hp']
                if 'step' in obj_keys:
                    local_object.step = ref['step']
                if 'remaining_lives' in obj_keys:
                    local_object.remaining_lives = ref['remaining_lives']
                if 'attack_power' in obj_keys:
                    local_object.attack_power = ref['attack_power']
                if 'actuator' in obj_keys:
                    if 'RandomActuator' in ref['actuator']['type']:
                        local_object.actuator = RandomActuator(moveset=[])
                        if 'moveset' in ref['actuator'].keys():
                            for m in ref['actuator']['moveset']:
                                local_object.actuator.moveset.append(
                                    _string_to_constant(m))
                    elif 'PathActuator' in ref['actuator']['type']:
                        local_object.actuator = PathActuator(path=[])
                        if 'path' in ref['actuator'].keys():
                            for m in ref['actuator']['path']:
                                local_object.actuator.path.append(
                                    _string_to_constant(m))
            # Now what remains is what is common to all BoardItem
            if not isinstance(local_object, BoardItemVoid):
                if 'name' in obj_keys:
                    local_object.name = ref['name']
                if 'model' in obj_keys:
                    local_object.model = ref['model']
                if 'type' in obj_keys:
                    local_object.type = ref['type']
            return local_object

        # Now load the library if any
        if 'library' in data_keys:
            self.object_library = []
            for e in data['library']:
                self.object_library.append(_ref2obj(e))
        # Now let's place the good stuff on the board
        if 'map_data' in data_keys:
            for pos_x in data['map_data'].keys():
                x = int(pos_x)
                for pos_y in data['map_data'][pos_x].keys():
                    y = int(pos_y)
                    ref = data['map_data'][pos_x][pos_y]
                    obj_keys = ref.keys()
                    if 'object' in obj_keys:
                        o = _ref2obj(ref)
                        if not isinstance(o, NPC) and not isinstance(
                                o, BoardItemVoid):
                            local_board.place_item(o, x, y)
                        elif isinstance(o, NPC):
                            self.add_npc(lvl_number, o, x, y)

                    else:
                        Utils.warn(
                            f'while loading the board in {filename}, at coordinates [{pos_x},{pos_y}] there is an entry without "object" attribute. NOT LOADED.'
                        )
        return local_board
dg = RLDungeonGenerator(dg_width, dg_height)
dg.generate_map()
print("done")
print("\rBuilding the map...", end="")
random_board = Board(
    size=[dg_width, dg_height],
    name="Random dungeon",
    ui_borders=Utils.WHITE_SQUARE,
    ui_board_void_cell=Utils.BLACK_SQUARE,
    DISPLAY_SIZE_WARNINGS=False,
)
potential_starting_position = []
for r in range(dg.height):
    for c in range(dg.width):
        if dg.dungeon[r][c].get_ch() == "#":
            random_board.place_item(Wall(model=Sprites.WALL), r, c)
        elif dg.dungeon[r][c].get_ch() == "+":
            random_board.place_item(Door(model=Sprites.DOOR), r, c)
        elif dg.dungeon[r][c].get_ch() == ".":
            potential_starting_position.append([r, c])
random_board.player_starting_position = choice(potential_starting_position)
print("done")
print(f"starting position chosen: {random_board.player_starting_position}")

# dg.print_map()
# random_board.display()
input("New random dungeon generated. Next?")

g = Game()
g.enable_partial_display = True
# g.load_board('/home/arnaud/Code/Games/hgl-editor/Large_Dungeon.json', 1)
Beispiel #4
0
    size=[40, 20],
    ui_border_left=Utils.WHITE_SQUARE,
    ui_border_right=Utils.WHITE_SQUARE,
    ui_border_top=Utils.WHITE_SQUARE,
    ui_border_bottom=Utils.WHITE_SQUARE,
    ui_board_void_cell=Utils.BLACK_SQUARE,
    player_starting_position=[10, 20],
)

# Now let's make a couple of walls using colored squares as models
green_wall = Wall(model=Utils.GREEN_SQUARE)
blue_wall = Wall(model=Utils.BLUE_SQUARE)
cyan_wall = Wall(model=Utils.CYAN_SQUARE)
magenta_wall = Wall(model=Utils.MAGENTA_SQUARE)

# Now let's place these walls on the board
for k in range(1, 6, 1):
    myboard.place_item(green_wall, 1, k)
    myboard.place_item(magenta_wall, k, 6)

for k in range(2, 6, 1):
    myboard.place_item(blue_wall, k, 1)
    myboard.place_item(cyan_wall, 5, k)

# And just for the fun of it, let's place a yellow and cyan wall
# in the middle of that "structure"
myboard.place_item(Wall(model=Utils.YELLOW_CYAN_SQUARE), 3, 3)

# Finally let's display the board
myboard.display()
Beispiel #5
0
myboard = Board(
                name='A demo board',
                size=[40,20],
                ui_border_left=Utils.WHITE_SQUARE, # Borders are going to be white squares
                ui_border_right=Utils.WHITE_SQUARE,
                ui_border_top=Utils.WHITE_SQUARE,
                ui_border_bottom=Utils.WHITE_SQUARE,
                ui_board_void_cell=Utils.BLACK_SQUARE, # Cells with nothing inside are going to be black squares
                player_starting_position=[10,20]
                )

# Then create a player 
playerone = Player( model=Utils.yellow_bright('××') )

# Place it on the board
myboard.place_item(playerone, 10,10)

# Now let's display our board
myboard.display()

# And make a short loop that moves the player and display the board 
# WARNING: in real life we would use the Game object to manage the game and the screen

for k in range(1,10,1):
    # Clear screen
    Utils.clear_screen()
    # Print a debug message
    Utils.debug(f'Round {k} player position is ({playerone.pos[0]},{playerone.pos[1]}) -- BEFORE moving')
    # Ask myboard to move playerone to the right by one cell
    myboard.move(playerone, Constants.RIGHT, 1 )
    # print another debug message
    g.clear_screen()
    nb_blocks = int((g.player.mp / g.player.max_mp) * 20)
    print("Mana [" + Utils.BLUE_RECT * nb_blocks + Utils.BLACK_RECT *
          (20 - nb_blocks) + "]")
    g.display_board()
    # manage_fireballs()


b = Board(
    ui_borders=Utils.WHITE_SQUARE,
    ui_board_void_cell=Utils.BLACK_SQUARE,
    size=[20, 20],
    player_starting_position=[5, 5],
)
wall = Wall(model=Sprites.WALL)
b.place_item(wall, 1, 6)
g = Game()
g.add_board(1, b)
g.player = Player(model=Sprites.MAGE, name="The Maje")
g.player.mp = 20
g.player.max_mp = 20
g.change_level(1)
key = None

black_circle = "-\U000025CF"
circle_jot = "-\U0000233E"

throw_fireball = False
projectile = Projectile()

while True:
Beispiel #7
0
life_heart = GenericActionableStructure(model=sprite_heart, name='life_100')
life_heart.set_overlappable(True)
life_heart.action = add_hp
life_heart.action_parameters = [game, 100]

life_heart_minor = GenericActionableStructure(model=sprite_heart_minor,
                                              name='life_25')
life_heart_minor.set_overlappable(True)
life_heart_minor.action = add_hp
life_heart_minor.action_parameters = [game, 25]

game.player = p

# Adding walls to level 1
lvl1.place_item(Wall(model=sprite_wall), 2, 3)
lvl1.place_item(Wall(model=sprite_wall), 2, 2)
lvl1.place_item(Wall(model=sprite_wall), 2, 1)
lvl1.place_item(Wall(model=sprite_wall), 2, 0)
lvl1.place_item(Wall(model=sprite_wall), 3, 3)
lvl1.place_item(Wall(model=sprite_wall), 4, 3)
lvl1.place_item(Wall(model=sprite_wall), 5, 3)
lvl1.place_item(Wall(model=sprite_wall), 6, 3)
lvl1.place_item(Wall(model=sprite_wall), 6, 2)
lvl1.place_item(Wall(model=sprite_wall), 6, 1)
lvl1.place_item(Wall(model=sprite_wall), 7, 1)
lvl1.place_item(Wall(model=sprite_wall), 8, 1)
lvl1.place_item(Wall(model=sprite_wall), 8, 3)
lvl1.place_item(Wall(model=sprite_wall), 9, 3)
lvl1.place_item(Wall(model=sprite_wall), 10, 3)
lvl1.place_item(Wall(model=sprite_wall), 10, 2)
Beispiel #8
0
    retry = 0
    while True :
        if row == None:
            row = random.randint(0,bonus_board.size[1]-1)
        if column == None:
            column = random.randint(0,bonus_board.size[0]-1)
        # print(f"Game.add_npc() finding a position for NPC {npc.name} trying ({x},{y})")
        if isinstance(bonus_board.item(row,column), BoardItemVoid):
            break
        elif retry > 20:
            break
        else:
            row = None
            column = None
            retry += 1
    bonus_board.place_item(Treasure(model=Sprites.MONEY_BAG, value=100, name=f'gold_bag_{k}'), row, column)

# And finally let's put 100 diamonds. Each diamond increase the score by 1000.
for k in range(0,100):
    row = None
    column = None
    retry = 0
    while True :
        if row == None:
            row = random.randint(0,bonus_board.size[1]-1)
        if column == None:
            column = random.randint(0,bonus_board.size[0]-1)
        # print(f"Game.add_npc() finding a position for NPC {npc.name} trying ({x},{y})")
        if isinstance(bonus_board.item(row,column), BoardItemVoid):
            break
        elif retry > 20:
Beispiel #9
0
from gamelib.Board import Board
from gamelib.Structures import Wall

walls = []
for i in range(0, 11):
    walls.append(Wall())

b = Board(size=[10, 10])
for i in range(0, 10):
    b.place_item(walls[i], i, i)

b.place_item(Wall(model="*", type="round"), 0, 9)
b.place_item(Wall(model="*", type="round"), 1, 9)
print(b.get_immovables())
for i in b.get_immovables(type="round"):
    print(f"{i}: {i.name} pos: {i.pos} ({id(i)})")

print("DISCARDING")
b._immovables.discard(b.item(1, 9))

for i in b.get_immovables(type="round"):
    print(f"{i}: {i.name} pos: {i.pos} ({id(i)})")
Beispiel #10
0
class TestBoard(unittest.TestCase):
    def test_create_board(self):
        self.board = Board(name="test_board",
                           size=[10, 10],
                           player_starting_position=[5, 5])
        self.assertEqual(self.board.name, "test_board")

    def test_sanity_size_is_list(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name="test_board",
                               size="bad",
                               player_starting_position=[5, 5])

        self.assertTrue("must be a list." in str(context.exception))

    def test_sanity_size_has_two_elements(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name="test_board",
                               size=["one"],
                               player_starting_position=[5, 5])

        self.assertTrue(
            "must be a list of 2 elements" in str(context.exception))

    def test_sanity_size_element_one_int(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name="test_board",
                               size=["one", "two"],
                               player_starting_position=[5, 5])

        self.assertTrue("first element of the" in str(context.exception))

    def test_sanity_size_element_two_int(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name="test_board",
                               size=[10, "two"],
                               player_starting_position=[5, 5])

        self.assertTrue("second element of the" in str(context.exception))

    def test_sanity_name_string(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name=100,
                               size=[10, 10],
                               player_starting_position=[5, 5])

        self.assertTrue("must be a string" in str(context.exception))

    def test_sanity_ui_border_bottom_string(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name=100, size=[10, 10], ui_border_bottom=[])

        self.assertTrue("must be a string" in str(context.exception))

    def test_sanity_ui_border_top_string(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name=100, size=[10, 10], ui_border_top=[])

        self.assertTrue("must be a string" in str(context.exception))

    def test_sanity_ui_border_left_string(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name=100, size=[10, 10], ui_border_left=[])

        self.assertTrue("must be a string" in str(context.exception))

    def test_sanity_ui_border_right_string(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name=100, size=[10, 10], ui_border_right=[])

        self.assertTrue("must be a string" in str(context.exception))

    def test_sanity_ui_board_void_cell_string(self):
        with self.assertRaises(Exception) as context:
            self.board = Board(name=100, size=[10, 10], ui_board_void_cell=[])

        self.assertTrue("must be a string" in str(context.exception))

    def test_item(self):
        self.board = Board(name="test_board",
                           size=[10, 10],
                           player_starting_position=[5, 5])
        self.placed_item = BoardItem()

        self.board.place_item(self.placed_item, 1, 1)
        self.returned_item = self.board.item(1, 1)
        self.assertEqual(self.placed_item, self.returned_item)

        with self.assertRaises(HacOutOfBoardBoundException) as excinfo:
            self.board.item(15, 15)
        self.assertTrue(
            "out of the board boundaries" in str(excinfo.exception))

    def test_clear_cell(self):
        self.board = Board(name="test_board",
                           size=[10, 10],
                           player_starting_position=[5, 5])
        self.placed_item = BoardItem()
        self.board.place_item(item=self.placed_item, row=1, column=1)
        self.assertIsInstance(self.board.item(1, 1), BoardItem)

        self.board.clear_cell(1, 1)
        self.assertIsInstance(self.board.item(1, 1), BoardItemVoid)
        redraw_screen()
        g.actuate_npcs(1)
        g.actuate_projectiles(1)
        g.animate_items(1)
        time.sleep(0.1)


game_running = True
b = Board(
    ui_borders=Graphics.WHITE_SQUARE,
    ui_board_void_cell=Graphics.BLACK_SQUARE,
    size=[20, 20],
    player_starting_position=[5, 5],
)
wall = Wall(model=Graphics.Sprites.BRICK)
b.place_item(wall, 1, 6)
b.place_item(wall, 5, 10)
g = Game()
g.add_board(1, b)
g.player = Player(model=Graphics.Sprites.MAGE)
g.player.level = 1
g.player.mp = 20
g.player.max_mp = 20

g.add_npc(
    1,
    NPC(
        name="Bob Soontobedead",
        model=Graphics.Sprites.SKULL,
        hp=10,
        actuator=RandomActuator(moveset=[Constants.NO_DIR]),