Esempio n. 1
0
 def __init__(self):
     """
     Sets up a game gui with the player and starts it
     :return:
     """
     pygame.init()
     self.view = View()
     self.map = Map()
     self.map.player = Player()
     self.map.player_loc = (1 * TILE_SIZE, 1 * TILE_SIZE)
     self.player = self.map.player
     self.player.set_location(self.map.player_loc)
     #self.time = pygame.time.Clock()
     self.map.set_player_location(self.map.player_loc)
     self.treasure = Treasure()
     self.inventory_button = Button("Inventory", 480, 0, 20, 20)
     self.save_button = Button("Save", 590, 0, 20, 20)
     self.load_button = Button("Load", 590, 50, 20, 20)
     self.view.draw_layers(self.map, self.treasure,
                           self.map.player.inventory, self.inventory_button,
                           self.save_button, self.load_button)
     self.monster = Monster()
     self.map.monster_loc = self.monster.loc
     while self.map.set_monster_location(self.monster.loc) is False:
         self.monster.set_location()
     self.map.treasure_loc = self.treasure.x_y
     while self.map.add_item(self.treasure.x_y) is False:
         self.treasure = Treasure()
Esempio n. 2
0
def get_data(pattern='*', excludes=''):
    if args.input and os.path.exists(args.input):
        files = get_files(args.input, pattern, excludes)
        for file in files:
            yield InputTreasure(Treasure.from_file(file), file)
    else:
        stdin_data = to_bytes(sys.stdin.read().rstrip('\n'))
        yield InputTreasure(Treasure(stdin_data))
Esempio n. 3
0
 def setMaterial(self, material, tier_level=-1):
     if (material == TREASURE):
         self.treasure = Treasure(self.x, self.y, tier_level)
     else:
         self.material = material
         if (self.material != None):
             self.set_texture(CELL_MATERIAL_TEXTURES_PATH[self.material])
             self.durability = CELL_MATERIAL_DURABILITY[self.material]
         else:
             self.texture = None
    def move_hero(self, direction):
        new_x = 0
        new_y = 0

        if direction == "r":
            new_x = self.hero_x
            new_y = self.hero_y + 1

        if direction == "l":
            new_x = self.hero_x
            new_y = self.hero_y - 1

        if direction == "u":
            new_x = self.hero_x - 1
            new_y = self.hero_y

        if direction == "d":
            new_x = self.hero_x + 1
            new_y = self.hero_y

        if not self.is_inside_the_borders_or_obstacle(new_x, new_y):
            return False

        self.hero.take_mana(self.hero.mana_regeneration_rate)

        self.map[self.hero_x][self.hero_y] = Dungeon.PATH_PLACE
        new_position = self.map[new_x][new_y]
        self.hero_x = new_x
        self.hero_y = new_y

        if new_position == Dungeon.SPAWN_PLACE:
            self.map[self.hero_x][self.hero_y] = Dungeon.HERO_PLACE

        if new_position == Dungeon.PATH_PLACE:
            self.map[self.hero_x][self.hero_y] = Dungeon.HERO_PLACE

        if new_position == Dungeon.GATEWAY_PLACE:
            self.map[self.hero_x][self.hero_y] = Dungeon.HERO_PLACE
            return True

        if new_position == Dungeon.TREASURE_PLACE:
            Treasure.get_random_treasure(self.hero)
            self.map[self.hero_x][self.hero_y] = Dungeon.HERO_PLACE

        if new_position == Dungeon.ENEMY_PLACE:
            self.hero_attack(self.hero)
            return False
Esempio n. 5
0
 def check_collisions(self):
     for item in self.board._content:
         if item != self.character and \
                 item.position.x == self.character.position.x and \
                 item.position.y == self.character.position.y:
             self.character.score += item.value
             self.board.place_random(Treasure())
             self.board.remove(item)
             break
Esempio n. 6
0
 def setMaterial(self, material, tier_level = -1):
     if (material == TREASURE):
         self.treasure = Treasure(self.x, self.y, tier_level)
     else:
         self.material = material
         if (self.material != None):
             self.set_texture(CELL_MATERIAL_TEXTURES_PATH[self.material])
             self.durability = CELL_MATERIAL_DURABILITY[self.material]
         else:
             self.texture = None
Esempio n. 7
0
 def __init__(self, width=9, height=9):
     self.board = Board(width, height)
     self.character = Character()
     self.board.place_center(self.character)
     self.board.place_random(Treasure())
     self.commands = {
         "left": self.turn_left,
         "right": self.turn_right,
         "forward": self.forward,
         "backward": self.backward,
     }
Esempio n. 8
0
 def create(self, key, row, col):
     if key == "G":
         Goblin(row, col, self)
     elif key == "S":
         Snake(row, col, self)
     elif key == "#":
         Barrier(row, col, self)
     elif key == "P":
         Player(row, col, self)
     elif key == "T":
         Treasure(row, col, self)
Esempio n. 9
0
 def hideout(self):
     dungeon = self.dungeon
     self.explore_depth = 6
     self.explored_nodes = []
     # populates back of dungeon with a tough boss, and entrance with some guards. Odd stuff in between.
     # see what else they've explored:
     self.explore(dungeon, 0)
     for node, node_data in dungeon.nodes(data=True):
         if node in self.explored_nodes:
             node_data['colour'] = self.colour
     # put some encounters in there
     subgraph = dungeon.subgraph(self.explored_nodes)
     nodes = subgraph.nodes(data=True)
     paths = {a: len(nx.shortest_path(subgraph, 0, a)) for a, node in nodes}
     max_path = max(paths.values())
     final_room = random.choice([key for key, value in paths.items() if value == max_path])
     main_route = nx.shortest_path(subgraph, 0, final_room)
     for a, node in nodes:
         if a == final_room:
             encounter = DirectedEncounter(self.level, style='boss')
             encounter.pick_monsters(self.monsters)
             node['encounter'] = encounter.display()
             t = Treasure(self.level)
             node['treasure'] = t.roll_on_treasure_table()
         elif a == 0:
             encounter = DirectedEncounter(self.level, style='guards')
             encounter.pick_monsters(self.monsters)
             node['encounter'] = encounter.display()
         elif a not in main_route:
             roll = random.randint(1, 6)
             if roll > 3:
                 encounter = DirectedEncounter(self.level, style='elite')
                 encounter.pick_monsters(self.monsters)
                 node['encounter'] = encounter.display()
         else:
             roll = random.randint(1, 6)
             if roll > 3:
                 encounter = DirectedEncounter(self.level, style='basic')
                 encounter.pick_monsters(self.monsters)
                 node['encounter'] = encounter.display()
Esempio n. 10
0
class Cell(Sprite):
    def __init__(self, cell_type_id, row, col):
        self.cell_type_id = cell_type_id
        self.material = None
        self.x = col * CELL_SIZE
        self.y = row * CELL_SIZE
        self.treasure = None
        self.bounding_box = (0, 0, CELL_SIZE, CELL_SIZE)

    def setMaterial(self, material, tier_level=-1):
        if (material == TREASURE):
            self.treasure = Treasure(self.x, self.y, tier_level)
        else:
            self.material = material
            if (self.material != None):
                self.set_texture(CELL_MATERIAL_TEXTURES_PATH[self.material])
                self.durability = CELL_MATERIAL_DURABILITY[self.material]
            else:
                self.texture = None

    def update(self, player):
        if (self.treasure):
            self.treasure.update(player)

    def draw(self, surface, camera):
        camerax, cameray = camera.getPosition()
        pygame.draw.rect(
            surface, CELL_TYPE_COLORS[self.cell_type_id],
            (self.x - camerax, self.y - cameray, CELL_SIZE, CELL_SIZE))
        if (self.material != None):
            Sprite.draw(self, surface, camera)
        if (self.treasure != None):
            self.treasure.draw(surface, camera)

    def isSolid(self):
        return self.cell_type_id == GROUND and self.material != None

    def hit(self):
        self.durability -= 1
        return self.durability <= 0
Esempio n. 11
0
class Cell(Sprite):
    def __init__(self, cell_type_id, row, col):
        self.cell_type_id = cell_type_id
        self.material = None
        self.x = col * CELL_SIZE
        self.y = row * CELL_SIZE
        self.treasure = None
        self.bounding_box = (0, 0, CELL_SIZE, CELL_SIZE)

    def setMaterial(self, material, tier_level = -1):
        if (material == TREASURE):
            self.treasure = Treasure(self.x, self.y, tier_level)
        else:
            self.material = material
            if (self.material != None):
                self.set_texture(CELL_MATERIAL_TEXTURES_PATH[self.material])
                self.durability = CELL_MATERIAL_DURABILITY[self.material]
            else:
                self.texture = None

    def update(self, player):
        if (self.treasure):
            self.treasure.update(player)

    def draw(self, surface, camera):
        camerax, cameray = camera.getPosition()
        pygame.draw.rect(surface, CELL_TYPE_COLORS[self.cell_type_id], (self.x - camerax, self.y - cameray, CELL_SIZE, CELL_SIZE)) 
        if (self.material != None):
            Sprite.draw(self, surface, camera)
        if (self.treasure != None):
            self.treasure.draw(surface, camera)

    def isSolid(self):
        return self.cell_type_id == GROUND and self.material != None

    def hit(self):
        self.durability -= 1
        return self.durability <= 0
Esempio n. 12
0
def init_game(MAP, tr_x, tr_y):
    # Treasure
    treasure = Treasure()
    MAP.getCordinate(tr_x, tr_y).setObject(treasure)

    # Flowers
    # Lotus Flowers
    for i in range(4):
        lf = LotusFlower()
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(lf)

    # Danger Flowers
    for i in range(4):
        df = DangerFlower(randint(1, 99))
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(df)

    # Killer Flowers
    for i in range(4):
        kf = KillerFlower()
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(kf)

    # Fish
    # Theif Fish
    for i in range(4):
        tfh = TheifFish()
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(tfh)

    # Rubber Eating Fish
    for i in range(4):
        rfh = RubberEatingFish()
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(rfh)

    # Danger Fish
    for i in range(4):
        dfh = DangerFish(randint(0, 99))
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(dfh)

    # Killer Fish
    for i in range(4):
        kfh = KillerFish()
        cordinate = init_object_cordinate(MAP)
        MAP.getCordinate(cordinate[0], cordinate[1]).setObject(kfh)
Esempio n. 13
0
def getMaze(level, room):
    """ A function to read the maze from level file and create different objects. """
    for x in range(len(level)):
        for y in range(len(level[x])):
            char = level[x][y]
            s_x = 35 + y * 25
            s_y = 35 + x * 25
            if char == "X":
                room.wall_list.add(Wall(s_x, s_y))
            elif char == "E":
                room.enemy_sprites.add(Enemy(s_x, s_y))
            elif char == "P":
                player = Player(s_x, s_y)
            elif char == "T":
                room.treasure_list.add(Treasure(s_x, s_y))
            elif char == "G":
                goal = Wall(s_x, s_y)
    return (player, goal)
Esempio n. 14
0
    def damageLogic(self, target, attacker, damage):
        # handles damage dealing
        target.take_damage(damage, attacker.rect.x, attacker.rect.y)
        if target.health <= 0:
            # if dead, removes from visual list
            self.current_room.enemy_list.remove(target)

            # rewards EXP to attacker
            # this function will need to be adjusted
            # to allow player-kill EXP rewards
            attacker.earn_EXP(target.EXP)

            loot_roll = random.randint(0, 30)
            # roll for loot
            if loot_roll > 15:
                loot = Treasure(target.rect.centerx, target.rect.centery)
                self.current_room.treasure_list.add(loot)
            # create EXP reward visual
            self.expReward_list.add(
                EXPReward(target.rect.centerx, target.rect.centery - TILE_SIZE,
                          target.EXP))
Esempio n. 15
0
    def __init__(self):
        self.walls = self.get_blank_map()
        self.treasure = self.get_blank_map()
        self.enemy = self.get_blank_map()
        self.floor = self.get_blank_map()
        self.wall_list = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.treasure_list = pygame.sprite.Group()
        self.chamber_list = []

        self.get_chambers()
        self.connect_chambers()

        for t in xrange(TREASURES):
            while 1:
                col = randint(0, COLUMNS - 1)
                row = randint(0, ROWS - 1)
                treasure = Treasure((row * TILE_SIZE), (col * TILE_SIZE))
                if not self.walls[row][col] and self.floor[row][col]:
                    self.treasure[row][col] = treasure
                    self.treasure_list.add(treasure)
                    break

        for m in xrange(ENEMIES):
            while 1:
                col = randint(0, COLUMNS - 1)
                row = randint(0, ROWS - 1)
                enemy = Enemy()
                enemy.rect.left = row * TILE_SIZE
                enemy.rect.top = col * TILE_SIZE
                if not self.treasure[row][col] and self.floor[row][col]:
                    self.enemy[row][col] = enemy
                    self.enemy_list.add(enemy)
                    break

        self.fill_map()
Esempio n. 16
0
 def move_player(self, direction):
     """
     Moves the player in a certain direction given a keypress
     :param direction: direction to move in
     :return:
     """
     oldx, oldy = self.map.player_loc
     x, y = oldx + direction[0], oldy + direction[1]
     x_limit = (ROW - 1) * TILE_SIZE
     y_limit = (COLUMN - 1) * TILE_SIZE
     #don't do anything if the location is too much
     if x > x_limit or x < 0 or y > y_limit or y < 0:
         return
     ret_move_player = self.map.set_player_location((x, y))
     self.player.set_location((x, y))
     if ret_move_player is True:
         self.map.player.add_to_inventory(self.treasure.item)
         self.treasure = Treasure()
         self.map.treasure_loc = self.treasure.x_y
         print(self.map.player.inventory.get_items())
         self.map.add_item(self.treasure.x_y)
     elif ret_move_player is 2:
         print("COMBAT")
         hp = Combat(self.map.player, self.monster, self.view).init_combat()
         print(hp)
         if hp[0] <= 0:
             self.end_game()
             return False
             #self.quit()
         else:
             self.map.player.hp = hp[0]
         self.monster = Monster()
         while self.map.set_monster_location(self.monster.loc) is False:
             self.monster.set_location()
         self.map.monster_loc = self.monster.loc
         self.map.add_monster(self.monster.loc)
Esempio n. 17
0
    def __init__(self):
        self.board = Board(number_of_rows=5, number_of_columns=5, game=self)

        self.board.player = BoardPlayer(x=0, y=0, player_type=Dog(), board=self.board)
        self.board.treasure = Treasure(treasure_type=Bone())
        self.score = 0
Esempio n. 18
0
# library will house 3 books
# Book - inherits from Item
# "read" i.e. collect all three books to access pieces of a password
# complete password will unlock "Treasure"

items = {
    'key':
    Item("key", "A heavy, bronze key."),
    'book1':
    Book("book1", "A dusty, old book. Try reading it.", "a8qr"),
    'book2':
    Book("book2", "A thick, leather book. Try reading it.", "f02g"),
    'book3':
    Book("book3", "A thin, fragile book. Try reading it.", "2h5n"),
    'treasure':
    Treasure("treasure",
             "One-thousand gold bars and a lifetime supply of burritos!")
}

# add the items to the rooms
room['foyer'].items = [items['key']]
room['library'].items = [items['book1'], items['book2'], items['book3']]
room['treasure'].items = [items['treasure']]

player_name = input('\nWhat is your name? ')

player = Player(player_name, room['outside'])

print_color('cyan', f'\nWelcome {player.name}!\n\n')

# time.sleep(1)
Esempio n. 19
0
from treasure import Treasure

if __name__ == '__main__':
    treasure = Treasure(1)
    print(treasure.roll_on_treasure_table())
Esempio n. 20
0
 def test_treasure_type_weapon(self):
     from weapon import Weapon
     treasure = Treasure("weapon", 20)
     self.assertEqual(type(treasure.item), Weapon)
Esempio n. 21
0
 def test_treasure_potion_type_not_expected(self):
     with self.assertRaises(ValueError):
         Treasure("fjghd", 4)
Esempio n. 22
0
 def __fill_treasures_list(self):
     file_lines = self.__read_file(f"treasures_level{self.level}.txt")
     for line in file_lines:
         treasure_info = line.split()
         treasure_info[1] = int(treasure_info[1])
         self.__treasures.append(Treasure(*treasure_info))
Esempio n. 23
0
 def test_treasure_type_spell(self):
     from spell import Spell
     treasure = Treasure("spell", 20)
     self.assertEqual(type(treasure.item), Spell)
Esempio n. 24
0
from treasure import Treasure

# Declare Items
item_dict = {
    'coins':
    Item("Coins", "Pile of coins - old gold"),
    'sword':
    Weapon("Sword", "Very sharp made out of steel", 20),
    'skull':
    Item("Skull", "As dry as a bone"),
    'apple':
    Item("Apple", "Eat this fresh apple to increase life points"),
    'hammer':
    Item("Hammer", "You can crush stones with it"),
    "diamond":
    Treasure("Diamond", "Very shiny"),
    "emerald":
    Treasure("Emerald",
             "The emerald has been known as a symbol of truth and love")
}

# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons", []),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""", [item_dict['apple']]),
    'overlook':
Esempio n. 25
0
    def add_rooms(self,
                  room: Room,
                  current_index,
                  treasure_probability=TREASURE_PROBABILITY,
                  enemy_probability=ENEMY_PROBABILITY):
        x_index, y_index = current_index
        new_x_index, new_y_index = x_index, y_index

        connections_to_add: List[Direction] = room.unset_directions

        new_rooms: List[Tuple[Room, Tuple[int, int]]] = []
        for direction in connections_to_add:
            door_config = DoorConfig.cap(direction)

            if direction == Direction.NORTH:
                new_y_index -= 1
            elif direction == Direction.SOUTH:
                new_y_index += 1
            elif direction == Direction.EAST:
                new_x_index += 1
            elif direction == Direction.WEST:
                new_x_index -= 1

            if new_x_index in LEVEL_EDGE_INDICES or new_y_index in LEVEL_EDGE_INDICES:
                cap = True
            else:
                cap = False

            new_room = self.level_layout[new_y_index][new_x_index]
            if new_room is None:
                if cap:
                    new_room = Room(door_config)
                else:
                    new_room = Room.random_room(direction)

                if random.random() < treasure_probability:
                    treasure = Treasure.random_treasure()
                    self.treasures.append(treasure)
                    new_room.add_treasure(treasure)
                    treasure_probability = TREASURE_PROBABILITY
                else:
                    treasure_probability += TREASURE_PROBABILITY

                if random.random() < enemy_probability:
                    number_of_enemies = random.randint(
                        ENEMY_MIN_NUMBER_PER_ROOM, ENEMY_MAX_NUMBER_PER_ROOM)
                    for _ in range(number_of_enemies):
                        enemy = Enemy.random_enemy()
                        self.enemies.append(enemy)
                        new_room.add_enemy(enemy)
                        enemy_probability = ENEMY_PROBABILITY
                else:
                    enemy_probability += ENEMY_PROBABILITY

                self.rooms.append(new_room)

            self._add_connection(room, new_room, direction)
            self.level_layout[new_y_index][new_x_index] = new_room

            if not cap:
                new_rooms.append((new_room, (new_x_index, new_y_index)))

            new_x_index, new_y_index = x_index, y_index

        for new_room, index in new_rooms:
            self.add_rooms(new_room, index, treasure_probability,
                           enemy_probability)
        return
Esempio n. 26
0
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
        [Weapon("Sword", "Vanquish your enemies", 150)]),
    'treasure':
    Room(
        "Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south.""", []),
    'secret room':
    Room(
        "Secret Room", """You've found the secret room North of the Treasure
Chamber. Reward yourself with treasures once thought to be lost. South of you is the main room of 
the treasure chamber.""", [
            Treasure("Gold Coins", "Fill your pockets with riches", "250"),
            Treasure("Crown", "The crown of a once great king", "2000"),
            Treasure("Holy Grail", "Indiana Jones would be pleased",
                     "Priceless")
        ]),
}

# Link rooms together

room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
Esempio n. 27
0
from room import Room
from player import Player
from monster import Monster
from item import Item
from weapon import Weapon
from treasure import Treasure
from lightsource import LightSource
import printing
import commandparser as parser

# Declare the items
items = {
    'jewel':
    Treasure(100, "jewel", ["glittering"],
             "It is a deep red hue and seems to pulse to an unheard rhythm."),
    'locket':
    Item("locket", ["battered", "silver"],
         "Opening it reveals a faded photograph of two lovers."),
    'dagger':
    Weapon(10, "dagger", ["thin"],
           "It looks like it could be used to stab somebody."),
    'lantern':
    LightSource("lantern", ["spooky"],
                "It flickers gently as if spurred by an unfelt breeze.")
}

monsters = {
    'demon':
    Monster(
        "demon",
        "Its festering skin appears to be falling off with every movement", 10,
Esempio n. 28
0
# The wizard's castle
# By Andrew and Jonathan
from treasure import Treasure
# Gameplay Constants
# MAP constants
MAP_MONSTER_DENSITY = 0.3
MAP_TREASURE_DENSITY = 0.05
# TREASURE_LIST = (, , )
TREASURE_LIST = (Treasure('Norn Stone'), Treasure('Opal Eye'),
                 Treasure('Black Sapphire'))

for treasure in TREASURE_LIST:
    print(treasure.name)

# map_size = 0
# while (int(map_size) > 11 or int(map_size) < 5):
#     map_size = input ('Choose a dungeon size (5 to 10): ')
# print ('You have chosen map size: ' + map_size)
# gender = None
# gender_list = ['M', 'F', 'm', 'f']
# while (gender not
#     in gender_list):
#     gender = input ('Do you want to be male "M" or female "F"? ')
#     if (gender not in gender_list):
#         print ('Please choose "M" or "F"!')

# race = None
# race_list = ['Human', 'Elf', 'Werewolf']
# def convert_lower (stringy): return stringy.lower()[0]
# race_list_lower = list(map(convert_lower, race_list))
# print (race_list_lower)
Esempio n. 29
0
import os
from dungeon import Dungeon
from hero import Hero
from enemy import Enemy
from treasure import Treasure
from spell import Spell
from weapon import Weapon

print('Hello player,\nyour adventure is about to begin..')
name = input('Enter your character\'s name:> ')
title = input('Enter {}\'s title:> '.format(name))
hero = Hero(name, title)
treasure = Treasure()
dungeon = Dungeon('level01.txt')
dungeon.spawn()
os.system('clear')
dungeon.print_map()
commands = {
    's': dungeon.move_down,
    'w': dungeon.move_up,
    'a': dungeon.move_left,
    'd': dungeon.move_right
}


def fight_mode():
    enemy = Enemy()
    os.system('clear')
    print(
        '<<< FIGHT MODE>>>\nYou {} have just met a monster.. FIGHT your enemy to DEATH!'
        .format(hero.known_as()))
Esempio n. 30
0
 def test_treasure_type_potion(self):
     treasure = Treasure("health", 20)
     self.assertEqual(str(treasure), "health potion, 20")
Esempio n. 31
0
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm.""",
        [Item("Pellet"), Item("Plates"),
         Item("Book")]),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
        [Item("Shovel"), Item("Barrow"),
         Item("Anvil")]),
    'treasure':
    Room(
        "Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south.""",
        [Treasure("Gold"),
         Treasure("Silver"),
         Treasure("Diamond")]),
    'corridor':
    Room(
        "Corridor",
        "A winding passage leads to the north. To east the path that brought you here",
        [Item("Portrait"), Item("Curtain")]),
    'patio':
    Room(
        "Patio",
        """A wilderness opens up before you lonely adventurer. You must return south, nothing awaits you to the north
    """, [Item("Chair"), Item("Basket"),
          Item("Knife")])
}
Esempio n. 32
0
 def add_treasure_at_pos(self, x, y):
     self.treasures[(x, y)] = Treasure.create_treasure()
Esempio n. 33
0
 def setUp(self):
     self.t = Treasure.load_treasures("test.json")
Esempio n. 34
0
def game(screen, room, level, lvl):
    pygame.display.set_caption('Maze Runner')
    font = pygame.font.Font('./data/fonts/freesansbold.ttf', 20)
    gameoverfont = winfont = pygame.font.Font('./data/fonts/freesansbold.ttf',
                                              72)
    gameovertext = gameoverfont.render('Game Over', 1, RED)
    gameoverrect = gameovertext.get_rect()
    gameoverrect.centerx = 320
    gameoverrect.centery = 240
    wintext = winfont.render('Level Completed', 1, RED)
    winrect = wintext.get_rect()
    winrect.centerx = 320
    winrect.centery = 240
    startime = font.render('Time: 0', 1, WHITE)
    startrect = startime.get_rect()
    startrect.x = 0
    startrect.y = 0
    gameovercount = 0
    gameoverdelay = 90
    wincount = 0
    windelay = 90

    invinciblecount = 0
    invincibledelay = 20
    invincibleon = False
    clock = pygame.time.Clock()
    gamePause = False
    #player=None
    walls = []
    enemys = []
    treasures = []
    starttime = time.time()
    for x in range(len(level)):
        for y in range(len(level[x])):
            char = level[x][y]
            s_x = 35 + y * 25
            s_y = 35 + x * 25
            if char == "X":
                room.wall_list.add(Wall(s_x, s_y))
            elif char == "E":
                room.enemy_sprites.add(Enemy(s_x, s_y))
            elif char == "P":
                player = Player(s_x, s_y)
            elif char == "T":
                room.treasure_list.add(Treasure(s_x, s_y))

    lives = int(player.lives)
    livestext = font.render('Lives: %s' % str(player.lives), 1, WHITE, BLACK)
    #enemy_c = len(room.enemy_sprites); enemy_text = font.render('Enemies: %s' % str(len(room.enemy_sprites)), 1, WHITE, (0,0,0))
    livesrect = livestext.get_rect()
    livesrect.x = screen.get_width() - livesrect.width
    livesrect.y = 0

    level_text = font.render('Level: %s' % str(lvl), 1, WHITE, (0, 0, 0))
    levelrect = level_text.get_rect()
    levelrect.centerx = screen.get_width() / 2
    levelrect.y = 0

    # Create the player object
    movingsprites = pygame.sprite.Group()
    movingsprites.add(player)
    bullets = pygame.sprite.Group()

    rooms = []

    rooms.append(room)

    current_room_no = 0
    current_room = rooms[current_room_no]

    done = False
    pygame.mixer.music.load('./data/background_music.ogg')
    #pygame.mixer.music.set_volume(0.5)
    pygame.mixer.music.play(-1, )
    screen.blit(startime, startrect)
    screen.blit(livestext, livesrect)

    while not done:
        screen.fill(BLACK)
        if not gamePause:
            tTime = int(round(abs(starttime - time.time())))
        else:
            if int(round(abs(starttime - time.time()))) > tTime:
                starttime += 1
        startime = font.render('Time: ' + str(tTime), 1, WHITE, BLACK)
        #livestext = font.render('Lives: %s' % str(player.lives), 1, (255,255,255), (0,0,0))

        if invinciblecount > 0: invinciblecount -= 1
        if player.invincible: invincibleon = not invincibleon
        if invinciblecount == 0: player.invincible = False

        # --- Event Processing ---
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if event.type == pygame.KEYDOWN and not gamePause:
                if event.key == pygame.K_LEFT:
                    player.changespeed(-5, 0, "LEFT")
                if event.key == pygame.K_RIGHT:
                    player.changespeed(5, 0, "RIGHT")
                if event.key == pygame.K_UP:
                    player.changespeed(0, -5, "UP")
                if event.key == pygame.K_DOWN:
                    player.changespeed(0, 5, "DOWN")
                if event.key == pygame.K_SPACE:
                    bullets.add(
                        Bullet(player.rect.x, player.rect.y + 10,
                               player.prev_dir))

            if event.type == pygame.KEYUP and not gamePause:
                if event.key == pygame.K_LEFT:
                    player.changespeed(5, 0, "LEFT")
                if event.key == pygame.K_RIGHT:
                    player.changespeed(-5, 0, "RIGHT")
                if event.key == pygame.K_UP:
                    player.changespeed(0, 5, "UP")
                if event.key == pygame.K_DOWN:
                    player.changespeed(0, -5, "DOWN")

        # --- Game Logic ---
        if not gamePause:
            player.move(current_room.wall_list, current_room.enemy_sprites,
                        current_room.treasure_list)

            for group in current_room.enemy_sprites:
                group.changespeed(player)
                group.move(current_room.wall_list)

            for treasure in current_room.treasure_list:
                treasure.animate()

            for bull in bullets:
                bull.update(current_room.wall_list, current_room.enemy_sprites)

            if lives > player.lives and player.lives >= 0:
                lives = player.lives
                livestext = font.render('Lives: %s' % str(player.lives), 1,
                                        WHITE, BLACK)
                player.invincible = True
                invinciblecount = invincibledelay
            if player.lives == 0 and (not player.dead):
                gameovercount = gameoverdelay
                gamePause = True
                player.dead = True
            if not current_room.treasure_list and (not player.won):
                wincount = windelay
                gamePause = True
                player.won = True

        if gameovercount > 0: gameovercount -= 1
        if gameovercount == 0 and player.dead:
            done = True
        if wincount > 0: wincount -= 1
        if wincount == 0 and player.won:
            pygame.sprite.Group.empty(current_room.wall_list)
            pygame.sprite.Group.empty(current_room.enemy_sprites)
            pygame.sprite.Group.empty(current_room.treasure_list)
            return True

        # --- Drawing ---
        if not player.invincible and not player.dead and not player.won:
            movingsprites.draw(screen)
        if player.invincible and invincibleon and not player.dead:
            movingsprites.draw(screen)
        current_room.wall_list.draw(screen)
        current_room.enemy_sprites.draw(screen)
        current_room.treasure_list.draw(screen)
        bullets.draw(screen)
        screen.blit(startime, startrect)
        screen.blit(livestext, livesrect)
        screen.blit(level_text, levelrect)

        if player.won:
            screen.blit(wintext, winrect)
        if player.dead:
            screen.blit(gameovertext, gameoverrect)
        #print(current_room.enemy_sprites)

        pygame.display.flip()

        clock.tick(20)
    return False