示例#1
0
    def testTargetSearch(self):
        itemList = []

        # Create a list of objects with names corresponding to ids.
        obj1 = object.Object(1)
        obj1.setName("staff1")
        itemList.append(obj1)
        obj2 = object.Object(2)
        obj2.setName("sword1")
        itemList.append(obj2)
        obj3 = object.Object(3)
        obj3.setName("armor1")
        itemList.append(obj3)
        obj4 = object.Object(4)
        obj4.setName("staff2")
        itemList.append(obj4)
        obj5 = object.Object(5)
        obj5.setName("sword2")
        itemList.append(obj5)

        inputs = [
            "staff",
            "staff 1",
            "staff sword",
            "staff 2 sword",
            "staff sword 2",
            "staff 2 sword 2",
        ]
        outputs = [
            ["staff1"],
            ["staff1"],
            ["staff1", "sword1"],
            ["staff2", "sword1"],
            ["staff1", "sword2"],
            ["staff2", "sword2"],
        ]

        for num, input in enumerate(inputs):
            targets = common.general.splitTargets(input)
            for num2, target in enumerate(targets):
                obj = common.general.targetSearch(itemList, target)
                if obj:
                    out = (
                        "Input: "
                        + str(input)
                        + " - Output: ("
                        + str(obj.getName())
                        + ") - Expected: ("
                        + str(outputs[num][num2])
                        + ")"
                    )
                    status = bool(obj.getName() == outputs[num][num2])
                else:
                    out = "Could not retrieve item for input: " + str(input)
                    status = False
                self.assertEqual(status, True, out)
示例#2
0
    def __init__(self):
        self.hero = HeroStatus()
        self.font = Font()
        self.spriteList = []
        self.spriteList.append(o.Object('../Resources/stage/uiShader.png'))
        self.spriteList.append(o.Object('../Resources/stage/character_Icon.png'))
        self.spriteList[0].set_position(960, 100)
        self.spriteList[1].set_position(100, 100)

        self.shake_float = 0.0
def drawn_canvas() -> None:
    canvas_normalized_coordinates = clipper.canvas
    canvas_obj = object.Object('___canvas', list(), [0.7, 0.2, 0], False,
                               False, False)
    canvas_obj.setToDrawnCoordinates(canvas_normalized_coordinates)
    canvas_obj.setOnBorderList([-1, -1, -1, -1])
    canvas_obj.setOnLineList([[0, 1], [0, 1], [1, 2], [1, 2], [2, 3], [2, 3],
                              [3, 0], [3, 0]])
    drawn_object(canvas_obj)
示例#4
0
 def eventHandler(self, event, keys):
     if event.type == pygame.MOUSEBUTTONDOWN:
         obj = object.Object(self.cursorPosition, self.radius, self.color,
                             self.density, tuple(self.velocity),
                             tuple(self.acceleration))
         self.objects.append(obj)
         if len(self.objects) > self.bodyLimit:
             self.objects.pop(0)
         self.clear()
     elif event.type == pygame.KEYDOWN:
         self.keyHandler(event.unicode)
示例#5
0
def make_bsp():
    global bsp_rooms
 
    cfg.objects = [cfg.player]
 
    cfg.map = [[Tile(True) for y in range(cfg.MAP_HEIGHT)] for x in range(cfg.MAP_WIDTH)]
 
    #Empty global list for storing room coordinates
    bsp_rooms = []
 
    #New root node
    bsp = libtcod.bsp_new_with_size(0, 0, cfg.MAP_WIDTH, cfg.MAP_HEIGHT)
 
    #Split into nodes
    libtcod.bsp_split_recursive(bsp, 0, cfg.DEPTH, cfg.MIN_SIZE + 1, cfg.MIN_SIZE + 1, 1.5, 1.5)
 
    #Traverse the nodes and create rooms                            
    libtcod.bsp_traverse_inverted_level_order(bsp, traverse_node)
 
    #Random room for the stairs
    stairs_location = random.choice(bsp_rooms)
    bsp_rooms.remove(stairs_location)
    if cfg.MAKE_STAIRS:
        cfg.stairs = object.Object(stairs_location[0], stairs_location[1], '>', 'stairs', libtcod.white, always_visible=True)
    else:
        cfg.stairs = object.Object(stairs_location[0], stairs_location[1], cfg.FLOOR_CHAR, ' ', cfg.color_light_ground, always_visible=False)
    cfg.objects.append(cfg.stairs)
    cfg.stairs.send_to_back()
 
    #Random room for player start
    player_room = random.choice(bsp_rooms)
    bsp_rooms.remove(player_room)
    cfg.player.x = player_room[0]
    cfg.player.y = player_room[1]
 
    #Add monsters and items
    for room in bsp_rooms:
        new_room = Rect(room[0] - cfg.MIN_SIZE/2, room[1] - cfg.MIN_SIZE/2, cfg.MIN_SIZE, cfg.MIN_SIZE)
        place_objects(new_room)
 
    initialize_fov()
示例#6
0
 def add_objects(self, objs):
     for obj in objs:
         self.objects[obj] = object.Object(objs[obj]['name'], objs[obj]['description'])
         try:
             if objs[obj]['carryable'] == 'yes':
                 self.objects[obj].make_carryable()
         except KeyError:
             pass
         try:
             self.objects[obj].add_image(objs[obj]['image'])
         except KeyError:
             pass
示例#7
0
def enter():
    global background, char, title, font
    fadescene.Fade()
    background = o.Object('../Resources/intro/background.png')
    title = o.Object('../Resources/intro/introLogo.png')
    char = o.Object('../Resources/intro/char.png')
    oList.append(Titledice('../Resources/intro/dice1.png', False))
    oList.append(Titledice( '../Resources/intro/dice2.png', False))
    oList.append(Titledice( '../Resources/intro/dice3.png', False))
    oList.append(Titledice( '../Resources/intro/dice4.png', False))
    oList.append(Titledice('../Resources/intro/dice_char.png', True))
    oList.append(Button('../Resources/intro/buttonAtlas.png', 450, 150))
    oList.append(Button('../Resources/intro/buttonAtlas.png', 300, 0))
    background.set_position(960, 540)
    title.set_position(300, 850)
    char.set_position(1300, 658)
    oList[0].set_position(600, 512)
    oList[1].set_position(1100, 600)
    oList[2].set_position(1150, 450)
    oList[3].set_position(900, 400)
    oList[4].set_position(350, 230)

    oList[5].set_position(1600, 250)
    oList[5].set_image_size(400, 100)
    oList[5].set_clip_size(608, 150)

    oList[6].set_position(1600, 100)
    oList[6].set_image_size(400, 100)
    oList[6].set_clip_size(608, 150)

    SoundManager.change_sound("../Resources/sound/title.ogg", "BackGround")
    SoundManager.add_effect_sound("../Resources/sound/effect/herowinsound.wav", "win")
    SoundManager.add_effect_sound("../Resources/sound/effect/herobattlesound.wav", "battle")
    SoundManager.play_sound("BackGround", True)

    SoundManager.add_effect_sound("../Resources/sound/effect/takebigdamage.wav", "tbdamage")
    SoundManager.add_effect_sound("../Resources/sound/effect/hugedamage.wav", "hdamage")
    SoundManager.add_effect_sound("../Resources/sound/effect/takehugedamage.wav", "thdamage")
    battle_state_sprite.Battle_state_sprite.set_init()
示例#8
0
    def create_object(self, objects, room_name, view_name, obj_name, obj_path,
                      obj):
        if self.DEBUG:
            print("        -creating object {}".format(obj_name))
        if obj['image_off'] == "empty.png":
            image_off = os.path.join(self.GRAPHICS, "empty.png")
        else:
            if type(obj['image_off']) == list:  # object is animated
                image_list = []
                for i in range(len(obj['image_off'])):
                    image_list.append(
                        os.path.join(self.GRAPHICS, room_name, view_name,
                                     obj["image_off"][i]))
                image_off = image_list
            else:
                image_off = os.path.join(self.GRAPHICS, room_name, view_name,
                                         obj["image_off"])
        if obj['image_on'] == "empty.png":
            image_on = os.path.join(self.GRAPHICS, "empty.png")
        else:
            if type(obj['image_on']) == list:  # object is animated
                image_list = []
                for i in range(len(obj['image_on'])):
                    image_list.append(
                        os.path.join(self.GRAPHICS, room_name, view_name,
                                     obj["image_on"][i]))
                image_on = image_list
            else:
                image_on = os.path.join(self.GRAPHICS, room_name, view_name,
                                        obj["image_on"])
# Check if object has "loop" property in json description.
# Object only has 'loop' in json description if it shouldn't loop.
# Loop is True by default
        loop = True
        try:
            if obj['loop'] == False:
                loop = False
                if self.DEBUG:
                    print("            loop mode for {} set to False".format(
                        obj_name))
        except KeyError:
            pass
        new_object = object_.Object(obj_name, obj['x'], obj['y'],\
                    image_off, image_on,\
                    obj['rect_off'], obj['rect_on'],\
                    layer=obj['layer'],\
                    activated=obj['activated'],examine=obj['examine'],\
                    breaks=obj['breaks'],dies=obj['dies'],message=obj['message'],response=obj["response"],\
                    info=obj['info'],speed=obj['speed'],loop=loop)
        #self.rooms[room_name][view_name]['view'].objects[obj_name] = new_object
        objects[obj_name] = new_object
示例#9
0
    def decode_item(self, file, x, y):
        item_dict = Decoder.decode(self, file)

        color = vars(libtcod)[item_dict['color']]
        item_component = Components.Item(
            use_function=vars(Components)[item_dict['use_function']])
        item = object.Object(x,
                             y,
                             item_dict['char'],
                             item_dict['name'],
                             color=color,
                             always_visible=True,
                             item=item_component)
        return item
示例#10
0
    def decode_equipment(self, file, x, y):
        item_dict = Decoder.decode(self, file)

        equipment_component = equipment.Equipment(
            slot=item_dict['slot'],
            power_bonus=item_dict['power_bonus'],
            dexterity_bonus=item_dict['dexterity_bonus'],
            max_hp_bonus=item_dict['max_hp_bonus'],
            accuracy_bonus=item_dict['accuracy_bonus'])

        color = vars(libtcod)[item_dict['color']]
        item = object.Object(x,
                             y,
                             item_dict['char'],
                             item_dict['name'],
                             color=color,
                             always_visible=True,
                             equipment=equipment_component)
        return item
示例#11
0
    def decode_enemy(self, file, x, y):
        enemy_dict = Decoder.decode(self, file)

        fighter_component = Components.Fighter(
            hp=enemy_dict['fighter']['hp'],
            dexterity=enemy_dict['fighter']['dexterity'],
            accuracy=enemy_dict['fighter']['accuracy'],
            power=enemy_dict['fighter']['power'],
            xp=enemy_dict['fighter']['xp'],
            death_function=vars(Components)[enemy_dict['death_function']])

        ai_component = vars(Components)[enemy_dict['ai']]()

        color = vars(libtcod)[enemy_dict['color']]
        monster = object.Object(x,
                                y,
                                enemy_dict['char'],
                                enemy_dict['name'],
                                color=color,
                                blocks=bool(enemy_dict['blocks']),
                                fighter=fighter_component,
                                ai=ai_component)
        return monster
示例#12
0
    def add_particles(self, pos, vel, n):
        for i in range(n):
            d = random.randint(5, 10)
            angle = random.randint(0, 359)
            color = None
            if (random.randint(0, 1)):
                color = [0xff, 0xdf, 0x00]
            else:
                color = [0xdd, 0x00, 0x00]
            smp = object.Object()
            angle = smp.calculate_angle(vel)

            a1 = int(angle - 175) % 360
            a2 = int(angle + 175) % 360
            #print(min(a1%360,a2%360),max(a1%360,a2%360))
            a = math.radians(random.randint(min(a1, a2), max(a1, a2)))
            np_angle = math.radians(random.randint(min(a1, a2), max(a1, a2)))
            newpoint = [math.cos(np_angle) * d, math.sin(np_angle) * d]
            #print(a1,a2)
            newpoint = smp.add_vec(pos, newpoint)
            speed = random.randint(100, 500)
            v = [math.cos(a), math.sin(a)]
            self.particles.append([newpoint, v, color, 100, speed])
 def get_object(self, object_requester):
     xml_objects = self.get_data_(self.GET_OBJECTS_CMD_,
                                  object_requester.to_xml())
     if xml_objects == None or len(xml_objects) == 0:
         raise DVBLinkError(DVBLinkStatus.STATUS_INVALID_DATA)
     return media_object.Object(xml_objects)
示例#14
0
 def add_image(self, string):
     self.spriteList.insert(0, o.Object(string))
     self.spriteList[0].set_position(960, 540)
示例#15
0
def place_objects(room):
    #this is where we decide the chance of each monster or item appearing.
 
    #maximum number of monsters per room
    #max_monsters = from_dungeon_level([[4, 1], [5, 4], [6, 6]])
 
    #chance of each monster
    monster_chances = {}
    for name in monst.properties:
        if name != 'player':
            monster_chances[name] = monst.properties[name].chances
 
    #maximum number of items per room
    max_items = from_dungeon_level([[0, 1], [0, 4]])
 
    #chance of each item (by default they have a chance of 0 at level 1, which then goes up)
    item_chances = {}
    item_chances['heal'] = 35  #healing potion always shows up, even if all other items have 0 chance
    item_chances['lightning'] = from_dungeon_level([[25, 4]])
    item_chances['fireball'] =  from_dungeon_level([[25, 6]])
    item_chances['confuse'] =   from_dungeon_level([[10, 2]])
    item_chances['sword'] =     from_dungeon_level([[5, 4]])
    item_chances['shield'] =    from_dungeon_level([[15, 8]])
 
 
    #choose random number of monsters
    choice = random_choice(monster_chances)
    max_monsters = monst.properties[choice].group_size
    num_monsters = libtcod.random_get_int(0, 0, max_monsters)
    
    for i in range(num_monsters):
        #choose random spot for this monster
        x = libtcod.random_get_int(0, room.x1+1, room.x2-1)
        y = libtcod.random_get_int(0, room.y1+1, room.y2-1)
 
        #only place it if the tile is not blocked
        if not is_blocked(x, y):
            object.make_monster(x, y, choice, monst.properties[choice])
 
    #generate plants/food objects
    max_plants = cfg.MAX_STARTING_PLANTS
    num_plants = libtcod.random_get_int(0, 0, max_plants)
 
    for i in range(num_plants):
        #choose random spot for this plant
        x = libtcod.random_get_int(0, room.x1+1, room.x2-1)
        y = libtcod.random_get_int(0, room.y1+1, room.y2-1)
 
        #only place it if the tile is not blocked
        if not is_occupied(x, y):
            object.make_plant(x, y)

    #choose random number of items
    num_items = libtcod.random_get_int(0, 0, max_items)
 
    for i in range(num_items):
        #choose random spot for this item
        x = libtcod.random_get_int(0, room.x1+1, room.x2-1)
        y = libtcod.random_get_int(0, room.y1+1, room.y2-1)
 
        #only place it if the tile is not blocked
        if not is_blocked(x, y):
            choice = random_choice(item_chances)
            if choice == 'heal':
                #create a healing potion
                item_component = object.Item(use_function=cast_heal)
                item = object.Object(x, y, '!', 'healing potion', libtcod.violet, item=item_component)
 
            elif choice == 'lightning':
                #create a lightning bolt scroll
                item_component = object.Item(use_function=cast_lightning)
                item = object.Object(x, y, '#', 'scroll of lightning bolt', libtcod.light_yellow, item=item_component)
 
            elif choice == 'fireball':
                #create a fireball scroll
                item_component = object.Item(use_function=cast_fireball)
                item = object.Object(x, y, '#', 'scroll of fireball', libtcod.light_yellow, item=item_component)
 
            elif choice == 'confuse':
                #create a confuse scroll
                item_component = object.Item(use_function=cast_confuse)
                item = object.Object(x, y, '#', 'scroll of confusion', libtcod.light_yellow, item=item_component)
 
            elif choice == 'sword':
                #create a sword
                equipment_component = object.Equipment(slot='right hand', power_bonus=3)
                item = object.Object(x, y, '/', 'sword', libtcod.sky, equipment=equipment_component)
 
            elif choice == 'shield':
                #create a shield
                equipment_component = object.Equipment(slot='left hand', defense_bonus=1)
                item = object.Object(x, y, '[', 'shield', libtcod.darker_orange, equipment=equipment_component)
 
            cfg.objects.append(item)
            item.send_to_back()  #items appear below other objects
            item.always_visible = True  #items are visible even out-of-FOV, if in an explored area
示例#16
0
def make_map():
    #the list of objects with just the player
    cfg.objects = [cfg.player]
 
    #fill map with "blocked" tiles
    cfg.map = [[ Tile(True)
             for y in range(cfg.MAP_HEIGHT) ]
           for x in range(cfg.MAP_WIDTH) ]
 
    rooms = []
    num_rooms = 0
 
    for r in range(cfg.MAX_ROOMS):
        #random width and height
        w = libtcod.random_get_int(0, cfg.ROOM_MIN_SIZE, cfg.ROOM_MAX_SIZE)
        h = libtcod.random_get_int(0, cfg.ROOM_MIN_SIZE, cfg.ROOM_MAX_SIZE)
        #random position without going out of the boundaries of the map
        x = libtcod.random_get_int(0, 0, cfg.MAP_WIDTH - w - 1)
        y = libtcod.random_get_int(0, 0, cfg.MAP_HEIGHT - h - 1)
 
        #"Rect" class makes rectangles easier to work with
        new_room = Rect(x, y, w, h)
 
        #run through the other rooms and see if they intersect with this one
        failed = False
        for other_room in rooms:
            if new_room.intersect(other_room):
                failed = True
                break
 
        if not failed:
            #this means there are no intersections, so this room is valid
 
            #"paint" it to the map's tiles
            create_room(new_room)
 
            #center coordinates of new room, will be useful later
            (new_x, new_y) = new_room.center()
 
            if num_rooms == 0:
                #this is the first room, where the player starts at
                cfg.player.x = new_x
                cfg.player.y = new_y
            else:
                #all rooms after the first:
                #connect it to the previous room with a tunnel
 
                #center coordinates of previous room
                (prev_x, prev_y) = rooms[num_rooms-1].center()
 
                #draw a coin (random number that is either 0 or 1)
                if libtcod.random_get_int(0, 0, 1) == 1:
                    #first move horizontally, then vertically
                    create_h_tunnel(prev_x, new_x, prev_y)
                    create_v_tunnel(prev_y, new_y, new_x)
                else:
                    #first move vertically, then horizontally
                    create_v_tunnel(prev_y, new_y, prev_x)
                    create_h_tunnel(prev_x, new_x, new_y)
 
            #add some contents to this room, such as monsters
            place_objects(new_room)
 
            #finally, append the new room to the list
            rooms.append(new_room)
            num_rooms += 1
 
    #create stairs at the center of the last room
    if cfg.MAKE_STAIRS:
        cfg.stairs = object.Object(stairs_location[0], stairs_location[1], '>', 'stairs', libtcod.white, always_visible=True)
    else:
        cfg.stairs = object.Object(stairs_location[0], stairs_location[1], cfg.FLOOR_CHAR, ' ', cfg.color_light_ground, always_visible=False)
        
    cfg.objects.append(cfg.stairs)
    cfg.stairs.send_to_back()  #so it's drawn below the monsters
示例#17
0
import render
import object
import game_io as io
import tilemap

SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50

objects = []
player = object.Object(1, 1, '@', object.OBJCLASS_PLAYER)
objects.append(player)

for i in range(4):
    monster = object.Object(4, 4 + i, 'A', object.OBJCLASS_MONSTER)
    objects.append(monster)

render.render_init(SCREEN_WIDTH, SCREEN_HEIGHT, b'Endless Tower')

game_running = True

while game_running and not render.check_window_closed():
    render.render_draw(objects)
    render.render_clear(objects)
    game_running = io.wait_for_key(player)
示例#18
0
def run():

    screen = utils.screen
    pygame.display.set_caption(utils.title)

    ### Defining Objects ###

    Player = player_.Player()
    Enemy = enemy_.Enemy()
    Object = object_.Object()

    ########################

    ### Point objects toward module json file ###

    modules = {
        Player: "modules/player.json",
        Enemy: "modules/enemy.json",
        Object: "modules/object.json",
    }

    ##############################################

    # Load modules
    for x in modules:
        modules[x] = json.loads(open(modules[x]).read())
    for module in modules:  # Preloads all images
        for m in modules[module]:
            if modules[module][m] != "Rect":
                for num, n in enumerate(modules[module][m]):
                    modules[module][m][num] = {
                        "image": pygame.image.load(n['image']).convert_alpha(),
                        "times": n['times']
                    }

    utils.map_ = util_functions.load_map_module()
    utils.map_on = utils.map_[
        'first']  # Thee is a field in the module called "first" that defines the first "level" or screen.
    load_collision_map(
        utils.map_on
    )  # This will load a level, in the future this will check if there is a saved file somewhere and load the map from there
    clock = pygame.time.Clock()

    if utils.camera_on:  # This will center the camera on the player
        utils.camerax = (utils.player['object'].x /
                         (utils.resolution[0] / 2)) - utils.resolution[0] / 3
        utils.cameray = (utils.player['object'].y /
                         (utils.resolution[1] / 2)) - utils.resolution[1] / 6
    font = pygame.font.init()

    while True:
        clock.tick(35)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.fill(utils.background_fill)

        if utils.map_[utils.map_on]['background'] == "Rect":
            for x in utils.collision_map:
                pygame.draw.rect(
                    screen, (0, 0, 0),
                    pygame.Rect(x.x - utils.camerax, x.y - utils.cameray,
                                utils.size, utils.size))
        else:
            # Draw map file
            screen.blit(
                util_functions.loader(utils.map_[utils.map_on]['background']),
                (0 - utils.camerax, 0 - utils.cameray))

        if utils.player['object']:
            if modules[Player][utils.player['state']] == "Rect":
                pygame.draw.rect(
                    screen, (0, 255, 255),
                    pygame.Rect(utils.player['object'].x - utils.camerax,
                                utils.player['object'].y - utils.cameray,
                                utils.size, utils.size))
            else:
                module = modules[Player]
                # Load images instead of block
                blitState(utils.player, module)

############# DRAW CUSTOM MODULES ########################

# These are the custom modules that you want to appear on the screen as you play

        for enemy in utils.enemies:
            if modules[Enemy][enemy['state']] == "Rect":
                pygame.draw.rect(
                    screen, (255, 0, 0),
                    pygame.Rect(enemy['object'].x - utils.camerax,
                                enemy['object'].y - utils.cameray, utils.size,
                                utils.size))
            else:
                # Load images instead
                # {"img":<image dir>, "times":4}
                pass

        for object__ in utils.objects:
            if modules[Object][object__['state']] == "Rect":
                pygame.draw.rect(
                    screen, (255, 100, 0),
                    pygame.Rect(object__['object'].x - utils.camerax,
                                object__['object'].y - utils.cameray,
                                utils.size, utils.size))


##########################################################

# Update sprites, add your sprite's update function here

        Player.update()
        Enemy.update()
        Object.update()

        ##########################################################

        for gamestate in utils.gameStatePhrases:
            if utils.gamestate == gamestate:
                for toprint in utils.gameStatePhrases[gamestate]:
                    screen.blit(
                        pygame.font.Font(toprint['font'],
                                         toprint['size']).render(
                                             toprint['phrase'], 1,
                                             toprint['color']),
                        toprint['coords'])
        pygame.display.update()
示例#19
0
class VelocityParticleSystem:
    def __init__(self):
        self.particles = []
        self.particle_release_time = 3
        self.particle_limits = 50

    def add_particle(self, pos, vel):

        parti = Particle(pos)
        parti.v = vel
        self.particles.append(parti)
        self.particle_release_time = 0

        if len(self.particles) > self.particle_limits:
            self.particles.pop(0)

    def update(self, slowvalue):
        for p in self.particles:
            p.pos = vectors.add_vec(
                p.pos, vectors.multiply(config.dt * slowvalue, p.v))

    def renderPosition(self, ref, slowvalue):
        self.update(slowvalue)
        for p in self.particles:
            p.renderPosition(ref)


if __name__ == '__main__':
    j = object.Object()
    # print(j.calculate_angle([23,34]))