def draw_labels(cache_dict, layeri=0, color=pygame.Color('black')):
    global label_font
    if label_font is None:
        label_font = pygame.font.Font(data.filepath('font', 'Vera.ttf'), 7)
    lfont = label_font
    #
    camera = State.camera
    cam_rect = State.camera.rect
    blit = camera.surface.blit
    left, top, width, height = cam_rect
    layer = State.map.layers[layeri]
    tw, th = layer.tile_width, layer.tile_height
    #
    x1 = tw - (left - left // tw * tw)
    y1 = th - (top - top // th * th)
    #
    for x in xrange(left - tw, left + width + tw, tw):
        for y in xrange(top - th, top + height + th, th):
            name = (x - tw) // tw + 1, (y - th) // th + 1
            sx, sy = x - left - tw, y - top - th
            label = cache_dict.get(name, None)
            if not label:
                label = lfont.render(
                    '{0[0]:d},{0[1]:d}'.format(name), True, color)
                cache_dict[name] = label
            blit(label, (sx + x1 + 2, sy + y1 + 2))
Пример #2
0
 def __init__(self, resolution=(640,480)):
     
     resolution = Vec2d(resolution)
     
     ## Load Tiled TMX map, then update the world's dimensions.
     tiled_map = TiledMap(data.filepath('map', 'Gumm no swamps.tmx'))
     
     Engine.__init__(self,
         caption='07 Tiled Map -  G: grid | L: labels',
         resolution=resolution,
         camera_target=Avatar((325,420), resolution//2),
         map=tiled_map,
         frame_speed=0)
     
     self.visible_objects = []
     
     # I like huds.
     toolkit.make_hud()
     
     # Create a speed box for converting mouse position to destination
     # and scroll speed.
     self.speed_box = geometry.Diamond(0,0,4,2)
     self.speed_box.center = Vec2d(State.camera.rect.size) // 2
     self.max_speed_box = float(self.speed_box.width) / 2.0
     
     # Mouse and movement state. move_to is in world coordinates.
     self.move_to = None
     self.speed = None
     self.target_moved = (0,0)
     self.mouse_down = False
     
     self.grid_cache = {}
     self.label_cache = {}
     
     State.speed = 3.33
def make_tiles(label=False):
    """Create tiles to fill the current map. This is a utility for easily making
    visible content to aid early game design or debugging.
    
    Tiles transition from top-left to bottom-right, red to blue.
    """
    # Tiles are sprites; each sprite must have a name, an image, and a rect.
    tw, th = State.map.tile_width, State.map.tile_height
    mw, mh = State.map.width, State.map.height
    layer = BasicLayer(State.map, 0)
    State.map.layers.append(layer)
    if label:
        font = pygame.font.Font(data.filepath('font', 'Vera.ttf'), 7)
        fg = Color('yellow')
        bg = Color(70, 70, 70)
    for y in range(mh):
        for x in range(mw):
            s = pygame.sprite.Sprite()
            s.name = (x, y)
            s.image = pygame.surface.Surface((tw, th))
            facx = max(float(x) / mw, 0.01)
            facy = max(float(y) / mh, 0.01)
            R = 255 - 255 * facx
            G = 0
            B = 255 * facy
            s.image.fill((R, G, B))
            s.rect = s.image.get_rect(topleft=(x * tw, y * th))
            if label:
                tag = font.render(str(s.name), 1, fg, bg)
                s.image.blit(tag, (1, 1))
            layer.add(s)
Пример #4
0
   def __init__(self,moving_beast_genitore):
       self.is_near=False
       self.testo="Hello!"
       self.close_clicked=False
       self.beeped=False
       self.scritto=False
       self.sequenza_partita=False
       self.sequenza_finita=True
       self.lista_messaggi=['...']
       self.text_altezza=50
       self.crossrect=None
       #self.dialogo_btn=False
       self.dialogo_show=False
       self.finito_dialogo=False
       self.idx_mess=0
       self.conta_click=0
       self.is_triang=False
 
       self.moving_beast_genitore=moving_beast_genitore
       self.screen=pygame.display.get_surface()
       #self.background_txt = pygame.Surface((self.screen.get_size()[0]-1,self.text_altezza))
       dir='.\\immagini\\'
       if sys.platform=='linux2':
           dir=dir.replace('\\', '/');
       square=pygame.image.load(dir+'square.png').convert_alpha()
       triangle=pygame.image.load(dir+'triangle.png').convert_alpha()
       self.triangle=pygame.transform.scale(triangle,(15,10))
       self.background_txt =pygame.transform.scale(square,(self.screen.get_size()[0]-1,self.text_altezza))
       self.backvuoto=self.background_txt.copy()
       #self.background_txt.fill((250, 250, 250))
       self.bgrect=self.background_txt.get_rect()
       self.bgrect.top=self.screen.get_size()[1]-self.text_altezza
       self.font=pygame.font.Font(data.filepath('font', 'Vera.ttf'), 18)
       #self.disegna_crocetta()
       pygame.mixer.init()
       self.suono=pygame.mixer.Sound('immagini/message.wav')
       #self.seq=MessageTimerClass(self.lista_messaggi,self)
       self.st_to_e1=StateToEvent(moving_beast_genitore.id)
       self.st_to_e2=StateToEvent(moving_beast_genitore.id)
Пример #5
0
 def load(self):
     self.map = TiledMap(
         data.filepath('map',self.map_file), collapse=self.collapse_level)
        theme.update(**custom_args)
    if not theme:
        theme = HUD_THEMES['default']
    hud = hudlight.HUD(**theme)
    if caption:
        hud.add('__caption', caption)
    topleft, bottomright = State.world.rect.topleft, State.world.rect.bottomright
    hud.add('__fps', 'FPS {:.0f}', 0.0, callback=_get_fps)
    hud.add('__bounds', 'Bounds {}, {}', topleft, bottomright)
    hud.add('__mouse', 'Mouse S{} W{}', (0, 0), (0, 0), callback=_get_mouse)
    hud.add('__camera', 'Camera S{} W{}', (0, 0), (0, 0), callback=_get_world_pos)
    return hud
HUD_THEMES = dict(
    # Boogaloo: nice fat font, red fading to blue with yellow outline
    boogaloo=dict(
        fontname=data.filepath('font', 'Boogaloo.ttf'),
        fontsize=26,
        color='red2',         # foreground color
        gcolor='deepskyblue',   # gradient color
        ocolor='yellow',        # outline color
    ),
    # Roboto_Condensded: clear thin font, blue fading to yellow with black outline
    roboto=dict(
        fontname=data.filepath('font', 'Roboto_Condensed.ttf'),
        fontsize=24,
        color='cornflowerblue',   # foreground color
        gcolor='lightyellow',       # gradient color
        ocolor='black',             # outline color
    ),
    # Bubblegum_Sans: clear, stylish, informal font, red2 fading to orange with yellow outline
    bubblegum=dict(
    def __init__(self, parameters,gameSounds):
        #playing sounds
        self.gameSounds = gameSounds
        self.gameSounds.playworld(True,0.6)
        #setting parameters
        resolution = Vec2d(parameters['resolution'])
        
        self.parameters = parameters
        if(parameters['fullscreen']):
           flags = pygame.FULLSCREEN
        else:
           flags = 0
        #creating instance of our avatar in screen
        #self.avatar = objects.ourHero("horseman","horseman",(30, 30), (0,0))
        #self.avatar.team = 1
        #self.avatar.attr = katrin

        #self.map is our map created with tile editor
        #we load all information from map
        worldmap = TiledMap(data.filepath('map', 'test.tmx'))
        #heores layer of the map edited with Tiled
        self.avatar_group = worldmap.layers[2]
        self.terrain_layer = worldmap.layers[0]
        self.collision_layer = worldmap.layers[1]
        self.objects_layer = worldmap.layers[3]
        #loading factions
        self.factions = game_dynamics.factions(self.objects_layer)

        self.actual_team = self.factions.team.pop(0)
        self.avatar = self.actual_team.heroes.pop(0)
        self.avatar.remaining_movement = self.avatar.move_points
        
        #loading creatures
        self.creatures = game_dynamics.creatures(self.objects_layer)
        #for element in  self.terrain_layer.objects:
        #   print(element.properties)
       
        ## Tell the renderer this layer needs to be sorted, and how to.
        self.avatar_group.objects.sort_key = lambda o: o.rect.bottom

        #engine initialization
        #   camera target: our avatar
        #Engine.__init__(self, caption=strcaption,camera_target= self.avatar,resolution=resolution,display_flags=pygame.FULLSCREEN,map =worldmap, frame_speed=0,camera_view_rect=pygame.Rect(0, 27, 833, 741))
        Engine.__init__(self, caption=parameters['strcaption'],camera_target= self.avatar,resolution=resolution, display_flags=flags,map =worldmap, frame_speed=0,camera_view_rect=pygame.Rect(0, 27, self.parameters["resolution"][0]-183, self.parameters["resolution"][1]-27))
        # Conserve CPU.
        State.clock.use_wait = True

        ## Insert avatars into the Fringe layer.
        self.avatar_group.add(self.avatar)
        #others avatars in actual team
        for avatars in self.actual_team.heroes:
           self.avatar_group.add(avatars)
        #others avatars in others teams
        for teams in self.factions.team:
           for avatars in teams.heroes:
              self.avatar_group.add(avatars)
        for group in self.creatures.group:
            self.avatar_group.add(group.creature)
       
        ##################
        #Game dynamics
        self.endturn = False
        ###################
        ## The renderer.
        self.renderer = BasicMapRenderer(
            worldmap, max_scroll_speed=State.speed)
        ## New requirement. When renderer draws dynamic layers (e.g. Fringe)
        ## we need to tell it to redraw the changed tiles. This also is done
        ## in the draw cycle; see self.draw_renderer().
        self.dirty_rect = Rect(self.avatar.rect)
        self.renderer.set_dirty(self.dirty_rect)

        # Make the hud.
        self.hud = toolkit.make_default_hud(theme='vera')
        # I like huds.
        #toolkit.make_hud()
        #State.hud.add('Max FPS',
        #              Statf(State.hud.next_pos(), 'Max FPS {:.0f}',
        #                    callback=lambda: (State.clock.max_fps,), interval=1.0))
        #State.hud.add('Use Wait',
        #              Statf(State.hud.next_pos(), 'Use Wait {}',
        #                    callback=lambda: (State.clock.use_wait,), interval=1.0))
        #State.hud.add('Tile Size',
        #              Statf(State.hud.next_pos(), 'Tile Size {} pixels (key={})',
        #                    callback=lambda: (self.renderer.tile_size, State.camera.rect.w // self.renderer.tile_size),
        #                    interval=1.0))


        #create world with map size and the cell size
        self.cell_size = 60
        self.world = SpatialHash(self.cell_size)
        #  no idea
        #self.set_state()
        #load entities from map, I think here we see collision rects, i.e.
        #removed temporally
        #entities, tilesheets = toolkit.load_entities(data.filepath('map', 'mini2.entities'))
        #for e in entities:
        #    State.world.add(e)
        
        # Create a speed box for converting mouse position to destination
        # and scroll speed. 800x600 has aspect ratio 8:6.
        self.speed_box = geometry.Diamond(0, 0, 8, 6)
        self.speed_box.center = Vec2d(State.camera.rect.size) // 2
        self.max_speed_box = float(self.speed_box.width) / 2.0
        
        # Mouse and movement state. move_to is in world coordinates.
        self.move_to = None
        self.move_to_G = 0
        self.speed = None
        self.mouse_down = False #left click
        self.mouse_down2 = False  #right click
        self.side_steps = []
        self.faux_avatar = objects.ourHero("horseman","horseman",self.camera.target.position, (10,0),0)
        self.final_cell_id = None
        self.path = path_finding.path()

        self.mouse_reponse = 4
        self.iterator = 0
        
        self.pathstep = None
        self.laststeppath = None 
        self.cellstep = None
        self.lastcellstep = None
        self.lastcellG = 0
        self.cellG = 0


        #keyboard managment
        self.key_down = False
        self.move_x = 0
        self.move_y = 0
        self.new_x = 0
        self.new_y = 0
        self.step = Vec2d(0,0)
        
        #computer movement
        self.pc_mov_cost = 0


        self.laststepx = 0
        self.laststepy = 0
        
        State.show_world = False
        State.speed = 5


        # Use the renderer.
        self.renderer = BasicMapRenderer(self.map, max_scroll_speed=State.speed)
             
        #game interface!
        self.interface = game_interface.gameInterface(State.screen, self.parameters)
        #populating game interface
        self.populating_interface()
Пример #8
0
Currently there is only HUD. And some dynamic stats classes with timers for
callback.
"""


import pygame
from pygame.locals import Color, RLEACCEL

if __name__ == '__main__':
    import paths
from gummworld2 import data, State


pygame.init()
hud_font = pygame.font.Font(data.filepath('font', 'Vera.ttf'), 10)
hud_alpha = 208
text_color = Color('yellow')


class HUD(pygame.sprite.OrderedUpdates):
    
    def __init__(self):
        super(HUD, self).__init__()
        self.stats = {}
        self.ordered = []
        self.top = 5
        self.font_height = hud_font.get_height()
#        self.y = lambda n: self.top + self.font_height * n
        self.x = State.screen.rect.x + 5
        self.i = 0
Пример #9
0
    def __init__(self, resolution=(800,600)):
        
        resolution = Vec2d(resolution)
        self.map_file_name = data.filepath('map', 'Gumm no swamps.tmx')
        
        # Caption for window, and HUD in full-screen mode
        caption = '09 Collapse Map - G: grid | L: labels | Collapse: 1-10 (0 is 10)'
        
        Engine.__init__(self,
            caption=caption,
            resolution=resolution, #display_flags=FULLSCREEN,
            camera_target=Avatar((325,420), resolution//2),
            map=TiledMap(self.map_file_name),
            frame_speed=0)  #, default_schedules=False)
        
        self.visible_objects = []
        
        # The collapse stat for the hud.
        self.collapse = 1
        
        # I like huds. Add more stuff to the canned hud.
        toolkit.make_hud(caption)
        State.hud.add('Collapse', Statf(State.hud.next_pos(),
            'Collapse %d', callback=lambda:self.collapse,
            interval=2.))
        State.hud.add('Tile size', Statf(State.hud.next_pos(),
            'Tile size %s', callback=lambda:str((State.map.tile_width,State.map.tile_height)),
            interval=2.))
#        def screen_info():
#            visible_tiles = State.camera.visible_tile_range
#            res = State.screen.size
#            if len(visible_tiles):
#                vis = visible_tiles[0]
#                tiles = Vec2d(vis[2]-vis[0], vis[3]-vis[1])
#            else:
#                tiles = Vec2d(0,0)
#            return 'Screen %dx%d / Visible tiles %dx%d' % (res.x,res.y,tiles.x,tiles.y,)
#        State.hud.add('Screen', Stat(State.hud.next_pos(),
#            '', callback=screen_info, interval=2.))
        def map_info():
            layern = len(State.map.layers)
            tilen = 0
            for layer in State.map.layers:
                tilen += len(layer)
            return '%d/%d' % (layern,tilen)
        State.hud.add('Layers/Tiles', Statf(State.hud.next_pos(),
            'Layers/Tiles: %s', callback=map_info, interval=2.))
        
        # Create a speed box for converting mouse position to destination
        # and scroll speed.
        self.speed_box = geometry.Diamond(0,0,4,2)
        self.speed_box.center = State.camera.abs_screen_center
        self.max_speed_box = float(self.speed_box.width) / 2.0
        
        # Mouse and movement state. move_to is in world coordinates.
        self.move_to = None
        self.speed = None
        self.mouse_down = False
        
        self.grid_cache = {}
        self.label_cache = {}