Пример #1
0
    def __init__(self, debug=False, level=1):

        self.debug = debug
        self.control = Control(self)
        self.level = Level(self)
        self.player = Player(self)
        self.ui = StartUI(self)
        self.setup(level_number=level)
Пример #2
0
    def run(self):
        self.sprites = Group()
        self.player = Player(self.surface, (0, 0), (40, 70),
                             5,
                             100,
                             200,
                             Group(),
                             gold=0,
                             animated=True)
        self.new_room()

        self.room.spawn_player(self.player)
        self.hud = Hud(self.surface, self.player)
Пример #3
0
 def __init__(self, file_name):
     self.name = file_name
     self.ref = self.mkdico()
     self.wall = Structure(self.ref, image=WALL)
     self.path = Structure(self.ref, image=[PATH, GARDIEN, ITEM1, HERO])
     self.player = Player(self.ref)
     self.gardien = Ennemy(self.ref)
     self.items = Items(self.ref)
Пример #4
0
 def loadMap(self, options):
     x, y = options["player_x"], options["player_y"]
     self.screen_size = (self.options["x_window_size"],
                         self.options["y_window_size"])
     self.map_x = self.screen_size[0] * (-1.5) - x % self.screen_size[0]
     self.map_y = self.screen_size[1] * (-1.5) - y % self.screen_size[1]
     coef_x = x // self.screen_size[0] * self.screen_size[0]
     coef_y = y // self.screen_size[1] * self.screen_size[1]
     self.chunck_loader = ChunckLoader(x, y, self, self.pil_textures,
                                       self.matrix, (coef_x, coef_y))
     self.map = self.chunck_loader.loadMapFromCenter(x, y)
     self.player = Player(self.map_x, self.map_y, self.map, self, self,
                          self.textures["fight_ui"])
     threading.Thread(target=self.chunck_loader.startCheckLoop,
                      args=(self.player, )).start()
     self.physical_engine = PhysicalEngine(self.chunck_loader, self)
     self.physical_engine.start()
     self.displayMap()
Пример #5
0
    def __init__(self, map_name):
        self.main_node = render.attachNewNode('main_node')
        self.blocked_squares = set()
        self.bodies = {}
        self.map = Map(map_name)
        self.map_builder = MapBuilder(self.map, self.main_node)
        self.map_builder.build()
        self.map_builder.clear_map_textures()
        self.player = Player(self, self.map.start_pos)
        self.set_npcs()
        self.setup_graphics()

        if S.show_view_field:
            self.view_fields = defaultdict(set)
            taskMgr.doMethodLater(1, self.update_view_fields, 'fields')
        if S.show_pathes:
            self.pathes = defaultdict(set)
            taskMgr.doMethodLater(1, self.update_pathes, 'pathes')
Пример #6
0
class Game(object):
    """Game class that contains all the game mechanics."""
    def __init__(self, debug=False, level=1):

        self.debug = debug
        self.control = Control(self)
        self.level = Level(self)
        self.player = Player(self)
        self.ui = StartUI(self)
        self.setup(level_number=level)

    def __enter__(self):

        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):

        if not self.debug:
            utility.save_object(self, 'game_exit')

    def setup_level(self, level_number):
        """Setup the game level."""

        self.level = Level(self, level_number)
        self.level.build()

        if not self.debug:
            utility.save_object(self, 'level_start')

    def setup_player(self):
        """Setup the player based on the game level"""

        map_config = level_config[self.level.number]['map']
        enter_coords = map_config['coord_enter']
        enter_orientation = map_config['orientation_enter']

        self.player.orientation = enter_orientation
        self.player.move_to(*enter_coords)
        self.player.last_action = None

    def setup(self, level_number):
        """Setup game elements."""

        # create save folder, if needed
        if not os.path.isdir('.save'):
            os.mkdir('.save')

        # setup level before player
        self.setup_level(level_number)
        self.setup_player()

    def reset(self):
        """Reset the game."""

        self.__init__()

    def mainloop(self):
        """The main game loop."""

        while True:

            if isinstance(self.ui, StartUI):
                if self.debug is True:
                    self.ui = MainUI(game=self)

            if isinstance(self.ui, MainUI):
                if self.player.cell.has_story(
                ) and not self.player.cell.story_seen:
                    self.ui = StoryUI(game=self)
                if self.level.kills_player():
                    death = self.level.get_death()
                    self.ui = PlayerDeadUI(game=self,
                                           message=death.description)
                if self.level.is_complete():
                    if self.level.has_next_level():
                        self.ui.next_level()
                    else:
                        self.ui = GameCompleteUI(game=self)
                    continue

            self.ui.process_input(self.ui.prompt())
Пример #7
0
class TowerOfBullets(metaclass=SingletonMeta):
    def __init__(self, display, fps=60):
        self.surface = display
        self.width, self.height = self.surface.get_size()
        self.fps = fps

        self.room = None
        self.player = None
        self.sprites = Group()
        self.save_dao = SaveDAO('save_info.pkl')
        self.changed_room = False

    def run(self):
        self.sprites = Group()
        self.player = Player(self.surface, (0, 0), (40, 70),
                             5,
                             100,
                             200,
                             Group(),
                             gold=0,
                             animated=True)
        self.new_room()

        self.room.spawn_player(self.player)
        self.hud = Hud(self.surface, self.player)

    def handle_input(self):
        keyboard = pygame.key.get_pressed()
        mouse = pygame.mouse.get_pressed()
        mouse_pos = pygame.mouse.get_pos()

        direction = [0, 0]
        if keyboard[pygame.K_a]:
            direction[0] = -1
        elif keyboard[pygame.K_d]:
            direction[0] = 1

        if keyboard[pygame.K_w]:
            direction[1] = -1
        elif keyboard[pygame.K_s]:
            direction[1] = 1

        self.player.move(direction)

        if keyboard[pygame.K_q]:
            self.player.swap_weapons()

        if mouse[0]:
            self.player.attack(mouse_pos)
            self.sprites.add(self.player.bullets)

    def new_room(self):
        if self.room is not None:
            self.room.kill()
        room_data = ROOMS_DB[choice(list(ROOMS_DB.keys()))]
        self.room = Room(self.surface, (0, 0), (self.width, self.height),
                         room_data)
        self.player.wall_sprites = self.room.walls
        self.room.player = self.player
        self.player.rect.left, self.player.rect.top = self.room.spawn_point
        self.changed_room = True

    def __collide_with(self, target):
        def callback(spr1, spr2):
            hited = spr1.rect.colliderect(spr2.rect)
            if hited:
                if target == 'bullet':
                    spr1.be_hit(spr2.damage)
                elif target == 'heart':
                    spr1.hp += 10
                    if spr1.hp > spr1.max_hp:
                        spr1.hp = spr1.max_hp
                elif target == 'coin':
                    spr1.gold += 1
                elif target == 'portal':
                    pass
                elif target == 'energy_orb':
                    spr1.energy += 10
                    if spr1.energy > spr1.max_energy:
                        spr1.energy = spr1.max_energy
                spr2.kill()
            return hited

        return callback

    def collision(self):
        bullets = Group()
        bullets.add(self.player.bullets)
        bullets.add(self.room.enemies_bullets)

        groupcollide(bullets, self.room.walls, True, False)
        spritecollideany(self.player,
                         self.room.enemies_bullets,
                         collided=self.__collide_with('bullet'))
        groupcollide(self.room.enemies,
                     self.player.bullets,
                     False,
                     False,
                     collided=self.__collide_with('bullet'))

        spritecollideany(self.player,
                         self.room.hearts,
                         collided=self.__collide_with('heart'))
        spritecollideany(self.player,
                         self.room.coins,
                         collided=self.__collide_with('coin'))
        spritecollideany(self.player,
                         self.room.energy_orbs,
                         collided=self.__collide_with('energy_orb'))

        if self.room.portal is not None:
            entered = self.player.rect.colliderect(self.room.portal.rect)
            if entered:
                self.new_room()
                self.player.rooms_survived += 1

    def update(self):
        self.handle_input()
        self.collision()
        self.sprites.update()
        self.player.weapon.update(pygame.mouse.get_pos())

    def render(self):
        self.update()

        # if self.changed_room:
        #     self.changed_room = False
        #     return WAITVIEW_ID

        self.room.draw()
        self.sprites.draw(self.surface)

        self.room.overlay.draw(self.surface)

        hud_render = self.hud.render()
        # ver se o jogador ganhou ou perdeu
        if self.player.hp <= 0:
            player = {
                "rooms": self.player.rooms_survived,
                "gold": self.player.gold
            }

            self.save_dao.add(player)
            return DEADVIEW_ID
        elif (len(self.room.enemies) == 0
              and self.room.wave_now > len(self.room.waves)):
            print('ganhou!')
        else:
            return hud_render
Пример #8
0
class Manager(object):

    def __init__(self, map_name):
        self.main_node = render.attachNewNode('main_node')
        self.blocked_squares = set()
        self.bodies = {}
        self.map = Map(map_name)
        self.map_builder = MapBuilder(self.map, self.main_node)
        self.map_builder.build()
        self.map_builder.clear_map_textures()
        self.player = Player(self, self.map.start_pos)
        self.set_npcs()
        self.setup_graphics()

        if S.show_view_field:
            self.view_fields = defaultdict(set)
            taskMgr.doMethodLater(1, self.update_view_fields, 'fields')
        if S.show_pathes:
            self.pathes = defaultdict(set)
            taskMgr.doMethodLater(1, self.update_pathes, 'pathes')

    def set_npcs(self):
        self.npcs = {}
        for data in self.map.npcs:
            for _ in range(data['count']):
                _data = data.copy()
                route = deque(self.map.routes[data['route']])
                free = [i for i in route if i not in self.npcs]
                assert free, 'all postions are occupated'
                pos = choice(free)
                while pos != route[0]:
                    route.rotate(1)
                _data['route'] = route
                NPC(self, **_data)#.dead = True # for debugging
        data = self.map.target_npc.copy()
        if not data:
            return
        route = deque(self.map.routes[data['route']])
        data['route'] = route
        TargetNPC(self, **data)

    def is_available(self, pos):
        return (pos in self.map and
                (pos != self.player.pos or self.player.walking) and
                (pos not in self.npcs or self.npcs[pos].walking) and
                pos not in self.bodies)

    def __call__(self, task):
        self.player.update_action()
        for npc in tuple(self.npcs.values()):
            if not npc and npc.action is None:
                if isinstance(npc, TargetNPC):
                    self.finish(True)
                del self.npcs[npc.pos]
                Body(npc, self)
                continue
            npc.update_action()
            if isinstance(npc, TargetNPC) and npc.pos == self.map.escape_position:
                self.finish(False)
        return task.cont

    def finish(self, win):
        base.finish_game(win)

    def on_player_moved(self, prev_pos, pos):
        map = self.map
        if prev_pos is None:
            prev_group = None
        elif map[prev_pos]['kind'] != 'model_field':
            prev_group = map[prev_pos]['ident']
        else:
            prev_group = map[prev_pos]['group']
        if map[pos]['kind'] != 'model_field':
            group = map[pos]['ident']
        else:
            group = map[pos]['group']
        if prev_group == group:
            return
        if prev_group is not None:
            for pos in map.groups[prev_group]:
                model = self.map_builder.get_model(pos)
                if model is None:
                    continue
                model.setAlphaScale(1)
        for pos in map.groups[group]:
            model = self.map_builder.get_model(pos)
            if model is None:
                continue
            model.setAlphaScale(S.graphics['transparency'])

    def alert(self, pos, target=None):
        for npc in self.npcs.values():
            if not npc:
                continue
            length = hypot(npc.pos[0] - pos[0], npc.pos[1] - pos[1])
            if length <= S.npc['alert_radius']:
                if isinstance(npc, TargetNPC):
                    npc.target = self.map.escape_position
                    npc.speed = S.target_npc['escape_speed']
                else:
                    npc.set_alert_texture()
                    #FIXME: don't set target if path to it doesn't exist
                    npc.target = target or self.player
                    npc.speed = S.npc['excited_speed']
                    npc.view_radius = S.npc['excited_view_radius']
                    npc.view_angle = S.npc['excited_view_angle']

    def setup_graphics(self):
        angle = self.map.hour * 15 - 90
        light_factor = max(sin(radians(angle)), 0)
        mnode = self.main_node
        alight = AmbientLight('alight')
        color = S.graphics['ambient_light_color'] + [light_factor]
        alight.setColor(VBase4(*color))
        alnp = mnode.attachNewNode(alight)
        mnode.setLight(alnp)

        dlight = DirectionalLight('dlight')
        color = S.graphics['light_color'] + [light_factor]
        dlight.setColor(VBase4(*color))
        dlnp = mnode.attachNewNode(dlight)
        dlnp.setHpr(0, -angle, 0)
        mnode.setLight(dlnp)

        if S.graphics['enable_shadows']:
            self.main_node.setShaderAuto() # doesn't work in multithreading mode
            lens = OrthographicLens()
            lens.setFilmSize(30, 30)
            lens.setNearFar(-1000, 1000)
            dlight.setLens(lens)
            ss = S.graphics['shadow_size']
            dlight.setShadowCaster(True, ss, ss)
            dlnp.reparentTo(self.player.node)
        if S.graphics['enable_cartoon']:
            # set for models separately
            self.main_node.setShaderAuto() # doesn't work in multithreading mode

    def update_view_fields(self, task):
        """ It is a very expensive funciton. Use only for debugging """
        for npc in self.npcs.values():
            key = id(npc)
            for marker in self.view_fields[key]:
                marker.removeNode()
            del self.view_fields[key]
            radius, c_angle = npc.view_radius, npc.view_angle
            angle = int(npc.actor.getHpr()[0] - 90) % 360
            pred = lambda pos: 'see' in self.map[pos]['actions']
            field = self.map.view_field(npc.pos, angle,
                                        c_angle, radius, pred)
            for pos in field:
                marker = loader.loadModel(S.model('plane'))
                marker.setHpr(0, -90, 0)
                marker.reparentTo(self.main_node)
                marker.setPos(pos[0], pos[1], 0.1)
                self.view_fields[key].add(marker)
        return task.again

    def update_pathes(self, task):
        """ It is a very expensive funciton. Use only for debugging """

        map = self.map
        for npc in self.npcs.values():
            key = id(npc)
            for marker in self.pathes[key]:
                marker.removeNode()
            del self.pathes[key]
            target = npc.target
            end_pos = target if isinstance(target, tuple) else target.pos
            pred = lambda pos: ('walk' in map[pos]['actions'] and
                                map.is_available(pos) and
                                (pos not in self.npcs or
                                self.npcs[pos].walking) and
                                pos not in self.bodies)
            path = map.get_path(npc.pos, end_pos, pred)
            if path is None:
                continue

            for pos in path:
                marker = loader.loadModel(S.model('plane'))
                marker.setHpr(0, -90, 0)
                marker.reparentTo(self.main_node)
                marker.setPos(pos[0], pos[1], 0.1)
                self.pathes[key].add(marker)
        return task.again