예제 #1
0
 def __init__(self, width, height):
     pygame.init()
     self.width = width
     self.height = height
     self.top_h = int(root.find("top_h").text)
     self.bottom_h = int(root.find("bottom_h").text)
     self.middle_h = self.height - self.top_h - self.bottom_h
     if (root.find("fullscreen").text == "True"):
         #self.screen = pygame.display.set_mode((self.width, self.height), pygame.FULLSCREEN)
         self.screen = pygame.display.set_mode((self.width, self.height),
                                               pygame.HWSURFACE)
     else:
         self.screen = pygame.display.set_mode((self.width, self.height),
                                               pygame.RESIZABLE)
     self.screen.set_colorkey(SRCALPHA)
     #self.gamearea = pygame.Rect(0, self.margin, self.width, (self.height - self.margin * 2))
     self.gamearea = self.screen.subsurface(
         Rect(0, self.top_h, self.width, self.middle_h))
     self.area_rect = self.gamearea.get_rect()
     ## using semi-transparent image for clearing the screen and smoothing out animation
     # self.bg = pygame.image.load(path.join("images", "alpha_fill.png")).convert_alpha()
     self.bg = pygame.Surface(
         (self.gamearea.get_width(), self.gamearea.get_height()))
     self.bg.fill(pygame.Color("black"))
     self.top_msg = HUD((8, 0), self.top_h, Color("yellow"), "Score: 0")
     gun = pygame.image.load(path.join("images", "gun.png")).convert_alpha()
     run = pygame.image.load(path.join("images", "run.png")).convert_alpha()
     blast = pygame.image.load(path.join("images",
                                         "blast.png")).convert_alpha()
     self.hk_list = [run, blast, gun]
     #self.bottom_msg = HotKeys((self.width, self.bottom_h), 16, self.hk_list)
     self.line_w = 1
예제 #2
0
 def spawn(self, cord, name):
     if cord == "rand":
         for n in range(20):
             x = numpy.random.randint(1, 127, size=(2))
             if self.data['path'][x[0]][x[1]] == 1:
                 HUD.print("New {} Spawned at Cord: {}".format(name, x))
                 return x
     return cord
예제 #3
0
파일: main.py 프로젝트: hai-nguyen93/mario
def play():
    pygame.init()
    settings = Settings()
    window = pygame.display.set_mode((768, 672), 0, 32)  # window's resolution
    screen = pygame.Surface(
        (settings.scr_width, settings.scr_height))  # real game's resolution
    pygame.display.set_caption("Mario")
    stats = GameStats()
    main_clock = pygame.time.Clock()
    cs = CreditsScreen(screen=window)
    go = GameoverScreen(screen=window)
    camera = Camera(screen=screen)
    sm = StageManager(screen=screen, settings=settings, stats=stats)
    hud = HUD(screen=window, settings=settings, stats=stats, stage_manager=sm)
    pc = Player(screen=screen,
                settings=settings,
                stats=stats,
                stage_manager=sm,
                camera=camera,
                hud=hud)
    sm.load_stage(stage=stats.current_stage, hud=hud)
    help_text = HelpText(screen=window, settings=settings)
    pygame.mouse.set_visible(False)

    # Main loop
    while True:
        # scale the game's resolution to window's resolution
        resized = pygame.transform.scale(screen, (768, 672))
        window.blit(resized, (0, 0))

        gf.check_inputs(player=pc)

        if stats.current_stage < stats.credits_stage and stats.current_stage != -1:
            camera.update(pc)
        if stats.current_stage != -1:
            gf.update_player(player=pc,
                             platforms=sm.platforms,
                             enemies=sm.enemies,
                             warp_zones=sm.warp_zones,
                             moving_platforms=sm.moving_platforms)
            sm.update(player=pc)

        # draw
        if stats.current_stage != -1:
            screen.fill(settings.bg_color)
            sm.draw(camera)
            pc.draw1()

        if stats.current_stage < stats.credits_stage and stats.current_stage != -1:
            hud.draw()
            if stats.current_stage == 1:
                help_text.draw(camera)
        elif stats.current_stage == stats.credits_stage:
            cs.draw()
        elif stats.current_stage == -1:
            go.draw()
        pygame.display.update()
        main_clock.tick(60)
예제 #4
0
class GameScene(Scene):
    def __init__(self):
        super().__init__()
        self.ADDRAINDROP = pygame.USEREVENT + 1
        pygame.time.set_timer(self.ADDRAINDROP, 300)

        self.backgrounds = [Background(0), Background(1)]
        self.player = Player()
        self.lumber = Lumber()
        self.raindrops = pygame.sprite.Group()
        self.obstacles = pygame.sprite.Group()
        self.obstacles.add(self.lumber)
        self.all_sprites = pygame.sprite.Group()
        self.all_sprites.add(self.player)
        self.all_sprites.add(self.lumber)
        self.hud = HUD()

        self.collision = False

    def handle_event(self, event):
        if event.type == self.ADDRAINDROP:
            new_raindrop = Raindrop()
            self.raindrops.add(new_raindrop)
            self.all_sprites.add(new_raindrop)
            self.obstacles.add(new_raindrop)

        pressed_keys = pygame.key.get_pressed()
        self.player.handle_keys(pressed_keys)

    def render(self, screen):
        screen.fill(pygame.Color('lightgrey'))
        for background in self.backgrounds:
            background.render(screen)

        for entity in self.all_sprites:
            entity.render(screen)
        self.hud.render(screen)

        pygame.display.flip()

        if self.collision == True:
            time.sleep(2)
            self.player.kill()
            self.manager.quit()

    def update(self):
        self.player.update()
        self.lumber.update()
        self.raindrops.update()
        self.hud.update()

        for background in self.backgrounds:
            background.update()

        if pygame.sprite.spritecollideany(self.player, self.obstacles,
                                          pygame.sprite.collide_mask):
            self.collision = True
예제 #5
0
 def give_birth(self, game):
     #print(f"{self.name} Borned")
     gene = {'inf': self.inf, 'inc': self.inc, 'base': self.base}
     game.add_entitie(self.name, self.cord, gene)
     for x in range(Action.database[self.specie]['inf']['maxchild']):
         if random.randint(100) < 40:
             game.add_entitie(self.name, self.cord, gene)
     self.birth = False
     HUD.print("A {}, id : {}, given birth.".format(self.name, self.id))
예제 #6
0
    def __init__(self, e_background, hero):
        self.e_background = e_background
        self.screen = thorpy.get_screen()
        self.ships = []
        self.bullets = deque()
        self.rockets = deque()
        self.hero = hero
        self.rail = shipm.Rail(self.hero)
        self.add_ship(self.rail)
        self.add_ship(hero)
        self.i = 1
        self.hero_dead = GameEvent(50,thorpy.functions.quit_menu_func,self)
        self.events = [self.hero_dead]
        self.hud = HUD()
        self.score = 0
        #
        self.ship_flux = 50
        self.ship_prob = 0.5
        self.ennemy_prob = 0.5
        #
        self.damage_rail_m = -1
        self.damage_rail_M = W + 1
        self.tot_time = 1000
        self.remaining_time = self.tot_time
        self.hints = []
        self.hints_ids = set([])
        self.laser = 0
        hlaser = self.hero.pos.y-self.hero.rect.h/2.
##        self.laser_img = pygame.Surface((p.LASER_W,hlaser))
##        self.laser_img.fill((255,255,0))
        self.laser_img = g.get_laser_img(self)
        self.laser_rect = self.laser_img.get_rect()
        #
        self.a_imgs = {}
        self.a_imgs["nice"] = g.get_imgs_alert("Right kill !", (200,255,0))
        self.a_imgs["bad"] = g.get_imgs_alert("Bad kill", (155,0,0), 20, 30)
        self.a_imgs["dead"] = g.get_imgs_alert("You are dead", (155,0,0), 40, 60)
        self.a_imgs["nuke"] = g.get_imgs_alert("Nuke!!!", size1=60, size2=90)
        self.a_imgs["item"] = g.get_imgs_alert("Got item", size1=20, size2=30)
        self.alerts = []
        #
        self.sounds = thorpy.SoundCollection()
        self.sounds.add("MikeKoenig2.wav", "bullet")
        self.sounds.add("SoundExplorer2.wav", "nuke")
        self.sounds.add("MikeKoenig3b.wav", "rocket")
        self.sounds.add("MikeKoenig4.wav", "laser")
        self.sounds.add("ljudman2.wav", "explosion")
        self.sounds.bullet.set_volume(0.1)
        #
        self.e_pause = thorpy.make_text("Pause - press a key to continue", 20, (255,255,0))
        self.e_pause.center(element=self.e_background)
        #
        self.scenario = Scenario()
        self.success = False
##        self.options = menus.get_options()
        self.last_rocket =-10
예제 #7
0
 def init(self):
     PlayState.TICK_LENGTH = 0.1
     self.tick_time = 0
     self.head = Head(PlayState.GRID_SIZE)
     self.body = []
     for i in range(PlayState.INITIAL_BODY_SIZE):
         self.__add_body__()
     self.food = Food(PlayState.GRID_SIZE, self.head.pos)
     self.hud = HUD()
     pass
예제 #8
0
class Screen:
    """ screen handling top class """
    def __init__(self, width, height):
        pygame.init()
        self.width = width
        self.height = height
        self.top_h = int(root.find("top_h").text)
        self.bottom_h = int(root.find("bottom_h").text)
        self.middle_h = self.height - self.top_h - self.bottom_h
        if (root.find("fullscreen").text == "True"):
            #self.screen = pygame.display.set_mode((self.width, self.height), pygame.FULLSCREEN)
            self.screen = pygame.display.set_mode((self.width, self.height),
                                                  pygame.HWSURFACE)
        else:
            self.screen = pygame.display.set_mode((self.width, self.height),
                                                  pygame.RESIZABLE)
        self.screen.set_colorkey(SRCALPHA)
        #self.gamearea = pygame.Rect(0, self.margin, self.width, (self.height - self.margin * 2))
        self.gamearea = self.screen.subsurface(
            Rect(0, self.top_h, self.width, self.middle_h))
        self.area_rect = self.gamearea.get_rect()
        ## using semi-transparent image for clearing the screen and smoothing out animation
        # self.bg = pygame.image.load(path.join("images", "alpha_fill.png")).convert_alpha()
        self.bg = pygame.Surface(
            (self.gamearea.get_width(), self.gamearea.get_height()))
        self.bg.fill(pygame.Color("black"))
        self.top_msg = HUD((8, 0), self.top_h, Color("yellow"), "Score: 0")
        gun = pygame.image.load(path.join("images", "gun.png")).convert_alpha()
        run = pygame.image.load(path.join("images", "run.png")).convert_alpha()
        blast = pygame.image.load(path.join("images",
                                            "blast.png")).convert_alpha()
        self.hk_list = [run, blast, gun]
        #self.bottom_msg = HotKeys((self.width, self.bottom_h), 16, self.hk_list)
        self.line_w = 1

    def update(self):
        self.top_msg.update()
        self.screen.blit(self.top_msg.background, (0, 0))
        self.screen.blit(self.top_msg.image, (0, 0))
        #self.screen.blit(self.bottom_msg.image, (self.bottom_h, self.height - self.bottom_h))
        #self.screen.blit(self.bg, (0,self.top_h))
        self.gamearea.blit(self.bg, self.area_rect, self.area_rect)

    def update_menu(self):
        pass

    def load_animation(self):
        if (self.line_w < 30):
            for y in range(0, self.height, 30):
                pygame.draw.line(self.screen, pygame.Color("black"), (0, y),
                                 (self.width, y), self.line_w)
            self.line_w += 1
            return True
        else:
            return False
예제 #9
0
class GlobalHUD(pygame.surface.Surface):

    def __init__(self, size, gamemode):
        pygame.surface.Surface.__init__(self, size, pygame.SRCALPHA, 32)
        self.hud = HUD(self)
        self.hud.acquire_global_gamemode_hud(gamemode)

    def update(self):
        self.hud.action()
    
    def render(self):
        self.fill((0,0,0,0))
        for element in self.hud.elements:
            if element.visible:
                self.blit(element.image, element.rect)
예제 #10
0
 def Init():
     Log.Message("Engine init")
     try:
         config = json.loads(
             open(os.path.join(os.path.dirname(__file__), "game.cfg"),
                  "r").read())
         Engine.properties["screen"] = (config["resolution"][0],
                                        config["resolution"][1])
         Engine.properties["title"] = config["title"]
     except IOError:
         Engine.properties["screen"] = (1024, 768)
         Engine.properties["title"] = "7444"
     pygame.init()
     Engine.properties["lastframe"] = time.time()
     if not pygame.font: Log.Warning("Warning, font disabled")
     if not pygame.mixer: Log.Warning("Warning, sound disabled")
     Engine.properties["display"] = Engine.CreateWindow(
         Engine.properties["screen"])
     Engine.DisplayVideoInfo()
     Engine.SetCaption(Engine.properties["title"])
     MatSys.Init()
     Engine.LoadSounds()
     HUD.Init(Engine)
     #Add required entities
     EntSys.AddEntity(Player, "player", Vector2D(200, 200))
     EntSys.AddEntity(Camera, "camera")
     EntSys.AddEntity(Background, "background", Vector2D(-480, -270))
     KeysGuide.Load()
     Engine.properties["font"] = pygame.font.Font(
         "data/fonts/newscycle-regular.ttf", 18)
     Log.Message("Entering loop")
     SfxSys.Play("data/sfx/the_final_frontier.wav", True)
예제 #11
0
 def newgame(self):
     self.player = Snake()
     self.food = None
     self.hud = HUD()
     self.spawnfood()
     self.state = STATE_PLAY
     pass
예제 #12
0
    def __init__(self, asurface):

        self.crashed = False

        self.hud = HUD(asurface)

        self.status = GameStatus.PLAYING
        self.road = Road(asurface)

        self.surface = asurface
        self.surface_width = surface.get_width()
        self.surface_height = surface.get_height()

        self.car = Car(surface)
        self.obstacles = []
        self.adding_obstacle = False
예제 #13
0
 def __init__(self):
     #blam, initiate that parent class
     State.__init__(self)
     self.kill_prev = True
     self.screen.fill((0, 0, 0))
     self.show_debug = False
     self.canvas = pygame.image.load('img/blankcanvas.png').convert()
     self.canvas = pygame.transform.scale(self.canvas,
                                          self.screen.get_size())
     self.canvas_pos = center(self.canvas.get_size(),
                              self.screen.get_size())
     self.current_room = StartRoom()
     self.player = Player()
     self.player.set_position(self.current_room.player_pos_left)
     self.current_room.player = self.player
     self.heads_up_display = HUD(self.player)
예제 #14
0
 def __init__(self):
     """Init pygame and the map."""
     self.WIDTH = 800
     self.HEIGHT = 600
     self.FPS = 60
     self.MAP_SIZE = (100, 100)
     self.PLAYER_POS = (0.5, 0.5)
     self.PLAYER_SIZE = (1.5, 1.5)
     self.PLAYER_REACH = 4
     self.HUD_HEIGHT = 50
     
     pygame.init()
     pygame.font.init()
     pygame.display.set_caption("tilecollision prototype")
     self.screen_size = (self.WIDTH, self.HEIGHT)
     self.screen = pygame.display.set_mode(self.screen_size)
     
     self.clock = pygame.time.Clock()
     
     self.map = Map(self.MAP_SIZE)
     self.player = MapEntity(*(self.PLAYER_POS + self.PLAYER_SIZE + (0, 0)))
     self.map.entities.append(self.player)
     
     hud_rect = (0, self.screen_size[1] - self.HUD_HEIGHT, 
                 self.screen_size[0], self.HUD_HEIGHT)
     self.hud = HUD(hud_rect)
     
     self.topleft = (0, 0) # reset to center on player
     
     self.mouse_pos = (0, 0)
예제 #15
0
def run_game():
    """Init game and run game"""
    # init config
    CFG()

    # pre-init sound
    pygame.mixer.pre_init(44100, -16, 2, 2048)

    # init pygame and screen
    pygame.init()
    if CFG().fullscreen:
        screen = pygame.display.set_mode((CFG().screen_width, CFG().screen_height), pygame.FULLSCREEN)
    else:
        screen = pygame.display.set_mode((CFG().screen_width, CFG().screen_height))

    pygame.display.set_caption('Space War 2027')

    # Internal screen
    int_screen = pygame.Surface((CFG().int_screen_width, CFG().int_screen_height))

    show_loading(screen)

    # Calculate internal scaling
    scale = CFG().screen_width / float(CFG().int_screen_width)
    CFG().int_scale_width = int(CFG().int_screen_width * scale)
    CFG().int_scale_height = int(CFG().int_screen_height * scale)

    # Init sound
    sfx.SFX()
    # Init graphics
    gfx.GFX()
    # Init game clock
    clock = pygame.time.Clock()
    # Status
    status = GameStatus()
    # Init menu
    menu = Menu(int_screen, status)
    # Init game itself
    game = Game(int_screen, status)
    # Init events
    Events()

    hud = HUD(status, screen, clock)

    # Main loop
    while True:
        dt = clock.tick(60)     # time between frames, should alter speed of everything that is not based on real time
        Events().get_events()

        if status.game_running:
            if game.update(dt): # If update is true level ended -> start new level
                game = Game(int_screen, status)
            game.draw()
            status.update()
        else:
            menu.update(game, dt)
            menu.draw()

        update_screen(screen, int_screen, hud)
예제 #16
0
    def __init__(self):
        super().__init__()
        self.ADDRAINDROP = pygame.USEREVENT + 1
        pygame.time.set_timer(self.ADDRAINDROP, 300)

        self.backgrounds = [Background(0), Background(1)]
        self.player = Player()
        self.lumber = Lumber()
        self.raindrops = pygame.sprite.Group()
        self.obstacles = pygame.sprite.Group()
        self.obstacles.add(self.lumber)
        self.all_sprites = pygame.sprite.Group()
        self.all_sprites.add(self.player)
        self.all_sprites.add(self.lumber)
        self.hud = HUD()

        self.collision = False
def game_loop(args):
    pygame.init()
    pygame.font.init()
    world = None

    try:
        # Connect to client
        client = carla.Client(args.host, args.port)
        client.set_timeout(2.0)
        # Display setting
        display = pygame.display.set_mode((args.width, args.height),
                                          pygame.HWSURFACE | pygame.DOUBLEBUF)
        hud = HUD(args.width, args.height)

        # Create ego world and spawn ego vehicle
        world = World(client.get_world(), hud, args.location, args.filter,
                      args.agent, args.scene)
        if world.player is None:
            return

        # Keyboard controller set up

        controller = KeyboardControl(world, start_in_autopilot=True)

        # Manually start the vehicle to avoid control delay
        world.player.apply_control(
            carla.VehicleControl(manual_gear_shift=True, gear=1))
        world.player.apply_control(
            carla.VehicleControl(manual_gear_shift=False))

        clock = pygame.time.Clock()

        while True:
            # Keyboard control
            clock.tick_busy_loop(60)
            if controller.parse_events(client, world, clock):
                return

            # as soon as the server is ready continue!
            world.world.wait_for_tick(5.0)
            world.tick(clock)
            world.render(display)
            pygame.display.flip()

            control = world.agent.run_step(debug=True)

            # Agent autopilot
            if world.autopilot_mode:
                # control signal to vehicle
                control.manual_gear_shift = False
                world.player.apply_control(control)

    finally:
        if world is not None:
            world.destroy()

        pygame.quit()
예제 #18
0
    def start(self):
        # set up tanks
        self.tanks = [self.battlefield.get_piece(id_) for id_ in self.tanks]
        self.active_tank = self.tanks[0]

        self.state = gs.play
        self.prev = gs.play

        # create hud
        self.hud = HUD(self, self.map_id, self.map_version)
예제 #19
0
파일: render.py 프로젝트: osm3000/dungeons
 def __init__(self, level):
     self._level = level
     self._window = level.game.game.window
     self._batch = pyglet.graphics.Batch()
     self._animations = set()
     self._sprites = {}
     self._level_vlist = None
     self._light_overlay = None
     self._last_messages_view = LastMessagesView(level.game.message_log,
                                                 self._window.width,
                                                 self._window.height,
                                                 batch=self._batch,
                                                 group=self.GROUP_HUD)
     self._hud = HUD(batch=self._batch, group=self.GROUP_HUD)
     self._level_group = ZoomGroup(
         self.zoom, CameraGroup(self._window, self.zoom, self.GROUP_LEVEL))
     self._digits_group = CameraGroup(self._window, self.zoom,
                                      self.GROUP_DIGITS)
     self._memory = collections.defaultdict(list)
예제 #20
0
class Display:
    """Holds all of the game's internals and objects."""
    
    _ent_in_control = None
    
    def __init__(self, size):
        self.surface = pygame.surface.Surface(size)
        self.hud = HUD(self.surface)
    
    def load_game(self, gamemode):
        self.camera = Camera(Map.current_map.rect.w, Map.current_map.rect.h, self.surface.get_width(), self.surface.get_height())
        self.hud.acquire_gamemode_hud(gamemode, self.camera)
        
    def update(self):
        self.camera.update()
        self.hud.action()
    
    @property
    def ent_in_control(self):
        return self._ent_in_control
        
    @ent_in_control.setter
    def ent_in_control(self, ent):
        self._ent_in_control = ent
        self.camera.target = ent
        
    def render(self):
        self.surface.fill((0xff, 0xff, 0xff))
        
        bg = Map.current_map.background
        if bg is not None:
            self.surface.blit(bg, (0,0))

        self.surface.blit(Map.current_map.image, self.camera.apply(Map.current_map))

        for object in Map.current_map.objects:
            self.surface.blit(object.image, self.camera.apply(object))

        for element in self.hud.elements:
            if element.visible:
                self.surface.blit(element.image, element.rect)
예제 #21
0
파일: render.py 프로젝트: nadako/dungeons
 def __init__(self, level):
     self._level = level
     self._window = level.game.game.window
     self._batch = pyglet.graphics.Batch()
     self._animations = set()
     self._sprites = {}
     self._level_vlist = None
     self._light_overlay = None
     self._last_messages_view = LastMessagesView(level.game.message_log, self._window.width, self._window.height, batch=self._batch, group=self.GROUP_HUD)
     self._hud = HUD(batch=self._batch, group=self.GROUP_HUD)
     self._level_group = ZoomGroup(self.zoom, CameraGroup(self._window, self.zoom, self.GROUP_LEVEL))
     self._digits_group = CameraGroup(self._window, self.zoom, self.GROUP_DIGITS)
     self._memory = collections.defaultdict(list)
예제 #22
0
파일: game.py 프로젝트: AkaiTobira/Zombie2D
class StateGame(Stete):
    generator = None
    unitManager = None
    running = True
    player = None
    HUD = None

    state_name = "GAME"

    delta_time_ticks = 0.0
    delta_time_seconds = 0.0

    obj_on_screen = []

    def __init_screen_objects(self, resolution, screen):
        self.obj_on_screen = self.generator.create_objects()
        self.player = self.generator.get_spawned_player(START_POSITION, 100)
        self.unitManager = UnitManager(self.obj_on_screen, self.player, screen,
                                       resolution)
        self.HUD = HUD(screen, self.player)

    def __init__(self, resolution, name, screen):
        self.generator = ObjectsGenerator(screen, NUMBER_OF_ENEMIES,
                                          NUMBER_OF_OBSTACLES,
                                          Vector(resolution[0], resolution[1]))
        self.__init_screen_objects(resolution, screen)

    def draw(self):
        self.unitManager.draw()
        self.HUD.draw()

    def process_input(self, event):
        self.unitManager.process_input(event)
        self.HUD.process_event(event)

    def __calculate_delta_time(self):
        delta = pygame.time.get_ticks() - self.delta_time_ticks
        self.delta_time_ticks = delta
        self.delta_time_seconds = delta / 100000.0

    def restart(self):
        return False

    def is_player_dead(self):
        return self.HUD.HP() == 0

    def no_more_zombie(self):
        return len(self.unitManager.enemy_list) == 0

    def update(self, delta):
        self.__calculate_delta_time()
        self.unitManager.process_physics(delta)
        self.HUD.update(delta)
예제 #23
0
def game_loop(args):
    pygame.init()
    pygame.font.init()
    world = None

    try:
        cruiseClient = CruiseClient(args.hostCruise, args.portCruiseTcp,
                                    args.portCruiseUdp, args.timeout)
        cruiseClient.connect()

        client = carla.Client(args.hostCarla, args.portCarla)
        client.set_timeout(5.0)

        carla_world = client.get_world()
        #settings = carla_world.get_settings()

        # We set CARLA syncronous mode
        #settings.fixed_delta_seconds = 0.1
        #settings.synchronous_mode = True
        #carla_world.apply_settings(settings)

        display = pygame.display.set_mode((args.width, args.height),
                                          pygame.HWSURFACE | pygame.DOUBLEBUF)

        display.fill((0, 0, 0))

        pygame.display.flip()

        width = args.width
        height = args.height

        hud = HUD(width, height)
        world = World(cruiseClient, carla_world, hud, args)
        controller = KeyboardControl(world)

        clock = pygame.time.Clock()
        while True:
            clock.tick_busy_loop(60)
            if controller.parse_events(client, world, clock):
                return

            world.runCruise()
            world.tick(clock)
            world.render(display)
            pygame.display.flip()
    finally:
        if world is not None:
            world.destroy()

        pygame.quit()
예제 #24
0
 def __init__(self):
     #blam, initiate that parent class
     State.__init__(self)
     self.kill_prev = True
     self.screen.fill((0,0,0))
     self.show_debug = False
     self.canvas = pygame.image.load('img/blankcanvas.png').convert()
     self.canvas = pygame.transform.scale(self.canvas, self.screen.get_size())
     self.canvas_pos = center(self.canvas.get_size(), self.screen.get_size())
     self.current_room = StartRoom()
     self.player = Player()
     self.player.set_position(self.current_room.player_pos_left)
     self.current_room.player = self.player
     self.heads_up_display = HUD(self.player)
예제 #25
0
 def hunt(self):
     check, ids = self.box_search("hunt", True)
     if check:
         x, y = check
         if Action.data['ent'][self.cord[0] + x][self.cord[1] + y][0]:
             for i, n in enumerate(Action.ent_list):
                 if n.id == ids and n.specie != 'fox':
                     del (Action.ent_list[i])
                     Action.sdraw = True
                     self.score += 20
                     self.genome.fitness += (
                         self.needs['hungry'][0] / self.needs['hungry'][1] -
                         0.5) * 35
                     self.data['ent'][n.cord[0]][n.cord[1]].remove(n.id)
                     HUD.bdraw = True
                     self.queue = []
                     HUD.deadt[n.specie].append(
                         ("hunt", n.specie, n.id, n.cord, n.score))
                     HUD.print("{} Id {}, died from {}".format(
                         n.name, n.id, 'Hunted'))
                     self.eat_counter += 1
                     return True
     return False
예제 #26
0
    def setup_hud(self):
        """Create the HUD object"""
        scr_x, scr_y = self.scr_surf.get_size()

        # Scale font based on screen size.
        font_height = 0.075
        max_width = 0.2

        # Create the HUD and register cars.
        self.hud = HUD(
            target=self.scr_surf,
            font_size=(scr_y * font_height),
            width=(scr_x * max_width),
            flash_size=(scr_x, (scr_y * font_height * 2))
        )
        self.hud.register_cars(self.sprites.sprites())
예제 #27
0
    def __init__(self, screen):
        size = screen.get_size()
        self.active_pc = 0
        self.active_skills = []
        self.screen = screen
        self.clock = pygame.time.Clock()

        self.pcs = []
        self.npcs = []

        self.hud = HUD(self)

        for p in range(3):
            self.pcs.append(PC((100, 100), 10, screen))

        for n in range(5):
            self.npcs.append(NPC((100 + n*100, 100 + n*20), 10, screen))
	def newGame(self):
		
		self.setupEnvironment()
		
		self.AIworld = AIWorld(self.render)
		
		self.introSound.stop()
		#TODO: Play creepy sound
		initialSound = loader.loadSfx('assets/sounds/enemies/nazgul_scream.mp3')
		initialSound.play()

		self.enemies = []
		self.items = []
		self.keys = []

		#TODO: Many things are only done once the game is started
		# Load the scene.
		self.loadScenario()
		
		self.player  = Player(self, self.render, 'Player', pos=Vec3(6, 1.44, -1.5))
		self.actions = ActionManager(self, self.player, self.rooms)
		
		self.em = EventManager(self, self.player, self.actions, self.rooms)
		self.em.start()

		for enemy in self.enemies:
			enemy.getHooded().addIntruder(self.player)
			enemy.start()

		self.hud      = HUD(self, self.player)
		self.controls = PlayerControls(self.player, self.actions)
		self.camctrl  = CameraControls(self, self.player)

		self.props.setCursorHidden(True)
		self.win.requestProperties(self.props)

		self.mainMenu.hideNewGame()
		
		self.addTasks()
		self.addCommands()
예제 #29
0
    def __setup_layout(self):
        """One time setup of the scene."""
        if not self.__need_setup:
            return
        stat_size = self.config['pyos']['status_size'].split(',')
        tool_size = self.config['pyos']['toolbar_size'].split(',')
        layout = TableLayout(self.config.getfloat('pyos', 'card_ratio'),
                             self.config.getfloat('pyos', 'padding'),
                             tuple([float(i) for i in stat_size]),
                             tuple([float(i) for i in tool_size]))
        layout.root.reparent_to(self.root)

        hud = HUD(layout.status, tuple([float(i) for i in stat_size]),
                  self.config['font']['normal'], self.config['font']['bold'])

        toolbar = ToolBar(self.ui.bottom_center,
                          tuple([float(i) for i in tool_size]),
                          self.config['font']['bold'],
                          (self.__new_deal, self.__reset_deal, self.__undo_move,
                           self.__menu))
        game_table = Table(layout.callback)
        layout.set_table(game_table)
        self.__systems = GameSystems(game_table, layout, hud, toolbar)
        self.__need_setup = False
예제 #30
0
    def __init__(self):
        vsync = config.IS_VSYNC
        
        if config.IS_FULLSCREEN:
            self.__window = window.Window( fullscreen=True, vsync=vsync )
        else:
            width,height = config.WIN_SIZE
            self.__window = window.Window( width=width, height=height, fullscreen=False, vsync=vsync )

        self.__winSize = winSize = ( self.__window.width, self.__window.height )

        self.__camera = Camera( winSize )
        self.__hud    = HUD( winSize )

        self.__inputManager = InputManager()
        self.__window.on_key_press   = self.__inputManager.key_pressed
        self.__window.on_key_release = self.__inputManager.key_released

        if config.IS_FPS_LIMIT:
            clock.set_fps_limit( FPS_LIMIT )
        
        glDepthFunc( GL_LEQUAL )
        glEnable( GL_DEPTH_TEST )
        self.__world = GameWorld(self)        # to musi być na końcu
예제 #31
0
class PlayState(GameState):
    TICK_LENGTH: float = 0.1
    GRID_SIZE: int = 50
    INITIAL_BODY_SIZE = 3
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    FOOD_COLOR = (0xFF, 0x90, 0x00)

    tick_time: float
    head: Head
    body: List[Body]
    food: Food
    hud: HUD

    def init(self):
        PlayState.TICK_LENGTH = 0.1
        self.tick_time = 0
        self.head = Head(PlayState.GRID_SIZE)
        self.body = []
        for i in range(PlayState.INITIAL_BODY_SIZE):
            self.__add_body__()
        self.food = Food(PlayState.GRID_SIZE, self.head.pos)
        self.hud = HUD()
        pass

    def handle_input(self):
        if MyInput.key_check_pressed(MyInput.BACK):
            self.switch_state(GameStateType.TITLE)
        self.head.handle_input()
        pass

    def update(self, screen_size: Tuple[float, float], delta_time):
        self.tick_time += delta_time
        if self.tick_time >= PlayState.TICK_LENGTH:
            self.tick_time = 0
            self.__tick__(delta_time)
        pass

    def __tick__(self, delta_time):
        for body in self.body:
            if body.colliding_with(self.head):
                Snake.score = len(self.body) - PlayState.INITIAL_BODY_SIZE
                self.switch_state(GameStateType.GAME_OVER)
        if len(self.body) >= 1:
            self.body[0].set_direction(self.head)
            for i in range(1, len(self.body)):
                self.body[i].set_direction(self.body[i - 1])
            for body in self.body:
                body.update()
        self.head.update()
        if self.head.colliding_with(self.food):
            PlayState.TICK_LENGTH *= .95
            self.food.reset(PlayState.GRID_SIZE, self.head.pos)
            self.__add_body__()
        if self.head.pos.x < 0 or self.head.pos.x > PlayState.GRID_SIZE - 1 or self.head.pos.y < 0 or self.head.pos.y > PlayState.GRID_SIZE - 1:
            Snake.score = len(self.body) - PlayState.INITIAL_BODY_SIZE
            self.switch_state(GameStateType.GAME_OVER)

    def draw(self, surface: Surface, screen_size: Tuple[float, float], delta_time):
        cell_width = 10
        grid_width = cell_width * PlayState.GRID_SIZE
        start_x = (screen_size[0] * 0.5) - (grid_width * 0.5)
        start_y = (screen_size[1] * 0.5) - (grid_width * 0.5)

        pygame.draw.rect(surface, PlayState.WHITE, Rect(start_x, start_y, grid_width, grid_width), 1)

        self.head.draw(surface, PlayState.BLACK, start_x, start_y, cell_width, cell_width)
        for body in self.body:
            body.draw(surface, PlayState.BLACK, start_x, start_y, cell_width, cell_width)

        self.food.draw(surface, PlayState.FOOD_COLOR, start_x, start_y, cell_width, cell_width)
        score = len(self.body) - PlayState.INITIAL_BODY_SIZE
        self.hud.draw(surface, start_x, start_y, grid_width, score, PlayState.BLACK)

    def __add_body__(self):
        if len(self.body) < 1:
            self.body.append(Body(self.head))
        else:
            self.body.append(Body(self.body[len(self.body) - 1]))
예제 #32
0
파일: render.py 프로젝트: nadako/dungeons
class RenderSystem(object):

    zoom = 3

    GROUP_LEVEL = pyglet.graphics.OrderedGroup(0)
    GROUP_DIGITS = pyglet.graphics.OrderedGroup(1)
    GROUP_HUD = pyglet.graphics.OrderedGroup(2)

    def __init__(self, level):
        self._level = level
        self._window = level.game.game.window
        self._batch = pyglet.graphics.Batch()
        self._animations = set()
        self._sprites = {}
        self._level_vlist = None
        self._light_overlay = None
        self._last_messages_view = LastMessagesView(level.game.message_log, self._window.width, self._window.height, batch=self._batch, group=self.GROUP_HUD)
        self._hud = HUD(batch=self._batch, group=self.GROUP_HUD)
        self._level_group = ZoomGroup(self.zoom, CameraGroup(self._window, self.zoom, self.GROUP_LEVEL))
        self._digits_group = CameraGroup(self._window, self.zoom, self.GROUP_DIGITS)
        self._memory = collections.defaultdict(list)

    def update_player(self):
        player_sprite = self._sprites[self._level.player]
        self._digits_group.focus = player_sprite
        self._level_group.parent.focus = player_sprite
        self._hud.player = self._level.player

    def render_level(self):
        vertices = []
        tex_coords = []

        for x in xrange(self._level.size_x):
            for y in xrange(self._level.size_y):
                x1 = x * 8
                x2 = x1 + 8
                y1 = y * 8
                y2 = y1 + 8

                for entity in self._level.position_system.get_entities_at(x, y):
                    renderable = entity.get(LayoutRenderable)
                    if renderable:
                        tile = renderable.tile
                        break
                else:
                    continue

                # always add floor, because we wanna draw walls above floor
                vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2))
                tex_coords.extend(floor_tex.tex_coords)

                if tile == LayoutGenerator.TILE_WALL:
                    # if we got wall, draw it above floor
                    tex = get_wall_tex(self._level.get_wall_transition(x, y))
                    vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2))
                    tex_coords.extend(tex.tex_coords)

        group = TextureGroup(dungeon_tex, pyglet.graphics.OrderedGroup(Position.ORDER_FLOOR, self._level_group))
        self._level_vlist = self._batch.add(len(vertices) / 2, pyglet.gl.GL_QUADS, group,
            ('v2i/static', vertices),
            ('t3f/statc', tex_coords),
        )

        group = pyglet.graphics.OrderedGroup(Position.ORDER_PLAYER + 1, self._level_group)
        self._light_overlay = LightOverlay(self._level.size_x, self._level.size_y, self._batch, group)

    def update_light(self, old_lightmap, new_lightmap):
        # for all changed cells
        for key in set(old_lightmap).union(new_lightmap):
            lit = key in new_lightmap
            memory = self._memory[key]

            # if cell is lit, add it to memory and clear all memory sprites, if there are any
            if lit:
                for sprite in memory:
                    sprite.delete()
                memory[:] = []

            # for every entity in cell
            for entity in self._level.position_system.get_entities_at(*key):
                # set in_fov flag
                # TODO: this doesnt belong to rendering, but i don't want to loop twice
                infov = entity.get(InFOV)
                if infov:
                    infov.in_fov = key in new_lightmap

                # if renderable, manage sprites/memory
                renderable = entity.get(Renderable)
                if not renderable:
                    continue

                # if object is lit, show its sprite
                sprite = self._sprites[entity]
                if lit:
                    sprite.visible = True
                else:
                    sprite.visible = False

                    # if it's memorable, add its current image to the memory
                    if renderable.memorable:
                        pos = entity.get(Position)
                        group = pyglet.graphics.OrderedGroup(pos.order, self._level_group)
                        sprite = pyglet.sprite.Sprite(renderable.image, pos.x * 8, pos.y * 8, batch=self._batch, group=group)
                        memory.append(sprite)


        # update light overlay
        self._light_overlay.update_light(new_lightmap, self._memory)

    def add_entity(self, entity):
        image = entity.get(Renderable).image
        pos = entity.get(Position)
        group = pyglet.graphics.OrderedGroup(pos.order, self._level_group)
        sprite = pyglet.sprite.Sprite(image, pos.x * 8, pos.y * 8, batch=self._batch, group=group)
        self._sprites[entity] = sprite
        entity.listen('image_change', self._on_image_change)
        entity.listen('move', self._on_move)

    def remove_entity(self, entity):
        sprite = self._sprites.pop(entity)
        sprite.delete()
        entity.unlisten('image_change', self._on_image_change)
        entity.unlisten('move', self._on_move)

    def _on_image_change(self, entity):
        self._sprites[entity].image = entity.get(Renderable).image

    def _on_move(self, entity, old_x, old_y, new_x, new_y):
        sprite = self._sprites[entity]
        target_x = new_x * 8
        target_y = new_y * 8

        if not sprite.visible:
            # don't animate invisible sprites
            sprite.set_position(target_x, target_y)
        else:
            start_x = sprite.x
            start_y = sprite.y

            anim = Animation(0.25)

            @anim.event
            def on_update(animation, dt, sprite=sprite, dx=(target_x - start_x), dy=(target_y - start_y)):
                ratio = animation.get_elapsed_ratio()
                x = round(start_x + dx * ratio)
                y = round(start_y + dy * ratio)
                sprite.set_position(x, y)

            @anim.event
            def on_finish(animation, sprite=sprite):
                sprite.set_position(target_x, target_y)

            self.add_animation(anim)

    def draw(self):
        self._window.clear()
        pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
        pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
        self._batch.draw()

    def dispose(self):
        for anim in tuple(self._animations):
            anim.cancel()
        assert not self._animations

        for sprite in self._sprites.values():
            sprite.delete()
        self._sprites.clear()

        for sprites in self._memory.values():
            for sprite in sprites:
                sprite.delete()
        self._memory.clear()

        if self._level_vlist:
            self._level_vlist.delete()
            self._level_vlist = None

        if self._light_overlay:
            self._light_overlay.delete()
            self._light_overlay = None

        self._last_messages_view.delete()
        self._hud.delete()

    def add_animation(self, animation):
        self._animations.add(animation)
        animation.push_handlers(on_finish=self._animations.remove)

    def animate_damage(self, x, y, dmg):
        x = (x * 8 + random.randint(2, 6)) * self.zoom
        start_y = (y * 8 + random.randint(0, 4)) * self.zoom

        label = pyglet.text.Label('-' + str(dmg), font_name='eight2empire', color=(255, 0, 0, 255),
            x=x, y=start_y, anchor_x='center', anchor_y='bottom',
            batch=self._batch, group=self._digits_group)

        anim = Animation(1)

        @anim.event
        def on_update(animation, dt, label=label, start_y=start_y, zoom=self.zoom):
            ratio = animation.get_elapsed_ratio()
            label.y = start_y + 12 * ratio * zoom
            label.color = (255, 0, 0, int((1.0 - ratio) * 255))

        @anim.event
        def on_finish(animation, label=label):
            label.delete()

        self.add_animation(anim)
예제 #33
0
    def __init__(self,
                 host="127.0.0.1",
                 port=2000,
                 viewer_res=(1280, 720),
                 obs_res=(1280, 720),
                 num_images_to_save=10000,
                 output_dir="images",
                 synchronous=True,
                 fps=30,
                 action_smoothing=0.9,
                 start_carla=True):
        """
            Initializes an environment that can be used to save camera/sensor data
            from driving around manually in CARLA.

            Connects to a running CARLA enviromment (tested on version 0.9.5) and
            spwans a lincoln mkz2017 passenger car with automatic transmission.

            host (string):
                IP address of the CARLA host
            port (short):
                Port used to connect to CARLA
            viewer_res (int, int):
                Resolution of the spectator camera (placed behind the vehicle by default)
                as a (width, height) tuple
            obs_res (int, int):
                Resolution of the observation camera (placed on the dashboard by default)
                as a (width, height) tuple
            num_images_to_save (int):
                Number of images to collect
            output_dir (str):
                Output directory to save the images to
            action_smoothing:
                Scalar used to smooth the incomming action signal.
                1.0 = max smoothing, 0.0 = no smoothing
            fps (int):
                FPS of the client. If fps <= 0 then use unbounded FPS.
                Note: Sensors will have a tick rate of fps when fps > 0, 
                otherwise they will tick as fast as possible.
            synchronous (bool):
                If True, run in synchronous mode (read the comment above for more info)
            start_carla (bool):
                Automatically start CALRA when True. Note that you need to
                set the environment variable ${CARLA_ROOT} to point to
                the CARLA root directory for this option to work.
        """

        # Start CARLA from CARLA_ROOT
        self.carla_process = None
        if start_carla:
            if "CARLA_ROOT" not in os.environ:
                raise Exception("${CARLA_ROOT} has not been set!")
            dist_dir = os.path.join(os.environ["CARLA_ROOT"], "Dist")
            if not os.path.isdir(dist_dir):
                raise Exception(
                    "Expected to find directory \"Dist\" under ${CARLA_ROOT}!")
            sub_dirs = [
                os.path.join(dist_dir, sub_dir)
                for sub_dir in os.listdir(dist_dir)
                if os.path.isdir(os.path.join(dist_dir, sub_dir))
            ]
            if len(sub_dirs) == 0:
                raise Exception(
                    "Could not find a packaged distribution of CALRA! " +
                    "(try building CARLA with the \"make package\" " +
                    "command in ${CARLA_ROOT})")
            sub_dir = sub_dirs[0]
            carla_path = os.path.join(sub_dir, "LinuxNoEditor", "CarlaUE4.sh")
            launch_command = [carla_path]
            launch_command += ["Town07"]
            if synchronous: launch_command += ["-benchmark"]
            launch_command += ["-fps=%i" % fps]
            print("Running command:")
            print(" ".join(launch_command))
            self.carla_process = subprocess.Popen(launch_command,
                                                  stdout=subprocess.PIPE,
                                                  universal_newlines=True)
            print("Waiting for CARLA to initialize")
            for line in self.carla_process.stdout:
                if "LogCarla: Number Of Vehicles" in line:
                    break
            time.sleep(2)

        # Initialize pygame for visualization
        pygame.init()
        pygame.font.init()
        width, height = viewer_res
        if obs_res is None:
            out_width, out_height = width, height
        else:
            out_width, out_height = obs_res
        self.display = pygame.display.set_mode(
            (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.clock = pygame.time.Clock()

        # Setup gym environment
        self.action_space = gym.spaces.Box(np.array([-1, 0]),
                                           np.array([1, 1]),
                                           dtype=np.float32)  # steer, throttle
        self.observation_space = gym.spaces.Box(low=0.0,
                                                high=1.0,
                                                shape=(*obs_res, 3),
                                                dtype=np.float32)
        self.fps = fps
        self.spawn_point = 1
        self.action_smoothing = action_smoothing

        self.done = False
        self.recording = False
        self.extra_info = []
        self.num_saved_observations = 0
        self.num_images_to_save = num_images_to_save
        self.observation = {key: None
                            for key in ["rgb", "segmentation"]
                            }  # Last received observations
        self.observation_buffer = {
            key: None
            for key in ["rgb", "segmentation"]
        }
        self.viewer_image = self.viewer_image_buffer = None  # Last received image to show in the viewer

        self.output_dir = output_dir
        os.makedirs(os.path.join(self.output_dir, "rgb"))
        os.makedirs(os.path.join(self.output_dir, "segmentation"))

        self.world = None
        try:
            # Connect to carla
            self.client = carla.Client(host, port)
            self.client.set_timeout(2.0)

            # Create world wrapper
            self.world = World(self.client)

            # Example: Synchronizing a camera with synchronous mode.
            settings = self.world.get_settings()
            settings.synchronous_mode = True
            self.world.apply_settings(settings)

            # Get spawn location
            lap_start_wp = self.world.map.get_waypoint(
                carla.Location(x=-180.0, y=110))
            spawn_transform = lap_start_wp.transform
            spawn_transform.location += carla.Location(z=1.0)

            # Create vehicle and attach camera to it
            self.vehicle = Vehicle(
                self.world,
                spawn_transform,
                on_collision_fn=lambda e: self._on_collision(e),
                on_invasion_fn=lambda e: self._on_invasion(e))

            # Create hud
            self.hud = HUD(width, height)
            self.hud.set_vehicle(self.vehicle)
            self.world.on_tick(self.hud.on_world_tick)

            # Create cameras
            self.dashcam_rgb = Camera(
                self.world,
                out_width,
                out_height,
                transform=camera_transforms["dashboard"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_observation_image("rgb", e))
            self.dashcam_seg = Camera(
                self.world,
                out_width,
                out_height,
                transform=camera_transforms["dashboard"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_observation_image(
                    "segmentation", e),
                camera_type="sensor.camera.semantic_segmentation"
            )  #, color_converter=carla.ColorConverter.CityScapesPalette)
            self.camera = Camera(
                self.world,
                width,
                height,
                transform=camera_transforms["spectator"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_viewer_image(e))
        except Exception as e:
            self.close()
            raise e

        self.hud.notification("Press \"Enter\" to start collecting data.")
예제 #34
0
class Game(object):
    """Main game class. Contains all game logic."""

    def __init__(self):
        # The following objects are injected by the App class.
        self.evt_mgr = None
        self.scr_surf = None
        self.logging_enabled = False

        self.sounds = dict()
        self.sprites = pygame.sprite.Group()
        self.finish_line = None
        self.background = None
        self.racing = False

        self.hud = None

    def update(self, dt):
        """Update the game logic."""
        if self.racing:
            self.update_car_vel(dt)
            self.check_for_winner()

        self.sprites.update(dt)

    def draw(self):
        """Blit surfaces to the display surface."""
        self.scr_surf.blit(self.background, (0, 0))
        self.scr_surf.blit(self.finish_line.image, self.finish_line.rect)
        self.sprites.draw(self.scr_surf)
        self.hud.draw()

    def build(self):
        """Called before the game loop starts."""
        self.setup_cars()
        self.setup_finish_line()
        self.setup_event_handlers()
        self.setup_hud()

        # Load the background and scale to screen size.
        self.background = pygame.image.load('street.png')
        self.background = pygame.transform.scale(self.background,
                                                 self.scr_surf.get_size())

        # Set the delay before a key starts repeating, and the repeat rate.
        pygame.key.set_repeat(250, 25)

        self.hud.flash("Press G to start, R to reset", 2500)

        try:
            self.sounds['race_start'] = pygame.mixer.Sound(file='gunshot.ogg')
            self.sounds['race_end'] = pygame.mixer.Sound(file='winner.ogg')
        except pygame.error:
            print('Error loading sounds: {}'.format(pygame.get_error()))
            exit(1)

        if self.logging_enabled:
            import logging
            logging.info('Game done building.')

    def on_keydown(self, evt):
        """Start or restart the race."""
        if evt.key == pygame.K_g:
            self.start_race()
        elif evt.key == pygame.K_r:
            self.reset_cars()

    def update_car_vel(self, dt):
        """Set both car's velocities to a random float from 0 to 1."""
        for car in self.sprites:
            car.vel.x = 0.01 + random.random()

    def check_for_winner(self):
        """Check if either car has hit the finish line."""
        collisions = pygame.sprite.spritecollide(self.finish_line, self.sprites,
                                                 False)
        n = len(collisions)
        log_msg = ''

        if n >= 2:
            log_msg = 'Race was a tie.'
            for car in self.sprites:
                car.adj_score(1)
                self.move_car_to_finish_area(car)
        elif n == 1:
            winner = collisions[0]
            log_msg = '{} won the race.'.format(winner)
            winner.adj_score(1)
            self.move_car_to_finish_area(winner)

        if log_msg:  # At least one car hit the finish line.
            self.racing = False
            self.play_sound('race_end')

            # Stop both cars.
            for car in self.sprites:
                car.vel.x = 0

            self.hud.flash(log_msg, 2250)

            if self.logging_enabled:
                logging.info(log_msg)

    def start_race(self):
        """Start a new race."""
        if self.logging_enabled:
            logging.info('Starting a new race')

        self.reset_cars()
        self.racing = True
        self.play_sound('race_start')

    def reset_cars(self):
        """Reset all cars to the left side and set velocity to 0."""
        if self.logging_enabled:
            logging.debug('Resetting cars')

        for car in self.sprites:
            # Move to the left side.
            car.rect.x = 0
            car.vel.x = 0

            # Set the red car on top, and blue car bellow.
            scr_y = self.scr_surf.get_size()[1]
            half_car = car.image.get_size()[1] / 2
            if car.name == 'red_car':
                car.rect.y = scr_y * 0.37 - half_car
            elif car.name == 'blue_car':
                car.rect.y = scr_y * 0.62 - half_car

    def setup_cars(self):
        """Initialize the Car sprites."""
        # Create cars using colored blocks for now.
        size = (64, 64)

        red_car = Car('red_car', pygame.Surface(size))
        red_car.image.fill((255, 0, 0))

        blue_car = Car('blue_car', pygame.Surface(size))
        blue_car.image.fill((0, 0, 255))

        # Register the cars with the sprite group.
        self.sprites.add(red_car, blue_car)

        # Give the cars their initial position.
        self.reset_cars()

    def move_car_to_finish_area(self, car):
        """Moves a car into the area after the finish line."""
        scr_x = self.scr_surf.get_size()[0]
        finish_line_left = self.finish_line.rect.x + self.finish_line.rect.width
        finish_area_mid_point = scr_x - ((scr_x - finish_line_left) / 2)

        car.rect.x = finish_area_mid_point - (car.rect.width / 2)

    def setup_finish_line(self):
        """Create the finish line surface."""
        self.finish_line = FinishLine('finish', self.scr_surf, 0.03, 0.8)

    def setup_hud(self):
        """Create the HUD object"""
        scr_x, scr_y = self.scr_surf.get_size()

        # Scale font based on screen size.
        font_height = 0.075
        max_width = 0.2

        # Create the HUD and register cars.
        self.hud = HUD(
            target=self.scr_surf,
            font_size=(scr_y * font_height),
            width=(scr_x * max_width),
            flash_size=(scr_x, (scr_y * font_height * 2))
        )
        self.hud.register_cars(self.sprites.sprites())

    def setup_event_handlers(self):
        """Register methods with specific Pygame events."""
        self.evt_mgr.subscribe(pygame.KEYDOWN, self.on_keydown)

    def play_sound(self, name):
        "Plays a sound and catches any exceptions."
        try:
            self.sounds[name].play()
        except IndexError:
            print('Error: sound {} not loaded.'.format(name))
        except pygame.error:
            print('Error: could not play sound {}.'.format(name))
    def __init__(self):
        '''
        Constructor
        '''
        # before anything else, load the profiles
        self.profiles = ProfileXMLParser().loadProfiles(os.path.join('assets','profiles.xml'))
        for p in self.profiles:
            if 'active' in p and p['active']:
                self.currentProfile = p
                break
        
        if not self.currentProfile:
            if len(self.profiles) > 0:
                self.currentProfile = self.profiles[0]
            else:
                self.setActiveProfile(profile.create_fresh_profile(id = 0))
                self.saveProfiles()
        
        #initialize managers
        pygame.init()
        random.seed()
        
        self.createDisplay()
        
        
        Utils.load_common_assets()
        
        pygame.display.set_caption("Space Domination (version %s) by Jami Couch" % VERSION)
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        self.background.fill((0,0,0))
        
        self.rootSprite = pygame.sprite.OrderedUpdates()
        self.shipSpriteGroup = pygame.sprite.RenderClear()
        self.backgroundSpriteGroup = pygame.sprite.RenderClear()
        self.foregroundSpriteGroup = pygame.sprite.RenderClear()
        self.triggerList = []
        self.messageList = []
        
        if pygame.font:
            self.defaultfont = pygame.font.Font(None, 20)
            self.largefont = pygame.font.Font(os.path.join("assets", "PLANM___.TTF"), 40)
            self.medfont = pygame.font.Font(None, 30)
        
        # load & display splash screen
        self.showSplash()
        splashTime = pygame.time.get_ticks()
        
        # show the splash for up to 5 seconds or until a key is pressed
        event = None
        keypress = False
        while (not keypress) and pygame.time.get_ticks() < splashTime + SPLASH_TIME:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    keypress = True
        
        # remove the splash screen
        self.removeSplash()
        
        # load the mission list
        self.missionList = self.loadMissionList()
        
        # load weapons
        self.weaponList = WeaponListXMLParser().loadWeaponList()
        
        # load ships
        self.shipList = ShipListXMLParser().loadShipList()
        
        # load upgrades
        self.upgradeList = UpgradeListXMLParser().load_upgrades()

        # initialize physics manager
        self.physics = Physics()
        
        # setup keymap
        self.keys = {"turnLeft" : 0, "turnRight" : 0, "accel" : 0, "brake" : 0, "fire" : 0, "alt-fire" : 0}
        
        # load the HUD
        self.HUD = HUD()
        
        # load the Campaign mangager
        self.campaignMgr = CampaignManager(self)
        
        # load the menus
        #self.menuManager = MenuManager(self.screen, self)
        self.menuManager = SpaceDominationGUI(self)
        
        
        self.gameState = SpaceDominationMain.GAMESTATE_NONE
        self.menuBackground = load_image("background.PNG")[0]
        #self.menuManager.menu_state_parse(Menu.MENU_MAIN)
        self.menuManager.set_active(True)
        self.menuManager.main_menu_click()
예제 #36
0
    def __init__(self, fps=60, fullscreen=False):
        """ (int, int, int, bool) -> Game
        Instantiate Game object with expected properties of a tower defense game. """
        pygame.init()
        
        # Parameter-based properties
        self.fps = fps
        self.fullscreen = fullscreen

        # Determine width and height
        self.screenW = pygame.display.list_modes()[0][0]
        self.screenH = pygame.display.list_modes()[0][1]
        if not self.fullscreen:
            self.screenW = floor(0.8 * self.screenW)
            self.screenH = floor(0.8 * self.screenH)

        # Display and framerate properties
        self.caption = GAME_NAME + ' - Left Mouse Button to select/place turret, drag by moving the mouse'
        self.displaySurf = None
        if self.fullscreen:
            self.flags = FULLSCREEN | DOUBLEBUF | HWACCEL
        else:
            self.flags = DOUBLEBUF | HWACCEL
        self.fpsClock = pygame.time.Clock()
        self.initializeDisplay()

        # Define and reset gameplay properties and objects
        self.money, self.wave, self.turrets, self.enemies, self.intersections, \
                    self.measuredFPS, self.tower, self.mode = [None] * 8
        self.reset()

        # HUD object 
        hudSize = 300
        hudRect = pygame.Rect(self.screenW - hudSize, 0, hudSize, self.screenH)
        hudColour = GREY
        self.hud = HUD(hudRect, hudColour, Turret(), FourShotTurret(), GlueTurret(),
                       FireTurret(), LongRange(), EightShotTurret())

        # Collision-related properties
        self.pathRects = []

        # Level appearance and elements
        self.intersectionSurface = pygame.Surface(self.displaySurf.get_size(), SRCALPHA | RLEACCEL, 32).convert_alpha()
        self.pathColour = ORANGE
        self.grassColour = LGREEN
        self.pathWidth = 50

        # Mouse and events
        self.mouseX, self.mouseY = 0, 0
        self.clicking = False
        self.dragging = False
        self.events = []

        # Health increment
        self.healthIncrement = 1

        # Menu object
        self.menu = Menu()

        # Background
        self.background = pygame.image.load(getDataFilepath(IMG_PATH_GRASS)).convert()
        self.pathImage = pygame.image.load(getDataFilepath(IMG_PATH_DIRT)).convert()

        # Sounds
        self.backgroundMusic = Sound(getDataFilepath('retro.wav'), True)
        self.hitSound = Sound(SOUND_PATH_SHOT, False)

        self.inPlay = True
예제 #37
0
	def _draw_hud(self):
		hud = HUD(self._screen())
		hud.set_score(self.hero().score())
		hud.draw()
예제 #38
0
def run_game():
    # Initialize Pygame
    pygame.mixer.pre_init(frequency=44100)
    pygame.init()
    # Initialize settings, preload assets, and create a clock
    settings = Settings()
    sounds = Sounds(settings)
    images = Images()
    clock = pygame.time.Clock()
    # Set up the window
    pygame.display.set_icon(images.icon)
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("Bullet Heck!")
    # Try to create a joystick object
    try:
        gamepad = Joystick(settings.gamepad_id)
        gamepad.init()
        settings.gamepad_connected = True
    except pygame.error:
        gamepad = None
        settings.gamepad_connected = False
    # Initialize the stats, HUD, and splash screen
    stats = Stats(settings)
    hud = HUD(settings, screen, stats, images)
    splash = SplashScreen(settings, images, screen)
    # Create the ship and groups for everything else
    ship = Ship(settings, screen, stats, images)
    stars = Group()
    bullets = Group()
    enemies = Group()
    enemy_bullets = Group()
    explosions = Group()
    pickups = Group()
    if not settings.mute_music:
        pygame.mixer.music.play(loops=-1)
    # Pause the music by default
    pygame.mixer.music.pause()
    # Main loop
    while stats.done is False:
        gf.check_events(settings, screen, ship, gamepad, bullets, stats,
                        sounds, enemies, images, enemy_bullets, splash, hud)
        gf.update_stars(settings, screen, stars, images)
        gf.manage_game_level(settings, stats)
        if stats.game_active:
            ship.update(settings, images)
            gf.spawn_enemies(settings, screen, enemies, images, id, stats)
            gf.update_bullets(settings, screen, ship, bullets, enemies, sounds,
                              enemy_bullets, images, stats, hud, explosions,
                              pickups, splash)
            gf.update_enemy_stuff(settings, screen, ship, enemies, sounds,
                                  stats, explosions, images, pickups, hud,
                                  bullets, enemy_bullets, splash)
        # Update the explosions even if the game is paused.
        gf.update_explosions(explosions)
        gf.update_screen(settings, screen, stars, ship, bullets, enemies,
                         explosions, pickups, hud, stats, enemy_bullets,
                         splash)
        clock.tick(settings.fps_limit)
        if settings.show_fps:
            stats.fps = clock.get_fps()
예제 #39
0
class Game(State):
    WHITE = (255, 255, 255)

    def __init__(self, screen):
        size = screen.get_size()
        self.active_pc = 0
        self.active_skills = []
        self.screen = screen
        self.clock = pygame.time.Clock()

        self.pcs = []
        self.npcs = []

        self.hud = HUD(self)

        for p in range(3):
            self.pcs.append(PC((100, 100), 10, screen))

        for n in range(5):
            self.npcs.append(NPC((100 + n*100, 100 + n*20), 10, screen))

    def update(self, user_input, mouse_position):
        for event in user_input:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.manager.go_to(Menu(self.screen))
                elif event.key == pygame.K_TAB:
                    self.active_pc = (self.active_pc + 1) % len(self.pcs)
                elif event.key == pygame.K_1:
                    self.pcs[self.active_pc].active_skill = 0
                elif event.key == pygame.K_2:
                    self.pcs[self.active_pc].active_skill = 1
                elif event.key == pygame.K_3:
                    self.pcs[self.active_pc].active_skill = 2
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    self.pcs[self.active_pc].target_dest = mouse_position
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
                    self.active_skills.append(self.pcs[self.active_pc].fire(mouse_position))
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 4:
                    skills_amt = len(self.pcs[self.active_pc].skills)
                    self.pcs[self.active_pc].active_skill = (self.pcs[self.active_pc].active_skill + 1) % skills_amt
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 5:
                    skills_amt = len(self.pcs[self.active_pc].skills)
                    self.pcs[self.active_pc].active_skill = (self.pcs[self.active_pc].active_skill - 1) % skills_amt

        self.active_skills = [a for a in self.active_skills if a is not None]
        self.active_skills = [a for a in self.active_skills if a.active_countdown > 0]

        for p in self.pcs:
            p.update()

        for n in self.npcs:
            n.update()

        '''
        Pass updated pcs and npcs to each skill to check for collisions.
        '''
        for a in self.active_skills:
            a.update(self.pcs, self.npcs)

    def draw(self):
        self.screen.fill(self.WHITE)

        for a in self.active_skills:
            a.draw()

        for n in self.npcs:
            n.draw()

        for p in self.pcs:
            p.draw()

        self.hud.draw()

        pygame.display.flip()
예제 #40
0
from player import Player
from sprites import *
from cast import ray_casting_walls
from hud import HUD
from gamelogic import GameLogic
pygame.init()
sc = pygame.display.set_mode((GAME_WIDTH, GAME_HEIGHT), pygame.DOUBLEBUF)
clock = pygame.time.Clock()
mp = pygame.Surface(MAP_RES)
all_s = Sprites()
player = Player(all_s)
drawing = HUD(sc, mp, player, clock)
game_logic = GameLogic(player, all_s, drawing)
drawing.menu()
pygame.mouse.set_visible(False)
game_logic.play_music()
while True:
    player.movement()
    drawing.background()
    walls, wall_shot = ray_casting_walls(player, drawing.textures)
    drawing.world(walls + [obj.locate(player) for obj in all_s.world])
    drawing.hud_fps(clock)
    drawing.mini_map()
    drawing.player_weapon([wall_shot, all_s.shot])
    game_logic.interaction_objects()
    game_logic.npc_action()
    game_logic.clear()
    game_logic.check_win()
    pygame.display.flip()
    clock.tick()
예제 #41
0
class Game:
    """Main class which handles input, drawing, and updating."""
    def __init__(self):
        """Init pygame and the map."""
        self.WIDTH = 800
        self.HEIGHT = 600
        self.FPS = 60
        self.MAP_SIZE = (100, 100)
        self.PLAYER_POS = (0.5, 0.5)
        self.PLAYER_SIZE = (1.5, 1.5)
        self.PLAYER_REACH = 4
        self.HUD_HEIGHT = 50
        
        pygame.init()
        pygame.font.init()
        pygame.display.set_caption("tilecollision prototype")
        self.screen_size = (self.WIDTH, self.HEIGHT)
        self.screen = pygame.display.set_mode(self.screen_size)
        
        self.clock = pygame.time.Clock()
        
        self.map = Map(self.MAP_SIZE)
        self.player = MapEntity(*(self.PLAYER_POS + self.PLAYER_SIZE + (0, 0)))
        self.map.entities.append(self.player)
        
        hud_rect = (0, self.screen_size[1] - self.HUD_HEIGHT, 
                    self.screen_size[0], self.HUD_HEIGHT)
        self.hud = HUD(hud_rect)
        
        self.topleft = (0, 0) # reset to center on player
        
        self.mouse_pos = (0, 0)
        
    def do_events(self):
        """Handle events from pygame."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)
            elif event.type == pygame.KEYDOWN:
                if event.key == 119: # w
                    self.player.jump = True
                elif event.key == 100: # d
                    self.player.walk_right = True
                elif event.key == 97: # a
                    self.player.walk_left = True
                else:
                    print event.key
            elif event.type == pygame.KEYUP:
                if event.key == 119: # w
                    self.player.jump = False
                elif event.key == 100: # d
                    self.player.walk_right = False
                elif event.key == 97: # a
                    self.player.walk_left = False
            elif event.type == pygame.MOUSEMOTION:
                # save mouse pos to compute map cursor each frame
                self.mouse_pos = event.pos
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    # if mouse is in valid location to place/destory block
                    if self.map.cursor_pos:
                        (gx, gy) = self.map.px_to_grid(self.topleft,
                                                       self.map.cursor_pos)
                        (gx, gy) = (int(gx), int(gy))
                        block_id = self.map.get_block(gx, gy)
                        if Block(block_id).is_solid:
                            # remove block
                            self.map.set_block(gx, gy, Block(name="air").id)
                            self.hud.add_block(block_id)
                            surf = Block(block_id).surf
                            ps_pos = (particles.ParticleSystem(surf),
                                      (gx+0.5, gy+0.5))
                            self.map._particle_systems.append(ps_pos)
                            angle = atan2(gx - self.player.x, gy -
                                          self.player.y)
                            self.player.punch((180/3.141) * angle)
                        else:
                            # add block
                            new_block = self.hud.get_selected_block()
                            self.map.set_block(gx, gy, new_block)
                elif event.button == 4: # wheel up
                    self.hud.rotate_selection(-1)
                elif event.button == 5: # wheel down
                    self.hud.rotate_selection(1)
                

    def do_update(self, elapsed):
        """Update the game state."""
        self.map.update(elapsed)
        
        # update the cursor
        # find grid distance from center of block under the mouse to
        # player's center
        (gx, gy) = self.map.px_to_grid(self.topleft, self.mouse_pos)
        (gx, gy) = (int(gx), int(gy))
        dist = sqrt(pow(gx + 0.5 - self.player.x - self.player.width/2, 2) +
                    pow(gy + 0.5 - self.player.y - self.player.height/2, 2))
        # only show cursor if close enough and block doesn't collide
        if dist > self.PLAYER_REACH:
            self.map.cursor_pos = None
        elif self.map.rect_colliding(self.player.get_rect(), (gx, gy)):
            self.map.cursor_pos = None
        else:
            self.map.cursor_pos = self.mouse_pos
    
    def do_draw(self):
        """Draw the game."""
        # fill bg red for now to show errors
        self.screen.fill((255, 0, 0))
        
        # calculate top left coordinates such that player is draw on map center
        self.topleft = (self.player.x - self.WIDTH / 2 / self.map.TILE_SIZE,
                        self.player.y - self.HEIGHT / 2 / self.map.TILE_SIZE)
        # modify top left coordinates so viewport does not leave map
        max_x = self.MAP_SIZE[0] - self.WIDTH / self.map.TILE_SIZE
        max_y = self.MAP_SIZE[1] - self.HEIGHT / self.map.TILE_SIZE
        if self.topleft[0] < 0:
            self.topleft = (0, self.topleft[1])
        elif self.topleft[0] > max_x:
            self.topleft = (max_x, self.topleft[1])
        if self.topleft[1] < 0:
            self.topleft = (self.topleft[0], 0)
        elif self.topleft[1] > max_y:
            self.topleft = (self.topleft[0], max_y)
        
        self.map.draw(self.screen, self.topleft)
        self.hud.draw(self.screen)
        
        pygame.display.flip()
    
    def main(self):
        """Run the main loop.
        
        The game state updates on a fixed timestep. The update method may be
        called a varying number of times to catch up to the current time.
        """
        now = 0
        show_fps = 0
        update_time = 0
        UPDATE_STEP = 1000/60.0 # 60 Hz
        
        # main loop
        while True:
            elapsed = pygame.time.get_ticks() - now
            now = pygame.time.get_ticks()
            
            # update as many times as needed to catch up to the current time
            while (now - (update_time + UPDATE_STEP) >= 0):
                update_time += UPDATE_STEP
                self.do_update(UPDATE_STEP)
            
            # draw and check events
            self.do_draw()
            self.do_events()
            
            # wait until it's time for next frame
            self.clock.tick(self.FPS)
            show_fps = show_fps + 1
            if (show_fps % self.FPS == 0):
                print self.clock.get_fps()
예제 #42
0
    def __init__(self,
                 host="127.0.0.1",
                 port=2000,
                 viewer_res=(1280, 720),
                 obs_res=(1280, 720),
                 reward_fn=None,
                 encode_state_fn=None,
                 synchronous=True,
                 fps=30,
                 action_smoothing=0.9,
                 start_carla=True):
        """
            Initializes a gym-like environment that can be used to interact with CARLA.

            Connects to a running CARLA enviromment (tested on version 0.9.5) and
            spwans a lincoln mkz2017 passenger car with automatic transmission.
            
            This vehicle can be controlled using the step() function,
            taking an action that consists of [steering_angle, throttle].

            host (string):
                IP address of the CARLA host
            port (short):
                Port used to connect to CARLA
            viewer_res (int, int):
                Resolution of the spectator camera (placed behind the vehicle by default)
                as a (width, height) tuple
            obs_res (int, int):
                Resolution of the observation camera (placed on the dashboard by default)
                as a (width, height) tuple
            reward_fn (function):
                Custom reward function that is called every step.
                If None, no reward function is used.
            encode_state_fn (function):
                Function that takes the image (of obs_res resolution) from the
                observation camera and encodes it to some state vector to returned
                by step(). If None, step() returns the full image.
            action_smoothing:
                Scalar used to smooth the incomming action signal.
                1.0 = max smoothing, 0.0 = no smoothing
            fps (int):
                FPS of the client. If fps <= 0 then use unbounded FPS.
                Note: Sensors will have a tick rate of fps when fps > 0, 
                otherwise they will tick as fast as possible.
            synchronous (bool):
                If True, run in synchronous mode (read the comment above for more info)
            start_carla (bool):
                Automatically start CALRA when True. Note that you need to
                set the environment variable ${CARLA_ROOT} to point to
                the CARLA root directory for this option to work.
        """

        # Start CARLA from CARLA_ROOT
        self.carla_process = None
        if start_carla:
            if "CARLA_ROOT" not in os.environ:
                raise Exception("${CARLA_ROOT} has not been set!")
            dist_dir = os.path.join(os.environ["CARLA_ROOT"], "Dist")
            if not os.path.isdir(dist_dir):
                raise Exception(
                    "Expected to find directory \"Dist\" under ${CARLA_ROOT}!")
            sub_dirs = [
                os.path.join(dist_dir, sub_dir)
                for sub_dir in os.listdir(dist_dir)
                if os.path.isdir(os.path.join(dist_dir, sub_dir))
            ]
            if len(sub_dirs) == 0:
                raise Exception(
                    "Could not find a packaged distribution of CALRA! " +
                    "(try building CARLA with the \"make package\" " +
                    "command in ${CARLA_ROOT})")
            sub_dir = sub_dirs[0]
            carla_path = os.path.join(sub_dir, "LinuxNoEditor", "CarlaUE4.sh")
            launch_command = [carla_path]
            launch_command += ["Town07"]
            if synchronous: launch_command += ["-benchmark"]
            launch_command += ["-fps=%i" % fps]
            print("Running command:")
            print(" ".join(launch_command))
            self.carla_process = subprocess.Popen(launch_command,
                                                  stdout=subprocess.DEVNULL)
            print("Waiting for CARLA to initialize")
            for line in self.carla_process.stdout:
                if "LogCarla: Number Of Vehicles" in line:
                    break
            time.sleep(2)

        # Initialize pygame for visualization
        pygame.init()
        pygame.font.init()
        width, height = viewer_res
        if obs_res is None:
            out_width, out_height = width, height
        else:
            out_width, out_height = obs_res
        self.display = pygame.display.set_mode(
            (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.clock = pygame.time.Clock()
        self.synchronous = synchronous

        # Setup gym environment
        self.seed()
        self.action_space = gym.spaces.Box(np.array([-1, 0]),
                                           np.array([1, 1]),
                                           dtype=np.float32)  # steer, throttle
        self.observation_space = gym.spaces.Box(low=0.0,
                                                high=1.0,
                                                shape=(*obs_res, 3),
                                                dtype=np.float32)
        self.metadata[
            "video.frames_per_second"] = self.fps = self.average_fps = fps
        self.spawn_point = 1
        self.action_smoothing = action_smoothing
        self.encode_state_fn = (
            lambda x: x) if not callable(encode_state_fn) else encode_state_fn
        self.reward_fn = (
            lambda x: 0) if not callable(reward_fn) else reward_fn
        self.max_distance = 3000  # m

        self.world = None
        try:
            # Connect to carla
            self.client = carla.Client(host, port)
            self.client.set_timeout(60.0)

            # Create world wrapper
            self.world = World(self.client)

            if self.synchronous:
                settings = self.world.get_settings()
                settings.synchronous_mode = True
                self.world.apply_settings(settings)

            # Create vehicle and attach camera to it
            self.vehicle = Vehicle(
                self.world,
                self.world.map.get_spawn_points()[0],
                on_collision_fn=lambda e: self._on_collision(e),
                on_invasion_fn=lambda e: self._on_invasion(e))

            # Create hud
            self.hud = HUD(width, height)
            self.hud.set_vehicle(self.vehicle)
            self.world.on_tick(self.hud.on_world_tick)

            # Create cameras
            self.dashcam = Camera(
                self.world,
                out_width,
                out_height,
                transform=camera_transforms["dashboard"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_observation_image(e),
                sensor_tick=0.0 if self.synchronous else 1.0 / self.fps)
            self.camera = Camera(
                self.world,
                width,
                height,
                transform=camera_transforms["spectator"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_viewer_image(e),
                sensor_tick=0.0 if self.synchronous else 1.0 / self.fps)
        except Exception as e:
            self.close()
            raise e

        # Reset env to set initial state
        self.reset()
class MetalSlender(ShowBase):
	
	VERSION=0.1
	
	GRAVITY = 9.81
	
	def __init__(self):
		ShowBase.__init__(self)
		
		self.initVideo()
		self.initGame()
	
	def initVideo(self):
		self.render.setShaderAuto()
		#TODO: Not working
		self.render.setAntialias(AntialiasAttrib.MMultisample)

		self.props = WindowProperties()

# 		self.props.setFullscreen(True)
#  		self.props.setSize(1920, 1080)
 		self.props.setSize(1280, 720)
		self.props.setCursorHidden(False)
		self.props.setMouseMode(self.props.M_absolute)
		
		self.win.requestProperties(self.props)
		self.win.movePointer(0, 100, 100)

	def initGame(self):
		self.paused = False
		self.initTimer = True
		self.time = 0
		self.gameOver = True

# 		self.setFrameRateMeter(True)
		self.taskMgr.add(self.menuDisplay, "menuDisplay")

		self.mainMenu = MainMenu(self)
		
		self.introSound = self.loader.loadSfx('assets/sounds/intro.mp3')
		self.introSound.setLoop(True)
		self.introSound.play()
		
	#TODO: Refactor environment into a class that inherits from nodepath
	def setupEnvironment(self):
		self.setBackgroundColor(0,0,0)
		self.setupLighting()
		self.setupFog()
		self.setupSkydome()
		self.setupPhysics()
		
	def setupFog(self):
		self.fog = Fog("fog")

		self.fog.setColor(FOG_COLOR)
		self.fog.setExpDensity(FOG_EXP_DENSITY)

		self.render.setFog(self.fog)
		
	def setupSkydome(self):
		self.skydome = self.loader.loadModel(EGG_SKYDOME)
		self.skydome.setBin('background', 0)
		self.skydome.setDepthWrite(False)
		self.skydome.reparentTo(self.cam)
		self.skydome.setCompass()
		self.skydome.setLight(self.shadeless)
		self.skydome.setScale(20)
		
	def setupLighting(self):
		alight = AmbientLight("AmbientLight")
		alight.setColor(AMBIENT_LIGHT)
		self.amblight = self.render.attachNewNode(alight)
		self.render.setLight(self.amblight)
		
		alight = AmbientLight("ShadelessLight")
		alight.setColor((1.0, 1.0, 1.0, 1.0))
		self.shadeless = self.render.attachNewNode(alight)
		
	def setupPhysics(self):
		self.cTrav = CollisionTraverser()
		
		plane = self.render.attachNewNode(CollisionNode('WorldBottom'))
		plane.node().addSolid(CollisionPlane(Plane(0, 0, 1, 30)))
		plane.node().setIntoCollideMask(CollisionMask.SCENE)
	#TODO: Set the scenario's into collide mask to a special value		
	def loadScenario(self):
		self.rooms = []
		
		self.rooms.append(Room(self, self.render, "LCG"      , "assets/chicken/lcg"    ))
		self.rooms.append(Room(self, self.render, "Bloco H"  , "assets/chicken/blocoh" ))
		self.rooms.append(Room(self, self.render, "Bloco H2" , "assets/chicken/blocoh2"))
		self.rooms.append(Room(self, self.render, "Collision", "assets/chicken/collision"    ))
		self.rooms[-1].root.setCollideMask(CollisionMask.SCENE)
		
	def addCommands(self):
		self.accept('escape', self.userExit)
		self.accept('g', self.endGame)
		self.accept('i', self.actionKeys, ['i'])
		self.accept('p', self.pauseGame)
		self.accept('z', self.restartGame)
		
		self.cTrav.setRespectPrevTransform(True)
		
	def addTasks(self):
		self.taskMgr.add(self.camctrl.update, "camera/control")
		self.taskMgr.add(self.player.updateAll, "player/update")
		self.taskMgr.add(self.hud.update, 'hud')
		self.taskMgr.add(self.player.flashlight.updatePower, 'player/flashlight/update')
		self.taskMgr.add(self.AIUpdate,"AIUpdate")
		self.taskMgr.add(self.camctrl.update, "camera/control")
		self.taskMgr.add(self.checkGoal, 'CheckGoal')

	def actionKeys(self, key):
		if key == 'i':
			self.player.fear = min(self.player.fear + 0.1, 1.0)

	def AIUpdate(self,task):
		pass
		hasAttacked = []
		for enemy in self.enemies:
			attack = enemy.update()
			hasAttacked.append(attack)
		for i in hasAttacked:
			if (i == True):
				self.player.hurt()#TODO:The enemy itself should hurt the player
				#attack
		self.AIworld.update()
		if (self.player.isDead()):
			for enemy in self.enemies:
				enemy.stop()
			self.endGame()
			return task.done
		return task.cont

	def newGame(self):
		
		self.setupEnvironment()
		
		self.AIworld = AIWorld(self.render)
		
		self.introSound.stop()
		#TODO: Play creepy sound
		initialSound = loader.loadSfx('assets/sounds/enemies/nazgul_scream.mp3')
		initialSound.play()

		self.enemies = []
		self.items = []
		self.keys = []

		#TODO: Many things are only done once the game is started
		# Load the scene.
		self.loadScenario()
		
		self.player  = Player(self, self.render, 'Player', pos=Vec3(6, 1.44, -1.5))
		self.actions = ActionManager(self, self.player, self.rooms)
		
		self.em = EventManager(self, self.player, self.actions, self.rooms)
		self.em.start()

		for enemy in self.enemies:
			enemy.getHooded().addIntruder(self.player)
			enemy.start()

		self.hud      = HUD(self, self.player)
		self.controls = PlayerControls(self.player, self.actions)
		self.camctrl  = CameraControls(self, self.player)

		self.props.setCursorHidden(True)
		self.win.requestProperties(self.props)

		self.mainMenu.hideNewGame()
		
		self.addTasks()
		self.addCommands()
		
# 		self.cTrav = None
	
	def pauseGame(self):
		if (self.paused == True):
			self.props.setCursorHidden(True)
			self.win.requestProperties(self.props)
			self.mainMenu.hidePauseGame()
			self.paused = False
			self.events.start()
			self.taskMgr.add(self.player.updateAll, "player/update")
			self.taskMgr.add(self.hud.update, 'hud')
			self.taskMgr.add(self.player.flashlight.updatePower, 'player/flashlight/update')
			self.taskMgr.add(self.AIUpdate,"AIUpdate")
			self.taskMgr.add(self.camctrl.update, "camera/control")
			self.taskMgr.add(self.checkGoal, 'CheckGoal')
			self.accept('p', self.pauseGame)
		else:
			self.events.stop()
			self.ignore('p')
			self.player.pause()
			self.taskMgr.remove("camera/control")
			self.taskMgr.remove("player/update")
			self.taskMgr.remove('hud')
			self.player.resetLast()
			self.taskMgr.remove('player/flashlight/update')
			self.taskMgr.remove("AIUpdate")
			self.taskMgr.remove('CheckGoal')
			self.props.setCursorHidden(False)
			self.win.requestProperties(self.props)
			self.mainMenu.showPauseGame()
			self.paused = True
		
	def restartGame(self):
		self.events.stop()
		self.taskMgr.remove("camera/control")
		self.taskMgr.remove("player/update")
		self.taskMgr.remove('hud')
		self.taskMgr.remove('player/flashlight/update')
		self.taskMgr.remove("AIUpdate")
		self.taskMgr.remove('CheckGoal')
		self.cleanResources()
		self.props.setCursorHidden(False)
		self.win.requestProperties(self.props)
		self.initGame()
	
	def cleanResources(self):
		self.AIworld = None
		del self.enemies [:]
		del self.rooms [:]
		self.enemies = None
		self.rooms = None
		self.player = None
		self.actions = None
		self.events = None
		self.mainMenu = None
		self.fog = None
		self.skydome.removeNode()
		self.amblight.removeNode()
		self.shadeless.removeNode()
		self.target1.removeNode()
		self.target2.removeNode()
		self.banana.removeNode()
		self.skydome = None
		self.amblight = None
		self.shadeless = None
		self.target1 = None
		self.target2 = None
		self.banana = None
		self.hud = None
		self.camctrl = None
		self.controls = None
		self.cTrav.clearColliders()
		gc.collect()

		self.taskMgr.add(self.player.updateAll, "player/update")
		self.taskMgr.add(self.player.flashlight.updatePower, 'player/flashlight/update')
		self.taskMgr.add(self.AIUpdate,"AIUpdate")
		self.taskMgr.add(self.camctrl.update, "camera/control")
		self.taskMgr.add(self.playerUpdate, "playerUpdate")
		self.taskMgr.add(self.checkGoal, 'CheckGoal')

	def endGame(self):
		self.hud.hide()
		if (self.gameOver):
			self.image = OnscreenImage(image="assets/images/GameOver.png", pos = (0, 0, 0), parent=base.render2d, scale=(1,1,1))
		else:
			self.image = OnscreenImage(image="assets/images/to-be-continued.jpg", pos = (0, 0, 0), parent=base.render2d, scale=(1,1,1))
		self.startTimer(3)

		self.taskMgr.remove("camera/control")

	def menuDisplay(self, task):
		if (self.initTimer == False):
			hasFinished = self.timer()
			if (hasFinished):
				self.resetTimer()
				self.image.hide()
				self.props.setCursorHidden(False)
				self.props.setMouseMode(self.props.M_absolute)
				self.win.requestProperties(self.props)
				self.mainMenu.showNewGame()

		return task.cont

	def timer(self):
		currentTime = time.time()
		diff = currentTime - self.time
		if (diff > self.interval):
			self.resetTimer()
			return True
		else:
			return False

	def resetTimer(self):
		self.initTimer = True

	def startTimer(self, interval):
		if (self.initTimer == True):
			self.interval = interval
			self.initTimer = False
			self.time = time.time()

	def playerUpdate(self, task):
		reached = self.checkGoal()
		if (reached):
# 			self.player.die()
			self.endGame()
			return task.done
		someKey = False
		for key in self.actions.keys:
			if (key.wasPicked()):
				someKey = True
		self.hud.setKey(someKey)

		return task.cont

	def checkGoal(self, task):
		close = not self.goal.isEmpty() and self.player.getNodePath().getDistance(self.goal) < 2
		hasKey = 'goal' in [key.lock for key in self.player.inventory]
		if (close and hasKey):
			self.gameOver = False
			self.endGame()
		return task.cont
예제 #44
0
파일: render.py 프로젝트: osm3000/dungeons
class RenderSystem(object):

    zoom = 3

    GROUP_LEVEL = pyglet.graphics.OrderedGroup(0)
    GROUP_DIGITS = pyglet.graphics.OrderedGroup(1)
    GROUP_HUD = pyglet.graphics.OrderedGroup(2)

    def __init__(self, level):
        self._level = level
        self._window = level.game.game.window
        self._batch = pyglet.graphics.Batch()
        self._animations = set()
        self._sprites = {}
        self._level_vlist = None
        self._light_overlay = None
        self._last_messages_view = LastMessagesView(level.game.message_log,
                                                    self._window.width,
                                                    self._window.height,
                                                    batch=self._batch,
                                                    group=self.GROUP_HUD)
        self._hud = HUD(batch=self._batch, group=self.GROUP_HUD)
        self._level_group = ZoomGroup(
            self.zoom, CameraGroup(self._window, self.zoom, self.GROUP_LEVEL))
        self._digits_group = CameraGroup(self._window, self.zoom,
                                         self.GROUP_DIGITS)
        self._memory = collections.defaultdict(list)

    def update_player(self):
        player_sprite = self._sprites[self._level.player]
        self._digits_group.focus = player_sprite
        self._level_group.parent.focus = player_sprite
        self._hud.player = self._level.player

    def render_level(self):
        vertices = []
        tex_coords = []

        for x in xrange(self._level.size_x):
            for y in xrange(self._level.size_y):
                x1 = x * 8
                x2 = x1 + 8
                y1 = y * 8
                y2 = y1 + 8

                for entity in self._level.position_system.get_entities_at(
                        x, y):
                    renderable = entity.get(LayoutRenderable)
                    if renderable:
                        tile = renderable.tile
                        break
                else:
                    continue

                # always add floor, because we wanna draw walls above floor
                vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2))
                tex_coords.extend(floor_tex.tex_coords)

                if tile == LayoutGenerator.TILE_WALL:
                    # if we got wall, draw it above floor
                    tex = get_wall_tex(self._level.get_wall_transition(x, y))
                    vertices.extend((x1, y1, x2, y1, x2, y2, x1, y2))
                    tex_coords.extend(tex.tex_coords)

        group = TextureGroup(
            dungeon_tex,
            pyglet.graphics.OrderedGroup(Position.ORDER_FLOOR,
                                         self._level_group))
        self._level_vlist = self._batch.add(
            len(vertices) / 2,
            pyglet.gl.GL_QUADS,
            group,
            ('v2i/static', vertices),
            ('t3f/statc', tex_coords),
        )

        group = pyglet.graphics.OrderedGroup(Position.ORDER_PLAYER + 1,
                                             self._level_group)
        self._light_overlay = LightOverlay(self._level.size_x,
                                           self._level.size_y, self._batch,
                                           group)

    def update_light(self, old_lightmap, new_lightmap):
        # for all changed cells
        for key in set(old_lightmap).union(new_lightmap):
            lit = key in new_lightmap
            memory = self._memory[key]

            # if cell is lit, add it to memory and clear all memory sprites, if there are any
            if lit:
                for sprite in memory:
                    sprite.delete()
                memory[:] = []

            # for every entity in cell
            for entity in self._level.position_system.get_entities_at(*key):
                # set in_fov flag
                # TODO: this doesnt belong to rendering, but i don't want to loop twice
                infov = entity.get(InFOV)
                if infov:
                    infov.in_fov = key in new_lightmap

                # if renderable, manage sprites/memory
                renderable = entity.get(Renderable)
                if not renderable:
                    continue

                # if object is lit, show its sprite
                sprite = self._sprites[entity]
                if lit:
                    sprite.visible = True
                else:
                    sprite.visible = False

                    # if it's memorable, add its current image to the memory
                    if renderable.memorable:
                        pos = entity.get(Position)
                        group = pyglet.graphics.OrderedGroup(
                            pos.order, self._level_group)
                        sprite = pyglet.sprite.Sprite(renderable.image,
                                                      pos.x * 8,
                                                      pos.y * 8,
                                                      batch=self._batch,
                                                      group=group)
                        memory.append(sprite)

        # update light overlay
        self._light_overlay.update_light(new_lightmap, self._memory)

    def add_entity(self, entity):
        image = entity.get(Renderable).image
        pos = entity.get(Position)
        group = pyglet.graphics.OrderedGroup(pos.order, self._level_group)
        sprite = pyglet.sprite.Sprite(image,
                                      pos.x * 8,
                                      pos.y * 8,
                                      batch=self._batch,
                                      group=group)
        self._sprites[entity] = sprite
        entity.listen('image_change', self._on_image_change)
        entity.listen('move', self._on_move)

    def remove_entity(self, entity):
        sprite = self._sprites.pop(entity)
        sprite.delete()
        entity.unlisten('image_change', self._on_image_change)
        entity.unlisten('move', self._on_move)

    def _on_image_change(self, entity):
        self._sprites[entity].image = entity.get(Renderable).image

    def _on_move(self, entity, old_x, old_y, new_x, new_y):
        sprite = self._sprites[entity]
        target_x = new_x * 8
        target_y = new_y * 8

        if not sprite.visible:
            # don't animate invisible sprites
            sprite.set_position(target_x, target_y)
        else:
            start_x = sprite.x
            start_y = sprite.y

            anim = Animation(0.25)

            @anim.event
            def on_update(animation,
                          dt,
                          sprite=sprite,
                          dx=(target_x - start_x),
                          dy=(target_y - start_y)):
                ratio = animation.get_elapsed_ratio()
                x = round(start_x + dx * ratio)
                y = round(start_y + dy * ratio)
                sprite.set_position(x, y)

            @anim.event
            def on_finish(animation, sprite=sprite):
                sprite.set_position(target_x, target_y)

            self.add_animation(anim)

    def draw(self):
        self._window.clear()
        pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
        pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA,
                              pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
        self._batch.draw()

    def dispose(self):
        for anim in tuple(self._animations):
            anim.cancel()
        assert not self._animations

        for sprite in self._sprites.values():
            sprite.delete()
        self._sprites.clear()

        for sprites in self._memory.values():
            for sprite in sprites:
                sprite.delete()
        self._memory.clear()

        if self._level_vlist:
            self._level_vlist.delete()
            self._level_vlist = None

        if self._light_overlay:
            self._light_overlay.delete()
            self._light_overlay = None

        self._last_messages_view.delete()
        self._hud.delete()

    def add_animation(self, animation):
        self._animations.add(animation)
        animation.push_handlers(on_finish=self._animations.remove)

    def animate_damage(self, x, y, dmg):
        x = (x * 8 + random.randint(2, 6)) * self.zoom
        start_y = (y * 8 + random.randint(0, 4)) * self.zoom

        label = pyglet.text.Label('-' + str(dmg),
                                  font_name='eight2empire',
                                  color=(255, 0, 0, 255),
                                  x=x,
                                  y=start_y,
                                  anchor_x='center',
                                  anchor_y='bottom',
                                  batch=self._batch,
                                  group=self._digits_group)

        anim = Animation(1)

        @anim.event
        def on_update(animation,
                      dt,
                      label=label,
                      start_y=start_y,
                      zoom=self.zoom):
            ratio = animation.get_elapsed_ratio()
            label.y = start_y + 12 * ratio * zoom
            label.color = (255, 0, 0, int((1.0 - ratio) * 255))

        @anim.event
        def on_finish(animation, label=label):
            label.delete()

        self.add_animation(anim)
예제 #45
0
 def __init__(self, size):
     self.surface = pygame.surface.Surface(size)
     self.hud = HUD(self.surface)
class SpaceDominationMain(object):
    '''
    classdocs
    '''
    # game state constants
    GAMESTATE_NONE = 0
    GAMESTATE_RUNNING = 1
    GAMESTATE_PAUSED = 2
    GAMESTATE_GAMEOVER = 3
    

    
    gameState = GAMESTATE_NONE
    
    physics = None
    menuManager = None
    missionList = None
    weaponList = None
    shipList = None
    currentMission = None
    upgradeList = None
    
    playerShip = None
    
    fpstext = None
    
    lastTick = 0
    timeTotal = 0
    clock = None
    screen = None
    screen_buffer = None
    window = None
    background = None
    menuBackground = None
    
    defaultfont = None
    largefont = None
    medfont = None
    
    rootSprite = None
    
    shipSpriteGroup = None
    destroyedSpriteGroup = None
    backgroundSpriteGroup = None
    triggerList = None
    foregroundSpriteGroup = None
    elapsedTime = 0.0
    messageList = None
    
    # Profile stuff
    profiles = None
    currentProfile = None
    
    HUD = None
    
    # Campaign manager
    campaignMgr = None
    
    def __init__(self):
        '''
        Constructor
        '''
        # before anything else, load the profiles
        self.profiles = ProfileXMLParser().loadProfiles(os.path.join('assets','profiles.xml'))
        for p in self.profiles:
            if 'active' in p and p['active']:
                self.currentProfile = p
                break
        
        if not self.currentProfile:
            if len(self.profiles) > 0:
                self.currentProfile = self.profiles[0]
            else:
                self.setActiveProfile(profile.create_fresh_profile(id = 0))
                self.saveProfiles()
        
        #initialize managers
        pygame.init()
        random.seed()
        
        self.createDisplay()
        
        
        Utils.load_common_assets()
        
        pygame.display.set_caption("Space Domination (version %s) by Jami Couch" % VERSION)
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        self.background.fill((0,0,0))
        
        self.rootSprite = pygame.sprite.OrderedUpdates()
        self.shipSpriteGroup = pygame.sprite.RenderClear()
        self.backgroundSpriteGroup = pygame.sprite.RenderClear()
        self.foregroundSpriteGroup = pygame.sprite.RenderClear()
        self.triggerList = []
        self.messageList = []
        
        if pygame.font:
            self.defaultfont = pygame.font.Font(None, 20)
            self.largefont = pygame.font.Font(os.path.join("assets", "PLANM___.TTF"), 40)
            self.medfont = pygame.font.Font(None, 30)
        
        # load & display splash screen
        self.showSplash()
        splashTime = pygame.time.get_ticks()
        
        # show the splash for up to 5 seconds or until a key is pressed
        event = None
        keypress = False
        while (not keypress) and pygame.time.get_ticks() < splashTime + SPLASH_TIME:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    keypress = True
        
        # remove the splash screen
        self.removeSplash()
        
        # load the mission list
        self.missionList = self.loadMissionList()
        
        # load weapons
        self.weaponList = WeaponListXMLParser().loadWeaponList()
        
        # load ships
        self.shipList = ShipListXMLParser().loadShipList()
        
        # load upgrades
        self.upgradeList = UpgradeListXMLParser().load_upgrades()

        # initialize physics manager
        self.physics = Physics()
        
        # setup keymap
        self.keys = {"turnLeft" : 0, "turnRight" : 0, "accel" : 0, "brake" : 0, "fire" : 0, "alt-fire" : 0}
        
        # load the HUD
        self.HUD = HUD()
        
        # load the Campaign mangager
        self.campaignMgr = CampaignManager(self)
        
        # load the menus
        #self.menuManager = MenuManager(self.screen, self)
        self.menuManager = SpaceDominationGUI(self)
        
        
        self.gameState = SpaceDominationMain.GAMESTATE_NONE
        self.menuBackground = load_image("background.PNG")[0]
        #self.menuManager.menu_state_parse(Menu.MENU_MAIN)
        self.menuManager.set_active(True)
        self.menuManager.main_menu_click()
        # TODO: show the menu
        # eventually the menu will lead to...
        #self.gameState = SpaceDominationMain.GAMESTATE_RUNNING
        #self.currentMission = self.loadMission("mission01.xml")
        #self.buildMission(self.currentMission)
    
    def run(self):
        rect_list = []
        while True:
            # handle input
            events = pygame.event.get()
            
            for event in events:
                if event.type == QUIT:
                    sys.exit(0)
                elif self.menuManager.is_active():
                    self.menuManager.update(event)
                
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        if self.gameState == self.GAMESTATE_RUNNING:
                            self.pause_game()
                    # movement
                    elif event.key == K_UP:
                        self.setKey("accel", 1)
                    elif event.key == K_DOWN:
                        self.setKey("brake", 1)
                    elif event.key == K_LEFT:
                        self.setKey("turnLeft", 1)
                    elif event.key == K_RIGHT:
                        self.setKey("turnRight", 1)
                    elif event.key == K_SPACE:
                        self.setKey("fire", 1)
                    # weapon swapping
                    elif event.key >= pygame.K_1 and event.key <= pygame.K_9:
                        wp = event.key - pygame.K_1
                        if len(self.playerShip.weapons) >= wp + 1:
                            self.playerShip.selected_weapon = wp
                    
                elif event.type == KEYUP:
                    # movement
                    if event.key == K_UP:
                        self.setKey("accel", 0)
                    elif event.key == K_DOWN:
                        self.setKey("brake", 0)
                    elif event.key == K_LEFT:
                        self.setKey("turnLeft", 0)
                    elif event.key == K_RIGHT:
                        self.setKey("turnRight", 0)
                    elif event.key == K_SPACE:
                        self.setKey("fire",0)
                
                elif event.type == pygame.ACTIVEEVENT:
                    if event.state == STATE_LOSE_FOCUS:
                        if self.gameState == self.GAMESTATE_RUNNING:
                            self.pause_game()
                        
                
                '''elif event.type == MOUSEBUTTONDOWN:
                    if event.button == 1:
                        self.setKey("fire", 1)
                    print event.button
                
                elif event.type == MOUSEBUTTONUP:
                    if event.button == 1:
                        self.setKey("fire", 0)'''
                
            # clear the background (blit a blank screen) then draw everything in the background then the sprite groups then the foreground group
            self.screen.blit(self.background, (0,0))
            
            # game loop
            self.gameLoop()
            if self.gameState == self.GAMESTATE_NONE:
                #drawSurf = pygame.transform.scale(self.menuBackground, self.screen.get_size())
                self.screen.blit(self.menuBackground, ((self.screen.get_width() - self.menuBackground.get_width()) * 0.5, (self.screen.get_height() - self.menuBackground.get_height()) * 0.5))
            if self.menuManager.is_active(): self.menuManager.draw()
            pygame.display.flip()
        
        return
    
    def pause_game(self):
        self.gameState = self.GAMESTATE_PAUSED
        self.menuManager.pause_menu_click()
        
    def unpause_game(self):
        self.gameState = self.GAMESTATE_RUNNING
        self.menuManager.close()
        
    def quit_mission(self):
        self.gameState = self.GAMESTATE_GAMEOVER
        self.menuManager.main_menu_click()
    
    def setKey(self, key, val): self.keys[key] = val
        
        
    def showSplash(self):
        self.screen.blit(self.background,  (0, 0))
        splashImage,  splashRect = Utils.load_image("splash.png")
        centerScreen = (self.screen.get_size()[0] * 0.5,  self.screen.get_size()[1] * 0.5)
        self.screen.blit(splashImage,  (centerScreen[0] - splashRect.width * 0.5, centerScreen[1] - splashRect.height * 0.5))
        pygame.display.flip()
        
        
        return
        
    def removeSplash(self):
        self.screen.blit(self.background,  (0, 0))
        pygame.display.flip()
        
        return
    
    def loadMissionList(self):
        return MissionListXMLParser().loadMissionList()
    
    def loadMission(self, filename):
    
        return MissionXMLParser().loadMission(filename)
    
    def startMission(self, mission):
        if isinstance(mission, Mission):
            self.currentMission = mission
        else:
            self.currentMission = self.loadMission(mission[0])
        self.buildMission(self.currentMission)
        self.pause_game()
    
    def getPlayerSpawn(self):
        if 'ship' in self.currentProfile and int(self.currentProfile['ship']) >= 0 and int(self.currentProfile['ship']) < len(self.shipList):
            proto = self.shipList[int(self.currentProfile['ship'])]
        else:
            proto = self.shipList[0]
        return proto
    
    def buildMission(self, mission):
        self.elapsedTime = 0.0
        #add the trigger list
        self.triggerList = mission.triggerList[:]
        #self.rootSprite = pygame.sprite.OrderedUpdates()
        self.shipSpriteGroup = OrderedUpdatesRect()
        self.destroyedSpriteGroup = OrderedUpdatesRect()
        self.backgroundSpriteGroup = OrderedUpdatesRect() #pygame.sprite.OrderedUpdates()
        self.foregroundSpriteGroup = OrderedUpdatesRect() #pygame.sprite.OrderedUpdates()
        self.physics = Physics()
        self.messageList = []
        for key in self.keys: 
            self.setKey(key, 0)
        
        #convert spawns to player or enemy
        for spawn in mission.spawnList:
            
            if spawn.type == 'player': # this is the player ship
                tp = self.getPlayerSpawn()
                tempShip = PlayerShip(proto = tp, context = self)
                tempShip.team = spawn.team
                self.playerShip = tempShip
                self.linkTriggers(spawn, tempShip)
            else:
                if spawn.id >= 0 and spawn.id < len(self.shipList):
                    if self.shipList[spawn.id].hard_points:
                        tempShip = StationShip(spawn.x, spawn.y, proto = self.shipList[spawn.id], context = self)
                        for pt in self.shipList[spawn.id].hard_points:
                            hpt = AIShip(spawn.x + pt['x'], spawn.y + pt['y'], spawn.r + pt['rot'], proto = self.shipList[pt['id']], parent = tempShip, context = self)
                            hpt.team = tempShip.team
                            tempShip.hard_points.append(hpt)
                    else:
                        tempShip = AIShip(spawn.x, spawn.y, spawn.r, proto = self.shipList[spawn.id], context = self)
                    tempShip.team = spawn.team
                    
                    self.linkTriggers(spawn, tempShip)
                    
                    
                elif spawn.id == -1:
                    if spawn.hard_points:
                        tempShip = StationShip(spawn.x, spawn.y, spawn.r, proto = spawn.proto, context = self)
                    
                        for pt in spawn.hard_points:
                            if pt.id >= 0 and pt.id < len(self.shipList):
                                hpt = AIShip(spawn.x + pt.x, spawn.y + pt.y, spawn.r + pt.r, proto = self.shipList[pt.id], parent = tempShip, context = self)    
                                hpt.team = tempShip.team     
                                tempShip.hard_points.append(hpt)
                    else:
                        tempShip = AIShip(spawn.x, spawn.y, spawn.r, proto = spawn.proto, context = self)
                        
                    tempShip.team = spawn.team
                    self.linkTriggers(spawn, tempShip)
                    
            if spawn.squad:
                spawn.squad.append(tempShip)
                tempShip.squad = spawn.squad
            self.shipSpriteGroup.add(tempShip)
            self.foregroundSpriteGroup.add(tempShip.hard_points)
            self.physics.addChild(tempShip)
            tempShip.set_position(spawn.x, spawn.y)
            tempShip.set_rotation(spawn.r)
            tempShip.tag = spawn.tag
            tempShip.spawn = spawn
            tempShip.apply_upgrade(spawn.upgrade)
            
        # first, set up any auto-backgrounds
        if mission.background_style == 'tiled':
            # set up a tiled background using background_file and width, height
            x = 0
            y = 0
            mission.background_image, dfrect = Utils.load_image(mission.background_file)
            
        
        #convert bglist to backgrounds
        for bg in mission.backgroundList:
            tempBg = pygame.sprite.Sprite()
            tempBg.image, tempBg.rect = Utils.load_image(bg.filename)
            tempBg.rect.topleft = (bg.x, bg.y)
            self.backgroundSpriteGroup.add(tempBg)
            
        self.updateTriggers()
    
    def endMission(self):
        
        self.gameState = self.GAMESTATE_GAMEOVER
        
        #self.menuManager.main_menu_click()
        
        # put together the results for the mission results menu
        destroyedSpawns = self.currentMission.get_losses(self.destroyedSpriteGroup)
        destroyedLabels = {'ally': {}, 'enemy': {}}
        
        for sp in destroyedSpawns:
            if sp.team == Ship.TEAM_DEFAULT_FRIENDLY:
                update = destroyedLabels['ally']
            else:
                update = destroyedLabels['enemy']
            
            if not sp.id in update.keys():
                # create a new entry
                lb = "Unknown"
                img = None
                if sp.id == -1 and sp.type == "player":
                    lb = self.shipList[int(self.currentProfile['ship'])].name
                    img = self.shipList[int(self.currentProfile['ship'])].image
                elif sp.id >= 0 and sp.id < len(self.shipList):
                    lb = self.shipList[sp.id].name
                    img = self.shipList[sp.id].image
                update[sp.id] = {'num': 1, 'label': lb, 'image': img}
            else:
                # update the existing entry
                update[sp.id]['num'] += 1
        
        results = {'win': self.updateTriggers(), 'labels': destroyedLabels, 'spawns': destroyedSpawns, 'ships': self.destroyedSpriteGroup}
        
        if self.currentMission.isCampaignMission:
            self.campaignMgr.mission_ended(results, self.currentMission)
        self.menuManager.mission_results_show(results, self.currentMission)
        return results['win']
        
    def linkTriggers(self, spawn, ship):
        for tg in self.triggerList:
            if tg.parent == spawn:
                tg.parent = ship
            
    def updateTriggers(self):
        # update triggers
        primObjComplete = True
        for tg in self.triggerList:
            tg.update(self)
            if not tg.completed and tg.type.count("objective-primary") > 0:
                primObjComplete = False
                
        
                
        return primObjComplete
    
    def gameLoop(self):
        dt = self.clock.tick(consts.FRAMERATE)
        self.timeTotal += dt
        
        # display the FPS
        if dt > 0: 
            self.fpstext = self.defaultfont.render("FPS: " + str(float(int(10000.0 / dt)) / 10), 1, (0, 250, 0))
            
        if self.gameState == self.GAMESTATE_RUNNING:
            # do physics
            if self.lastTick == 0: self.lastTick = pygame.time.get_ticks()
            #if pygame.time.get_ticks() - self.lastTick > 33:
            #    self.physics.updatePhysics(self)
            #    self.lastTick = pygame.time.get_ticks()
            timestep = float(dt) * consts.GAMESPEED * 0.001
            
            self.elapsedTime += dt
            
            self.physics.updatePhysics(self, timestep)
            
            vel = Vec2(0,0)
            vel.setXY(*self.playerShip.velocity)
            #print "Ship: %f / Vel: %f (%f, %f) / timestep: %f" % (self.playerShip.get_rotation(), vel.theta, self.playerShip.velocity[0], self.playerShip.velocity[1], timestep)
                
            # update all sprites
            for sprite in self.backgroundSpriteGroup:
                sprite.update(self)
            
            for sprite in self.shipSpriteGroup:
                sprite.update(self, timestep)
        
            for sprite in self.foregroundSpriteGroup:
                sprite.update(self, timestep)

            if self.updateTriggers():
                # player completed all primary objectives - mission should end with a victory status now
                self.endMission()
            else:
                failed = False
                for tg in self.triggerList:
                    if not tg.completed and tg.type.count("objective-primary") > 0 and tg.condition.count("survive") > 0:
                        failed = True
                if failed:
                    self.endMission()
                
            if not self.playerShip in self.shipSpriteGroup:
                # player ship died - game over :(
                #self.gameState = self.GAMESTATE_GAMEOVER
                #self.menuManager.main_menu_click()
                self.endMission()
            
            if self.gameState == self.GAMESTATE_GAMEOVER:
                # TODO the game is ending, save the profile stats
                if not 'shots-fired' in self.currentProfile:
                    self.currentProfile['shots-fired'] = 0
                self.currentProfile['shots-fired'] = int(self.currentProfile['shots-fired']) + int(self.playerShip.stats['shots-fired'])
                
                if not 'shots-hit' in self.currentProfile:
                    self.currentProfile['shots-hit'] = 0
                self.currentProfile['shots-hit'] = int(self.currentProfile['shots-hit']) + int(self.playerShip.stats['shots-hit'])
                
                if not 'damage-dealt' in self.currentProfile:
                    self.currentProfile['damage-dealt'] = 0
                self.currentProfile['damage-dealt'] = int(self.currentProfile['damage-dealt']) + int(self.playerShip.stats['damage-dealt'])
                
                if not 'damage-taken' in self.currentProfile:
                    self.currentProfile['damage-taken'] = 0
                self.currentProfile['damage-taken'] = int(self.currentProfile['damage-taken']) + int(self.playerShip.stats['damage-taken'])
                
                if not 'kills' in self.currentProfile:
                    self.currentProfile['kills'] = 0
                self.currentProfile['kills'] = int(self.currentProfile['kills']) + int(self.playerShip.stats['kills'])
                
                death = 0
                if not self.playerShip in self.shipSpriteGroup:
                    death = 1
                if not 'deaths' in self.currentProfile:
                    self.currentProfile['deaths'] = 0
                self.currentProfile['deaths'] = int(self.currentProfile['deaths']) + death
                
                self.saveProfiles()
        
        elif self.gameState == self.GAMESTATE_GAMEOVER:
            for sprite in self.foregroundSpriteGroup:
                if isinstance(sprite, Particle): sprite.update(self)
            
            self.updateTriggers()
                
        
        if self.gameState != self.GAMESTATE_NONE:       
            
            # use the given mission width/height and the backgrounds to determine the boundaries
            maxrect = Rect(0,0,self.currentMission.width,self.currentMission.height)
            for sprite in self.backgroundSpriteGroup: # backgrounds will define the boundaries
                if sprite.rect.left + sprite.rect.width > maxrect.width:
                    maxrect.width = sprite.rect.left + sprite.rect.width
                if sprite.rect.top + sprite.rect.height > maxrect.height:
                    maxrect.height = sprite.rect.top + sprite.rect.height
                
            # now render to the screen using the playerShip to decide on coords
            render = (-1 * self.playerShip.rect.center[0] + (self.screen.get_width() * 0.5), -1 * self.playerShip.rect.center[1] + (self.screen.get_height() * 0.5))
            if render[0] > 0: render = (0, render[1])
            if render[1] > 0: render = (render[0], 0)
            if render[0] < -1 * maxrect.width + self.screen.get_width(): render = (-1 * maxrect.width + self.screen.get_width(), render[1])
            if render[1] < -1 * maxrect.height + self.screen.get_height(): render = (render[0], -1 * maxrect.height + self.screen.get_height())
            
            # draw a tiled background if necessary
            if self.currentMission and self.currentMission.background_style == 'tiled' and self.currentMission.background_image:
                # we will always assume that 0,0 is the starting point for the tiling
                bgimg = self.currentMission.background_image
                # set the offset to start at the closest tiling position to the top/left of the current area
                offset = [-1 * render[0], -1 * render[1]]
                # set up parralax
                offset[0] -= (bgimg.get_width() - consts.PARALLAX * render[0] % bgimg.get_width())
                offset[1] -= (bgimg.get_height() - consts.PARALLAX * render[1] % bgimg.get_height())
                #offset[0] = int(offset[0] / bgimg.get_width()) * bgimg.get_width()
                #offset[1] = int(offset[1] / bgimg.get_height()) * bgimg.get_height()
                start = [offset[0], offset[1]]
                end = [-1 * render[0] + self.screen.get_width(), -1 * render[1] + self.screen.get_height()]
                # render the tiles until off the screen
                while offset[0] < end[0] and offset[1] < end[1]:
                    self.screen.blit(bgimg, (offset[0] + render[0], offset[1] + render[1]))
                    offset[0] += bgimg.get_width()
                    if offset[0] >= end[0]:
                        offset[0] = start[0]
                        offset[1] += bgimg.get_height()
                
            # now draw the sprites
            drawrect = pygame.rect.Rect(-1 * render[0], -1 * render[1], self.screen.get_width(), self.screen.get_height())
            self.backgroundSpriteGroup.draw(self.screen, drawrect, render)
            self.shipSpriteGroup.draw(self.screen, drawrect, render)
            self.foregroundSpriteGroup.draw(self.screen, drawrect, render)
        
        
            # TODO display HUD things
            self.screen.blit(self.fpstext, (10,30))
            
            
                
                #if isinstance(sprite, AIShip):
                #    rect = pygame.rect.Rect(0,0,10,10)
                #    rect.center = (sprite.waypoint[0] + render[0], sprite.waypoint[1] + render[1])
                #    pygame.gfxdraw.box(self.screen, rect, (0, 0, 250))
                                                        
        
            self.HUD.draw(self.screen, self, render)
                
            
            #if self.gameState == self.GAMESTATE_GAMEOVER:
            #    if self.updateTriggers():
            #        text_surf = self.largefont.render("MISSION COMPLETE", 1, (0, 255, 0))
            #        self.screen.blit( text_surf, (self.screen.get_width() * 0.5 - text_surf.get_width() * 0.5, 100))
            #    else:
            #        text_surf = self.largefont.render("MISSION FAILED", 1, (255, 0, 0))
            #        self.screen.blit( text_surf, (self.screen.get_width() * 0.5 - text_surf.get_width() * 0.5, 100))
            
        return True
    
    def createDisplay(self):
        '''creates a display from the current profile settings'''
        try:
            if 'width' in self.currentProfile and int(self.currentProfile['width']) >= MIN_WINDOW_WIDTH:
                self.currentProfile['width'] = int(self.currentProfile['width'])
            else:
                self.currentProfile['width'] = MIN_WINDOW_WIDTH
            
            if 'height' in self.currentProfile and int(self.currentProfile['height']) >= MIN_WINDOW_HEIGHT:
                self.currentProfile['height'] = int(self.currentProfile['height'])
            else:
                self.currentProfile['height'] = MIN_WINDOW_HEIGHT
                
            if not 'fullscreen' in self.currentProfile:
                self.currentProfile['fullscreen'] = 0
            flags = 0
            if int(self.currentProfile['fullscreen']):
                flags = pygame.FULLSCREEN
            self.window = pygame.display.set_mode((self.currentProfile['width'],self.currentProfile['height']), flags)
        except pygame.error, msg:
            print "Error in profile video mode: %s" % msg
            self.window = pygame.display.set_mode((1024, 768))
예제 #47
0
 def __init__(self, size, gamemode):
     pygame.surface.Surface.__init__(self, size, pygame.SRCALPHA, 32)
     self.hud = HUD(self)
     self.hud.acquire_global_gamemode_hud(gamemode)
예제 #48
0
class HighwayPatrol:
    def __init__(self, asurface):

        self.crashed = False

        self.hud = HUD(asurface)

        self.status = GameStatus.PLAYING
        self.road = Road(asurface)

        self.surface = asurface
        self.surface_width = surface.get_width()
        self.surface_height = surface.get_height()

        self.car = Car(surface)
        self.obstacles = []
        self.adding_obstacle = False

    def start(self):
        clock = pygame.time.Clock()

        while not self.status == GameStatus.EXITING:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    HighwayPatrol.close()

                if event.type == pygame.MOUSEBUTTONUP:
                    self.car.toggle_lights()

            if pygame.key.get_pressed()[pygame.K_UP] != 0:
                self.car.increase_speed()
            elif pygame.key.get_pressed()[pygame.K_DOWN] != 0:
                self.car.reduce_speed()

            if pygame.key.get_pressed()[pygame.K_LEFT] != 0:
                self.car.turn_left()
                if self.car.rect.left <= 0:
                    self.car.rect.left = 1
            elif pygame.key.get_pressed()[pygame.K_RIGHT] != 0:
                self.car.turn_right()
                if self.car.rect.right >= self.surface_width:
                    self.car.rect.right = self.surface_width - 1

            if not self.crashed:
                self.road.scroll(self.car.speed)
                self.car.animate(surface)

                self.add_random_obstacle(surface)

                for obstacle in self.obstacles:
                    obstacle.animate(surface, self.car.speed)
                    collided = self.car.rect.colliderect(obstacle.rect)

                    if collided:
                        self.crashed = True
                        sounds.play_crash_sound()

                self.hud.display_car_speed(self.car.speed)
                self.hud.display_car_odometer(self.car.odometer)

            pygame.display.update()
            clock.tick(60)

    @classmethod
    def close(cls):
        pygame.quit()
        quit()

    def add_random_obstacle(self, surface: pygame.Surface):

        if self.visible_obstacles == 0 and not self.adding_obstacle:
            self.adding_obstacle = True
            self.add_obstacle(surface)

    @property
    def visible_obstacles(self):
        count = 0
        for obstacle in self.obstacles:
            if self.surface.get_rect().contains(obstacle.rect):
                count += 1
        if count > 0:
            self.adding_obstacle = False
        return count

    def add_obstacle(self, surface):
        self.adding_obstacle = True
        obstacle = Obstacle(surface, self.car.speed)
        self.obstacles.append(obstacle)
예제 #49
0
파일: vrc.py 프로젝트: indygfx/opticfoo
    def __init__(self):
        ShowBase.__init__(self)
#        self.base.enableParticles()

        # load operation map which holds state of operations
        self.operationmap = operationMap
        self.op = operationMap
        self.mode = self.op['mode']

        # sound analyzer
        self.snd = SoundAnalyzer()
        self.snd.start()


        # set up another camera to view stuff in other window
        self.disableMouse()
        props = WindowProperties()
        props.setSize(1600, 900)
        props.setUndecorated(True)
        props.setOrigin(0,0)
        self.otherWin = self.openWindow(props, makeCamera = 0)
        props = WindowProperties()
        props.setCursorHidden(True)
        self.win.requestProperties(props)
        self.win.setClearColor((0,0,0,1))
        self.otherWin.setClearColor((0,0,0,1))
        self.gridCard = CardMaker("grid")
        self.gridCard.setFrame(-10,10,-10,10)
        self.grid = self.render.attachNewNode(self.gridCard.generate())
        self.grid.setP(90)
        self.grid.setZ(-50)
        self.grid.setTwoSided(1)
        tex = self.loader.loadTexture("grid.png")
        self.grid.setTexture(tex)
        self.grid.setTransparency(TransparencyAttrib.MAlpha, 1)
        self.grid.setScale(100)
        self.grid.setAlphaScale(0.15)

        # mouse shit
        # Set the current viewing target
        self.heading = 180
        self.pitch = 0

        # allocate visuals
        self.visuals = {}
        self.factory = VisualFactory(
            loader,
            self.render,
            self.snd,
            [self.win, self.otherWin]
        )
        #self.activeVisual = visual(loader, self.render, self.snd)

        # refactor this
        self.activeVisual = self.factory.visuals['placeholder']
        self.visuals['placeholder'] = self.activeVisual
        self.otherCam = self.makeCamera(self.otherWin)
        self.camSpeed = 1.0
        self.cam.setPos(0,-100,0)
        self.camAfterMath()

        self.cam.node().setCameraMask(BitMask32.bit(0))
        self.otherCam.node().setCameraMask(BitMask32.bit(1))
        self.grid.hide(BitMask32.bit(1))

        self.hud = HUD(self)
        self.hudToggle = 1
        self.setFrameRateMeter(True)

        # movement keys
        self.accept('a', self.setOperation, ['a'])
        self.accept('a-up', self.setOperation, ['a-up'])
        self.accept('d', self.setOperation, ['d'])
        self.accept('d-up', self.setOperation, ['d-up'])
        self.accept('w', self.setOperation, ['w'])
        self.accept('w-up', self.setOperation, ['w-up'])
        self.accept('s', self.setOperation, ['s'])
        self.accept('s-up', self.setOperation, ['s-up'])
        self.accept('d', self.setOperation, ['d'])
        self.accept('d-up', self.setOperation, ['d-up'])
        self.accept('h', self.setOperation, ['h'])
        self.accept('h-up', self.setOperation, ['h-up'])
        self.accept('j', self.setOperation, ['j'])
        self.accept('j-up', self.setOperation, ['j-up'])
        self.accept('k', self.setOperation, ['k'])
        self.accept('k-up', self.setOperation, ['k-up'])
        self.accept('l', self.setOperation, ['l'])
        self.accept('l-up', self.setOperation, ['l-up'])
        self.accept('i', self.setOperation, ['i'])
        self.accept('i-up', self.setOperation, ['i-up'])
        self.accept('u', self.setOperation, ['u'])
        self.accept('u-up', self.setOperation, ['u-up'])
        self.accept('shift', self.setOperation, ['shift'])
        self.accept('shift-up', self.setOperation, ['shift-up'])
        self.accept('space', self.setOperation, ['space'])
        self.accept('space-up', self.setOperation, ['space-up'])
        self.accept('arrow_up', self.setOperation, ['arrow_up'])
        self.accept('arrow_up-up', self.setOperation, ['arrow_up-up'])
        self.accept('arrow_down', self.setOperation, ['arrow_down'])
        self.accept('arrow_down-up', self.setOperation, ['arrow_down-up'])
        self.accept('arrow_left', self.setOperation, ['arrow_left'])
        self.accept('arrow_left-up', self.setOperation, ['arrow_left-up'])
        self.accept('arrow_right', self.setOperation, ['arrow_right'])
        self.accept('arrow_right-up', self.setOperation, ['arrow_right-up'])
        self.accept('page_up', self.setOperation, ['page_up'])
        self.accept('page_up-up', self.setOperation, ['page_up-up'])
        self.accept('page_down', self.setOperation, ['page_down'])
        self.accept('page_down-up', self.setOperation, ['page_down-up'])
        self.accept('1', self.setOperation, ['1'])
        self.accept('1-up', self.setOperation, ['1-up'])
        self.accept('2', self.setOperation, ['2'])
        self.accept('2-up', self.setOperation, ['2-up'])
        self.accept('3', self.setOperation, ['3'])
        self.accept('3-up', self.setOperation, ['3-up'])
        self.accept('4', self.setOperation, ['4'])
        self.accept('4-up', self.setOperation, ['4-up'])
        self.accept('5', self.setOperation, ['5'])
        self.accept('5-up', self.setOperation, ['5-up'])
        self.accept('6', self.setOperation, ['6'])
        self.accept('6-up', self.setOperation, ['6-up'])
        self.accept('7', self.setOperation, ['7'])
        self.accept('7-up', self.setOperation, ['7-up'])
        self.accept('8', self.setOperation, ['8'])
        self.accept('8-up', self.setOperation, ['8-up'])
        self.accept('9', self.setOperation, ['9'])
        self.accept('9-up', self.setOperation, ['9-up'])
        self.accept('0', self.setOperation, ['0'])
        self.accept('0-up', self.setOperation, ['0-up'])

        # mode keys
        self.accept('escape', self.setOperation, ['escape'])
        self.accept('v', self.setOperation, ['v'])
        self.accept('c', self.setOperation, ['c'])
        self.accept('b', self.setOperation, ['b'])
        self.accept('n', self.setOperation, ['n'])

        # misc
        self.accept('r', self.setOperation, ['r'])
        self.accept('r-up', self.setOperation, ['r-up'])
        self.accept('f', self.setOperation, ['f'])
        self.accept('g', self.setOperation, ['g'])
        self.accept('t', self.setOperation, ['t'])
        self.accept('tab', self.setOperation, ['tab'])
        self.accept('wheel_up', self.setOperation, ['wheel-up'])
        self.accept('wheel_down', self.setOperation, ['wheel-down'])
        self.accept('mouse1', self.setOperation, ['mouse1'])
        self.accept('mouse1-up', self.setOperation, ['mouse1-up'])

        # effect keys
        self.accept('1', self.setOperation, ['1'])
        self.accept('1-up', self.setOperation, ['1-up'])
        self.accept('2', self.setOperation, ['2'])
        self.accept('2-up', self.setOperation, ['2-up'])
        self.accept('3', self.setOperation, ['3'])
        self.accept('3-up', self.setOperation, ['3-up'])
        self.accept('4', self.setOperation, ['4'])
        self.accept('4-up', self.setOperation, ['4-up'])
        self.accept('5', self.setOperation, ['5'])
        self.accept('5-up', self.setOperation, ['5-up'])
        self.accept('6', self.setOperation, ['6'])
        self.accept('6-up', self.setOperation, ['6-up'])
        self.accept('7', self.setOperation, ['7'])
        self.accept('7-up', self.setOperation, ['7-up'])
        self.accept('8', self.setOperation, ['8'])
        self.accept('8-up', self.setOperation, ['8-up'])
        self.accept('9', self.setOperation, ['9'])
        self.accept('9-up', self.setOperation, ['9-up'])
        self.accept('0', self.setOperation, ['0'])
        self.accept('0-up', self.setOperation, ['0-up'])
        self.accept('`', self.toggleHud)

        self.taskMgr.doMethodLater(0.3, self.displayOperationHud, 'operationHud')
        self.taskMgr.add(self.executeOperation, 'action', sort = 1, priority = 2)
        self.taskMgr.add(self.spreadTheBeat, 'sound', sort = 1, priority = 1)
        self.taskMgr.add(self.controlCamera, 'cam', sort = 1, priority = 1)

        # GUI
        #self.GUI = GUI(self)
        self.startTk()
예제 #50
0
class Game(object):

    modes = ['Waiting', 'In Play']

    def __init__(self, fps=60, fullscreen=False):
        """ (int, int, int, bool) -> Game
        Instantiate Game object with expected properties of a tower defense game. """
        pygame.init()
        
        # Parameter-based properties
        self.fps = fps
        self.fullscreen = fullscreen

        # Determine width and height
        self.screenW = pygame.display.list_modes()[0][0]
        self.screenH = pygame.display.list_modes()[0][1]
        if not self.fullscreen:
            self.screenW = floor(0.8 * self.screenW)
            self.screenH = floor(0.8 * self.screenH)

        # Display and framerate properties
        self.caption = GAME_NAME + ' - Left Mouse Button to select/place turret, drag by moving the mouse'
        self.displaySurf = None
        if self.fullscreen:
            self.flags = FULLSCREEN | DOUBLEBUF | HWACCEL
        else:
            self.flags = DOUBLEBUF | HWACCEL
        self.fpsClock = pygame.time.Clock()
        self.initializeDisplay()

        # Define and reset gameplay properties and objects
        self.money, self.wave, self.turrets, self.enemies, self.intersections, \
                    self.measuredFPS, self.tower, self.mode = [None] * 8
        self.reset()

        # HUD object 
        hudSize = 300
        hudRect = pygame.Rect(self.screenW - hudSize, 0, hudSize, self.screenH)
        hudColour = GREY
        self.hud = HUD(hudRect, hudColour, Turret(), FourShotTurret(), GlueTurret(),
                       FireTurret(), LongRange(), EightShotTurret())

        # Collision-related properties
        self.pathRects = []

        # Level appearance and elements
        self.intersectionSurface = pygame.Surface(self.displaySurf.get_size(), SRCALPHA | RLEACCEL, 32).convert_alpha()
        self.pathColour = ORANGE
        self.grassColour = LGREEN
        self.pathWidth = 50

        # Mouse and events
        self.mouseX, self.mouseY = 0, 0
        self.clicking = False
        self.dragging = False
        self.events = []

        # Health increment
        self.healthIncrement = 1

        # Menu object
        self.menu = Menu()

        # Background
        self.background = pygame.image.load(getDataFilepath(IMG_PATH_GRASS)).convert()
        self.pathImage = pygame.image.load(getDataFilepath(IMG_PATH_DIRT)).convert()

        # Sounds
        self.backgroundMusic = Sound(getDataFilepath('retro.wav'), True)
        self.hitSound = Sound(SOUND_PATH_SHOT, False)

        self.inPlay = True

    def reset(self, money=200, wave=1):
        """ ([int], [int]) -> None
        Reset money, wave number, and other similar game world properties. """
        self.money = money
        self.wave = wave
        self.turrets = []
        self.intersections = []
        self.enemies = []
        self.tower = Tower(IMG_PATH_TOWER, self.screenW / 2, self.screenH / 2)
        self.mode = self.modes[0]

    def incrementEnemyHealth(self, increment):
        for enemy in self.enemies:
            enemy.health *= increment

    def generateEnemies(self, x=1, separation=70):
        """ ([int], [int]) -> None
        Generate "x" number of enemies with the given separation for the tower defense game. """

        # Return immediately if there are no intersections loaded.
        if not self.intersections:
            print('WARNING: Enemies not loaded! Intersections must be loaded first.')
            return

        # Clear the list of enemies to start with.
        self.enemies = []

        # Gather information and create temporary variables.
        firstTurnX = self.intersections[0][0]
        firstTurnY = self.intersections[0][1]
        secondTurnX = self.intersections[1][0]
        secondTurnY = self.intersections[1][1]
        gap = x * separation
        xlist = []
        ylist = []
        direction = NODIR

        # Determine the starting direction and co-ordinate lists for the enemies.
        if firstTurnX == secondTurnX and firstTurnY > secondTurnY:
            xlist = [firstTurnX]
            ylist = xrange(firstTurnY, firstTurnY + gap, separation)
            direction = UP
        elif firstTurnX == secondTurnX:
            xlist = [firstTurnX]
            ylist = xrange(firstTurnY - gap, firstTurnY, separation)
            direction = DOWN
        elif firstTurnY == secondTurnY and firstTurnX > secondTurnX:
            xlist = xrange(firstTurnX, firstTurnX + gap, separation)
            ylist = [firstTurnY]
            direction = LEFT
        elif firstTurnY == secondTurnY:
            xlist = xrange(firstTurnX - gap, firstTurnX, separation)
            ylist = [firstTurnY]
            direction = RIGHT

        # Create enemies with the information determined above.
        w = Enemy(IMG_PATH_ENEMY1, 0, 0).w
        h = Enemy(IMG_PATH_ENEMY1, 0, 0).h
        assigned = False
        for x in xlist:
            for y in ylist:
                enemyType = random.randint(1, 5)
                if enemyType == 2 and not assigned:
                    self.enemies.append(Enemy(IMG_PATH_ENEMY2, x - w // 2, y - h // 2, direction, 3, 200))
                    assigned = True
                elif enemyType == 3 and not assigned and self.wave >= 2:
                    self.enemies.append(Enemy(IMG_PATH_ENEMY3, x - w // 2, y - h // 2, direction, 2, 300))
                    assigned = True
                elif enemyType == 4 and not assigned and self.wave >= 2:
                    self.enemies.append(Plane(IMG_PATH_ENEMY4, x - w // 2, y - h // 2, direction, 6, 100))
                    assigned = True
                elif enemyType == 5 and not assigned and self.wave >= 10:
                    self.enemies.append(HugeTank(IMG_PATH_ENEMY5, x - w // 2, y - h // 2, direction, 2, 500))
                    assigned = True
                else:
                    self.enemies.append(Enemy(IMG_PATH_ENEMY1, x - w // 2, y - h // 2, direction, health=100))
                    assigned = True
                self.enemies[-1].setNextIntersection(self.intersections[0])
                self.enemies[-1].initialDistanceFromWorld = distance((self.enemies[-1].x, self.enemies[-1].y),
                                                                     (firstTurnX, firstTurnY))
                assigned = False

        if self.wave % 5 == 0:
            self.healthIncrement += 1
        self.incrementEnemyHealth(self.healthIncrement)
        # Sort the list of enemies in terms of ascending distance away from the initial intersection.
        self.enemies.sort(key=lambda x: x.initialDistanceFromWorld)

    def makeStrSubstitutions(self, string):
        """ (str) -> str
        Return the input string but with human-readable keywords
        exchanged for co-ordinates and directions. """
        substitutions = {'RIGHT': RIGHT, 'LEFT': LEFT, 'UP': UP, 'DOWN': DOWN, 'WIDTH': self.hud.left,
                         'HEIGHT': self.screenH}
        result = string[:]
        for word in string.split():
            if word in substitutions:
                result = result.replace(word, str(substitutions[word]))
        return result

    def stretchIntersections(self):
        """ (None) -> None
        Stretch or compress intersection co-ordinates as necessary to fit them to screen. """
        # Return immediately if there are no intersections
        if not self.intersections:
            return
        # Gather info about the needed scaling for horizontal and vertical co-ordinates of each intersection
        temp = self.intersections[:]
        temp.sort(key=lambda x: x[0])
        horizontalStretch = (self.screenW - self.hud.width) / float(temp[-1][0] + self.pathWidth // 2)
        temp = self.intersections[:]
        temp.sort(key=lambda x: x[1])
        verticalStretch = self.screenH / float(temp[-1][1] + self.pathWidth)
        # Make it happen and leave the intersection direction intact
        for i in xrange(len(self.intersections)):
            self.intersections[i] = ceil(self.intersections[i][0] * horizontalStretch), \
                                    ceil(self.intersections[i][1] * verticalStretch), self.intersections[i][2]
        self.tower.x *= horizontalStretch
        self.tower.y *= verticalStretch

    def loadIntersections(self, filename):
        """ (None) -> tuple
        Load the saved intersections from file based on the current wave.
        Return the loaded intersection 3-tuples. """
        self.intersections = []
        data = open(getDataFilepath(filename), 'r')
        for line in data:
            intersection = self.makeStrSubstitutions(line).split()
            intersection = int(intersection[0]), int(intersection[1]), int(intersection[2])
            self.intersections.append(intersection)
        self.stretchIntersections()
        return self.intersections

    def loadTowerLoc(self, filename):
        """ (None) -> None
        Load the co-ordinates of the tower to defend. """
        data = open(getDataFilepath(filename), 'r').read().split()
        x = int(self.makeStrSubstitutions(data[-3]))
        y = int(self.makeStrSubstitutions(data[-2]))
        self.tower.x, self.tower.y = x - self.tower.w // 2, y - self.tower.h // 2
        newRect = self.tower.getRect().clamp(pygame.Rect(0, 0, self.screenW - self.hud.width, self.screenH))
        self.tower.x = newRect.x
        self.tower.y = newRect.y

    def incrementWave(self):
        """ (None) -> None
        Set up the level for the next wave. """
        self.wave += 1
        self.generateEnemies(4 * self.wave)
        for turret in self.turrets:
            turret.bullets = []
            turret.angle = 0

    def drawText(self, text, x=0, y=0):
        """ (str, [int], [int]) -> None
        Draw the given string such that the text matches up with the given top-left co-ordinates.
        Acts as a wrapper for the HUD drawText(). """
        self.hud.drawText(self.displaySurf, text=text, left=x, top=y)

    def handleAI(self):
        """ (None) -> None
        Force the enemies to turn at each intersection. """
        if not self.enemies or not self.intersections:
            return
        for enemy in self.enemies:
            nextTurn = enemy.getNextIntersection()            
            if not enemy.getReducedRect().collidepoint(nextTurn[0:2]):
                continue
            if nextTurn[-1] == LEFT: enemy.startMovingLeft()   
            elif nextTurn[-1] == RIGHT: enemy.startMovingRight()
            elif nextTurn[-1] == UP: enemy.startMovingUp()
            elif nextTurn[-1] == DOWN: enemy.startMovingDown()
            else: enemy.stop()
            intersectionIndex = self.intersections.index(nextTurn)  
            if intersectionIndex + 1 < len(self.intersections):  
                enemy.setNextIntersection(self.intersections[intersectionIndex + 1])
                
    def drawIntersections(self, surface):
        """ (Surface) -> None
        Draw a sequence of paths joining all of the intersections onto the given surface.
        Update the list of path Rect objects for collision detection. """
        if not self.intersections:
            return
        points, intersectionRects, joinRects, result = [], [], [], []
        half = floor(self.pathWidth / 2.0)
        for intersection in self.intersections:
            points.append((intersection[0], intersection[1]))
        for point in points:
            intersectionRects.append(pygame.Rect(point[0] - half, point[1] - half, 2 * half, 2 * half))
        for i in xrange(len(points) - 1):
            result.append(intersectionRects[i].union(intersectionRects[i + 1]))
            surface.blit(self.pathImage, (result[-1].x, result[-1].y), result[-1])
        self.pathRects = result

    def onPath(self, other):
        """ (int, int) -> bool
        Return True if the x and y co-ordinates represent a spot on the paths, False otherwise. """
        result = False
        if not self.pathRects:
            return result
        for rect in self.pathRects:
            if (isinstance(other, tuple) and rect.collidepoint(other)) or rect.colliderect(other):
                result = True
        return result

    def onGrass(self, other):
        """ (int, int) -> bool
        Return True if the x and y co-ordinates represent a spot on the grass, False otherwise. """
        return not self.onPath(other)

    def hoveringSidebar(self):
        """ (None) -> bool
        Return True if the mouse is hovering over the HUD sidebar, False otherwise. """
        return self.mouseX >= self.hud.left
        
    def initializeDisplay(self):
        """ (None) -> Surface
        Initialize the display Surface and update the caption and display settings. Only call once in __init__. """
        self.displaySurf = pygame.display.set_mode((self.screenW, self.screenH), self.flags)
        pygame.display.set_caption(self.caption)
        return self.displaySurf

    def redrawAndProceedTick(self):
        """ (None) -> None
        Redraw the screen, and delay to enforce the FPS. Call on every update. """
        pygame.display.flip()
        self.fpsClock.tick_busy_loop(self.fps)
        self.measuredFPS = self.fpsClock.get_fps()

    def terminate(self):
        """ (None) -> None
        Set the game to exit as soon as possible. """
        print('Game closing...')
        self.inPlay = False

    def handleQuitEvents(self, events):
        """ (list-of-Events) -> None
        Exit the game if Escape is pressed or if the close button is used. """
        for event in events:
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                self.terminate()

    def updateState(self):
        """ (None) -> None
        Update the state of the game based on the user selection on the sidebar. """
        if self.hud.shouldPause():
            self.backgroundMusic.pause()
            if self.menu.drawPauseMenu(self.displaySurf):
                self.__init__(self.fps, self.fullscreen)
                self.execute()
            self.menu.drawPauseMenu(self.displaySurf)
            self.backgroundMusic.play(-1)
        if self.hud.shouldStart():
            self.mode = self.modes[1]
        self.canRun()

    def updateEnemies(self):
        """ (None) -> None
        Update and draw all enemies and the central tower. """
        levelComplete = True
        for enemy in self.enemies:
            if self.mode == self.modes[0]:
                enemy.pause()
            elif self.mode == self.modes[1]:
                enemy.unpause()
            if enemy.alive():
                levelComplete = False
            enemy.update()

            self.tower.update(self.displaySurf, enemy)
            enemy.draw(self.displaySurf, enemy.x, enemy.y)
        if levelComplete and self.mode == self.modes[1]:
            self.mode = self.modes[0]
            self.incrementWave()

    def enemyIndex(self, enemy):
        try:
            return self.enemies.index(enemy)
        except IndexError:
            print('WARNING: Tried to access nonexistent enemy.')
            return 0

    @staticmethod
    def inRange(enemy, turret):
        """ (Enemy, Turret) -> None
        Return True if the enemy is in range of the given turret, False
        otherwise. """
        return distance(enemy.getRect().center, turret.getRect().center) < turret.range and enemy.active

    def setTarget(self, enemy, turret):
        """ (Enemy, Turret) -> None
        Lock onto a new enemy with the given turret. """
        if not isinstance(turret, FourShotTurret) and turret.canShoot:
            turret.angle = getAngle(deltaX(enemy.x, turret.x), deltaY(enemy.y, turret.y))
        turret.lockOn = True

    def provideReward(self, turret):
        """ (None, Turret) -> None
        Provide the player with a reward for each kill. """
        self.money += turret.reward

    def updateTurrets(self):
        """ (None) -> None
        Update and draw all turrets and bullets. """
        for turret in self.turrets:
            # Check if the turret is highlighted
            turret.highlighted = False
            if turret.getRect().collidepoint(self.mouseX, self.mouseY):
                turret.highlighted = True
                
            # Check for lock-on with enemies
            foundTarget = False
            for enemy in self.enemies:
                if self.inRange(enemy, turret):
                    self.setTarget(enemy, turret)
                    foundTarget = True
                    break
            if not foundTarget:
                turret.lockOn = False
                turret.bullets = []
                
            # Update and draw the turret
            turret.update(self.displaySurf)
            
            # Check for bullet collision with enemies
            for bullet in turret.bullets:
                for enemy in self.enemies:
                    bulletEnemyCollision = bullet.getRect().colliderect(enemy.getRect())
                    if bulletEnemyCollision and not isinstance(turret, FourShotTurret):
                        self.hitSound.play()
                        bullet.dispose()
                        turret.test = True
                        if not isinstance(turret, GlueTurret) or \
                                (isinstance(enemy, Plane) and not isinstance(turret, FireTurret)):
                            enemy.health -= bullet.damagePotential
                        else:
                            enemy.topSpeed *= bullet.slowFactor
                        enemy.dispose()
                        if enemy.health <= 0:
                            self.provideReward(turret)             
                    elif bulletEnemyCollision:
                        self.hitSound.play()
                        enemy.health -= bullet.damagePotential
                        enemy.dispose()
                        bullet.dispose()
                        if enemy.health <= 0:
                            self.provideReward(turret)

    def updateHud(self):
        """ (None) -> None
        Update and draw the HUD sidebar. """
        self.hud.update(self.tower.health, self.money, self.wave)
        self.hud.draw(self.displaySurf)

    def updateInputs(self):
        """ (None) -> None
        Get keyboard and mouse status and check for quit events. """
        self.mouseX, self.mouseY = pygame.mouse.get_pos()
        self.clicking = pygame.mouse.get_pressed()[0]
        self.events = pygame.event.get()
        self.handleQuitEvents(self.events)

    def addTurret(self, index):
        """ (int) -> None
        Add a turret with the given index to the list of turrets. """
        newTurret = copy.copy(self.hud.turrets[index])
        newTurret.x = DEFAULT_VALUE
        newTurret.y = DEFAULT_VALUE
        self.turrets.append(newTurret)

    def handleDragging(self):
        """ (None) -> None
        Facilitate dragging of turrets from the HUD sidebar to the game field. """
        overlapping = False
        index = self.hud.highlighted()
        clicked = False
        rects = [turret.getRect() for turret in self.turrets[0:-1]]
        if len(self.turrets) > 1:
            for rect in rects:
                if self.turrets[-1].getRect().colliderect(rect):
                    overlapping = True
        for event in self.events:
            if event.type == MOUSEBUTTONDOWN:
                clicked = True
        if self.dragging and clicked and self.onGrass(self.turrets[-1].getRect()) and not overlapping:
            self.dragging = False
            self.turrets[-1].canShoot = True
            self.money -= self.turrets[-1].price
        if index >= 0 and clicked and not self.dragging and self.money >= self.hud.turrets[index].price:
            self.dragging = True
            self.addTurret(index)
        if self.dragging and not clicked:
            self.turrets[-1].x = self.mouseX - self.turrets[-1].width // 2
            self.turrets[-1].y = self.mouseY - self.turrets[-1].height // 2
            self.turrets[-1].canShoot = False

    def update(self):
        """ (None) -> None
        Update the entire game state and draws all objects on the screen. """
        self.displaySurf.blit(self.background, ORIGIN)
        self.updateInputs()
        self.handleAI()
        self.updateEnemies()
        self.updateTurrets()
        self.updateHud()
        self.handleDragging()
        self.redrawAndProceedTick()
        self.updateState()

    def execute(self):
        """ (None) -> None
        Execute the Tower Defense game. """

        # Play background music and enter the title screen
        self.backgroundMusic.play(-1)
        self.menu.drawTitleMenu(self.displaySurf)
        filename = self.menu.drawSelectLevelScreen(self.displaySurf)

        # Load the first level properties
        self.loadTowerLoc(filename)
        self.loadIntersections(filename)
        self.generateEnemies(5)

        # Blit the tower and paths onto the background Surface
        self.drawIntersections(self.intersectionSurface)
        self.background.blit(self.intersectionSurface, ORIGIN)
        self.tower.draw(self.background)

        # Play!
        while self.inPlay:
            self.update()
        self.menu.drawLosePanel (self.displaySurf)
        self.menu.drawCredits(self.displaySurf)
        pygame.quit()

    def getRect(self):
        """ (None) -> Rect
        Return a pygame Rect object defining the display surface boundaries. """
        return self.displaySurf.get_rect()

    def canRun (self):
        if self.tower.health <= 0:
            self.terminate ()
예제 #51
0
class Game(State):
    def __init__(self):
        #blam, initiate that parent class
        State.__init__(self)
        self.kill_prev = True
        self.screen.fill((0,0,0))
        self.show_debug = False
        self.canvas = pygame.image.load('img/blankcanvas.png').convert()
        self.canvas = pygame.transform.scale(self.canvas, self.screen.get_size())
        self.canvas_pos = center(self.canvas.get_size(), self.screen.get_size())
        self.current_room = StartRoom()
        self.player = Player()
        self.player.set_position(self.current_room.player_pos_left)
        self.current_room.player = self.player
        self.heads_up_display = HUD(self.player)

# events loop, feeds the player.dir values to handle player
# animation, also handles the player jump and walk speed
    def check_events(self):
        p = self.player
        pg = pygame
        keypress = pg.KEYDOWN
        keyrelease = pg.KEYUP
        esc = pg.K_ESCAPE
        s_key = pg.K_s
        d_key = pg.K_d
        up_arrow = pg.K_UP
        left_arrow = pg.K_LEFT
        right_arrow = pg.K_RIGHT

        for e in pg.event.get():
            if e.type == pg.QUIT:
                self.close_game()
                sys.exit()
            elif e.type == keypress:
                if e.key == esc:
                    self.close_game()
                    sys.exit()
                if e.key == left_arrow:
                    p.walk_left()
                if e.key == right_arrow:
                    p.walk_right()
                if e.key == up_arrow:
                    p.jumpSound.play()
                    p.jump(-p.jump_speed)
                if e.key == s_key:
                    p.attack(False)

            elif e.type == keyrelease:
                if e.key == left_arrow and p.xvelocity < 0:
                    p.move_x(0)
                elif e.key == right_arrow and p.xvelocity > 0:
                    p.move_x(0)
                elif e.key == up_arrow and p.yvelocity < 0:
                    p.move_y(0)
                elif e.key == s_key:
                    p.attack(True)


    def check_collisions(self):
        for e in self.current_room.enemy_list:
            e.target = self.player
            if e.dead:
                pu = PickUp(e.rect.center)
                self.current_room.item_list.append(pu)
                self.current_room.enemy_list.remove(e)
        self.current_room.check_collisions()
        if self.current_room.goto_next:
            self.current_room = self.current_room.next_room()
            self.player.set_position(self.current_room.player_pos_left)
            self.current_room.player = self.player
        if self.current_room.goto_previous:
            self.current_room = self.current_room.previous_room()
            self.player.set_position(self.current_room.player_pos_right)
            self.current_room.player = self.player
        if self.player.dead:
            self.next = GameOver()
            self.quit()

    def update_screen(self):
        self.screen.blit(self.canvas, self.canvas_pos)
        self.current_room.update_screen()
        if self.show_debug:
            self.heads_up_display.show_debug()
        self.heads_up_display.update()

        pygame.display.update()
예제 #52
0
class CarlaDataCollector:
    """
        To be able to drive in this environment, either start start CARLA beforehand with:

        Synchronous:  $> ./CarlaUE4.sh Town07 -benchmark -fps=30
        Asynchronous: $> ./CarlaUE4.sh Town07

        Or pass argument -start_carla in the command-line.
        Note that ${CARLA_ROOT} needs to be set to CARLA's top-level directory
        in order for this option to work.
    """
    def __init__(self,
                 host="127.0.0.1",
                 port=2000,
                 viewer_res=(1280, 720),
                 obs_res=(1280, 720),
                 num_images_to_save=10000,
                 output_dir="images",
                 synchronous=True,
                 fps=30,
                 action_smoothing=0.9,
                 start_carla=True):
        """
            Initializes an environment that can be used to save camera/sensor data
            from driving around manually in CARLA.

            Connects to a running CARLA enviromment (tested on version 0.9.5) and
            spwans a lincoln mkz2017 passenger car with automatic transmission.

            host (string):
                IP address of the CARLA host
            port (short):
                Port used to connect to CARLA
            viewer_res (int, int):
                Resolution of the spectator camera (placed behind the vehicle by default)
                as a (width, height) tuple
            obs_res (int, int):
                Resolution of the observation camera (placed on the dashboard by default)
                as a (width, height) tuple
            num_images_to_save (int):
                Number of images to collect
            output_dir (str):
                Output directory to save the images to
            action_smoothing:
                Scalar used to smooth the incomming action signal.
                1.0 = max smoothing, 0.0 = no smoothing
            fps (int):
                FPS of the client. If fps <= 0 then use unbounded FPS.
                Note: Sensors will have a tick rate of fps when fps > 0, 
                otherwise they will tick as fast as possible.
            synchronous (bool):
                If True, run in synchronous mode (read the comment above for more info)
            start_carla (bool):
                Automatically start CALRA when True. Note that you need to
                set the environment variable ${CARLA_ROOT} to point to
                the CARLA root directory for this option to work.
        """

        # Start CARLA from CARLA_ROOT
        self.carla_process = None
        if start_carla:
            if "CARLA_ROOT" not in os.environ:
                raise Exception("${CARLA_ROOT} has not been set!")
            dist_dir = os.path.join(os.environ["CARLA_ROOT"], "Dist")
            if not os.path.isdir(dist_dir):
                raise Exception(
                    "Expected to find directory \"Dist\" under ${CARLA_ROOT}!")
            sub_dirs = [
                os.path.join(dist_dir, sub_dir)
                for sub_dir in os.listdir(dist_dir)
                if os.path.isdir(os.path.join(dist_dir, sub_dir))
            ]
            if len(sub_dirs) == 0:
                raise Exception(
                    "Could not find a packaged distribution of CALRA! " +
                    "(try building CARLA with the \"make package\" " +
                    "command in ${CARLA_ROOT})")
            sub_dir = sub_dirs[0]
            carla_path = os.path.join(sub_dir, "LinuxNoEditor", "CarlaUE4.sh")
            launch_command = [carla_path]
            launch_command += ["Town07"]
            if synchronous: launch_command += ["-benchmark"]
            launch_command += ["-fps=%i" % fps]
            print("Running command:")
            print(" ".join(launch_command))
            self.carla_process = subprocess.Popen(launch_command,
                                                  stdout=subprocess.PIPE,
                                                  universal_newlines=True)
            print("Waiting for CARLA to initialize")
            for line in self.carla_process.stdout:
                if "LogCarla: Number Of Vehicles" in line:
                    break
            time.sleep(2)

        # Initialize pygame for visualization
        pygame.init()
        pygame.font.init()
        width, height = viewer_res
        if obs_res is None:
            out_width, out_height = width, height
        else:
            out_width, out_height = obs_res
        self.display = pygame.display.set_mode(
            (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.clock = pygame.time.Clock()

        # Setup gym environment
        self.action_space = gym.spaces.Box(np.array([-1, 0]),
                                           np.array([1, 1]),
                                           dtype=np.float32)  # steer, throttle
        self.observation_space = gym.spaces.Box(low=0.0,
                                                high=1.0,
                                                shape=(*obs_res, 3),
                                                dtype=np.float32)
        self.fps = fps
        self.spawn_point = 1
        self.action_smoothing = action_smoothing

        self.done = False
        self.recording = False
        self.extra_info = []
        self.num_saved_observations = 0
        self.num_images_to_save = num_images_to_save
        self.observation = {key: None
                            for key in ["rgb", "segmentation"]
                            }  # Last received observations
        self.observation_buffer = {
            key: None
            for key in ["rgb", "segmentation"]
        }
        self.viewer_image = self.viewer_image_buffer = None  # Last received image to show in the viewer

        self.output_dir = output_dir
        os.makedirs(os.path.join(self.output_dir, "rgb"))
        os.makedirs(os.path.join(self.output_dir, "segmentation"))

        self.world = None
        try:
            # Connect to carla
            self.client = carla.Client(host, port)
            self.client.set_timeout(2.0)

            # Create world wrapper
            self.world = World(self.client)

            # Example: Synchronizing a camera with synchronous mode.
            settings = self.world.get_settings()
            settings.synchronous_mode = True
            self.world.apply_settings(settings)

            # Get spawn location
            lap_start_wp = self.world.map.get_waypoint(
                carla.Location(x=-180.0, y=110))
            spawn_transform = lap_start_wp.transform
            spawn_transform.location += carla.Location(z=1.0)

            # Create vehicle and attach camera to it
            self.vehicle = Vehicle(
                self.world,
                spawn_transform,
                on_collision_fn=lambda e: self._on_collision(e),
                on_invasion_fn=lambda e: self._on_invasion(e))

            # Create hud
            self.hud = HUD(width, height)
            self.hud.set_vehicle(self.vehicle)
            self.world.on_tick(self.hud.on_world_tick)

            # Create cameras
            self.dashcam_rgb = Camera(
                self.world,
                out_width,
                out_height,
                transform=camera_transforms["dashboard"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_observation_image("rgb", e))
            self.dashcam_seg = Camera(
                self.world,
                out_width,
                out_height,
                transform=camera_transforms["dashboard"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_observation_image(
                    "segmentation", e),
                camera_type="sensor.camera.semantic_segmentation"
            )  #, color_converter=carla.ColorConverter.CityScapesPalette)
            self.camera = Camera(
                self.world,
                width,
                height,
                transform=camera_transforms["spectator"],
                attach_to=self.vehicle,
                on_recv_image=lambda e: self._set_viewer_image(e))
        except Exception as e:
            self.close()
            raise e

        self.hud.notification("Press \"Enter\" to start collecting data.")

    def close(self):
        if self.carla_process:
            self.carla_process.terminate()
        pygame.quit()
        if self.world is not None:
            self.world.destroy()
        self.closed = True

    def save_observation(self):
        # Blit image from spectator camera
        self.display.blit(
            pygame.surfarray.make_surface(self.viewer_image.swapaxes(0, 1)),
            (0, 0))

        # Superimpose current observation into top-right corner
        for i, (_, obs) in enumerate(self.observation.items()):
            obs_h, obs_w = obs.shape[:2]
            view_h, view_w = self.viewer_image.shape[:2]
            pos = (view_w - obs_w - 10, obs_h * i + 10 * (i + 1))
            self.display.blit(
                pygame.surfarray.make_surface(obs.swapaxes(0, 1)), pos)

        # Save current observations
        if self.recording:
            for obs_type, obs in self.observation.items():
                img = Image.fromarray(obs)
                img.save(
                    os.path.join(self.output_dir, obs_type,
                                 "{}.png".format(self.num_saved_observations)))
            self.num_saved_observations += 1
            if self.num_saved_observations >= self.num_images_to_save:
                self.done = True

        # Render HUD
        self.extra_info.extend([
            "Images: %i/%i" %
            (self.num_saved_observations, self.num_images_to_save),
            "Progress: %.2f%%" %
            (self.num_saved_observations / self.num_images_to_save * 100.0)
        ])
        self.hud.render(self.display, extra_info=self.extra_info)
        self.extra_info = []  # Reset extra info list

        # Render to screen
        pygame.display.flip()

    def step(self, action):
        if self.is_done():
            raise Exception("Step called after CarlaDataCollector was done.")

        # Take action
        if action is not None:
            steer, throttle = [float(a) for a in action]
            #steer, throttle, brake = [float(a) for a in action]
            self.vehicle.control.steer = self.vehicle.control.steer * self.action_smoothing + steer * (
                1.0 - self.action_smoothing)
            self.vehicle.control.throttle = self.vehicle.control.throttle * self.action_smoothing + throttle * (
                1.0 - self.action_smoothing)
            #self.vehicle.control.brake = self.vehicle.control.brake * self.action_smoothing + brake * (1.0-self.action_smoothing)

        # Tick game
        self.clock.tick()
        self.hud.tick(self.world, self.clock)
        self.world.tick()
        try:
            self.world.wait_for_tick(seconds=0.5)
        except RuntimeError as e:
            pass  # Timeouts happen for some reason, however, they are fine to ignore

        # Get most recent observation and viewer image
        self.observation["rgb"] = self._get_observation("rgb")
        self.observation["segmentation"] = self._get_observation(
            "segmentation")
        self.viewer_image = self._get_viewer_image()

        pygame.event.pump()
        keys = pygame.key.get_pressed()
        if keys[K_ESCAPE]:
            self.done = True
        if keys[K_SPACE]:
            self.recording = True

    def is_done(self):
        return self.done

    def _get_observation(self, name):
        while self.observation_buffer[name] is None:
            pass
        obs = self.observation_buffer[name].copy()
        self.observation_buffer[name] = None
        return obs

    def _get_viewer_image(self):
        while self.viewer_image_buffer is None:
            pass
        image = self.viewer_image_buffer.copy()
        self.viewer_image_buffer = None
        return image

    def _on_collision(self, event):
        self.hud.notification("Collision with {}".format(
            get_actor_display_name(event.other_actor)))

    def _on_invasion(self, event):
        lane_types = set(x.type for x in event.crossed_lane_markings)
        text = ["%r" % str(x).split()[-1] for x in lane_types]
        self.hud.notification("Crossed line %s" % " and ".join(text))

    def _set_observation_image(self, name, image):
        self.observation_buffer[name] = image

    def _set_viewer_image(self, image):
        self.viewer_image_buffer = image
예제 #53
0
파일: vrc.py 프로젝트: indygfx/opticfoo
class VRC(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
#        self.base.enableParticles()

        # load operation map which holds state of operations
        self.operationmap = operationMap
        self.op = operationMap
        self.mode = self.op['mode']

        # sound analyzer
        self.snd = SoundAnalyzer()
        self.snd.start()


        # set up another camera to view stuff in other window
        self.disableMouse()
        props = WindowProperties()
        props.setSize(1600, 900)
        props.setUndecorated(True)
        props.setOrigin(0,0)
        self.otherWin = self.openWindow(props, makeCamera = 0)
        props = WindowProperties()
        props.setCursorHidden(True)
        self.win.requestProperties(props)
        self.win.setClearColor((0,0,0,1))
        self.otherWin.setClearColor((0,0,0,1))
        self.gridCard = CardMaker("grid")
        self.gridCard.setFrame(-10,10,-10,10)
        self.grid = self.render.attachNewNode(self.gridCard.generate())
        self.grid.setP(90)
        self.grid.setZ(-50)
        self.grid.setTwoSided(1)
        tex = self.loader.loadTexture("grid.png")
        self.grid.setTexture(tex)
        self.grid.setTransparency(TransparencyAttrib.MAlpha, 1)
        self.grid.setScale(100)
        self.grid.setAlphaScale(0.15)

        # mouse shit
        # Set the current viewing target
        self.heading = 180
        self.pitch = 0

        # allocate visuals
        self.visuals = {}
        self.factory = VisualFactory(
            loader,
            self.render,
            self.snd,
            [self.win, self.otherWin]
        )
        #self.activeVisual = visual(loader, self.render, self.snd)

        # refactor this
        self.activeVisual = self.factory.visuals['placeholder']
        self.visuals['placeholder'] = self.activeVisual
        self.otherCam = self.makeCamera(self.otherWin)
        self.camSpeed = 1.0
        self.cam.setPos(0,-100,0)
        self.camAfterMath()

        self.cam.node().setCameraMask(BitMask32.bit(0))
        self.otherCam.node().setCameraMask(BitMask32.bit(1))
        self.grid.hide(BitMask32.bit(1))

        self.hud = HUD(self)
        self.hudToggle = 1
        self.setFrameRateMeter(True)

        # movement keys
        self.accept('a', self.setOperation, ['a'])
        self.accept('a-up', self.setOperation, ['a-up'])
        self.accept('d', self.setOperation, ['d'])
        self.accept('d-up', self.setOperation, ['d-up'])
        self.accept('w', self.setOperation, ['w'])
        self.accept('w-up', self.setOperation, ['w-up'])
        self.accept('s', self.setOperation, ['s'])
        self.accept('s-up', self.setOperation, ['s-up'])
        self.accept('d', self.setOperation, ['d'])
        self.accept('d-up', self.setOperation, ['d-up'])
        self.accept('h', self.setOperation, ['h'])
        self.accept('h-up', self.setOperation, ['h-up'])
        self.accept('j', self.setOperation, ['j'])
        self.accept('j-up', self.setOperation, ['j-up'])
        self.accept('k', self.setOperation, ['k'])
        self.accept('k-up', self.setOperation, ['k-up'])
        self.accept('l', self.setOperation, ['l'])
        self.accept('l-up', self.setOperation, ['l-up'])
        self.accept('i', self.setOperation, ['i'])
        self.accept('i-up', self.setOperation, ['i-up'])
        self.accept('u', self.setOperation, ['u'])
        self.accept('u-up', self.setOperation, ['u-up'])
        self.accept('shift', self.setOperation, ['shift'])
        self.accept('shift-up', self.setOperation, ['shift-up'])
        self.accept('space', self.setOperation, ['space'])
        self.accept('space-up', self.setOperation, ['space-up'])
        self.accept('arrow_up', self.setOperation, ['arrow_up'])
        self.accept('arrow_up-up', self.setOperation, ['arrow_up-up'])
        self.accept('arrow_down', self.setOperation, ['arrow_down'])
        self.accept('arrow_down-up', self.setOperation, ['arrow_down-up'])
        self.accept('arrow_left', self.setOperation, ['arrow_left'])
        self.accept('arrow_left-up', self.setOperation, ['arrow_left-up'])
        self.accept('arrow_right', self.setOperation, ['arrow_right'])
        self.accept('arrow_right-up', self.setOperation, ['arrow_right-up'])
        self.accept('page_up', self.setOperation, ['page_up'])
        self.accept('page_up-up', self.setOperation, ['page_up-up'])
        self.accept('page_down', self.setOperation, ['page_down'])
        self.accept('page_down-up', self.setOperation, ['page_down-up'])
        self.accept('1', self.setOperation, ['1'])
        self.accept('1-up', self.setOperation, ['1-up'])
        self.accept('2', self.setOperation, ['2'])
        self.accept('2-up', self.setOperation, ['2-up'])
        self.accept('3', self.setOperation, ['3'])
        self.accept('3-up', self.setOperation, ['3-up'])
        self.accept('4', self.setOperation, ['4'])
        self.accept('4-up', self.setOperation, ['4-up'])
        self.accept('5', self.setOperation, ['5'])
        self.accept('5-up', self.setOperation, ['5-up'])
        self.accept('6', self.setOperation, ['6'])
        self.accept('6-up', self.setOperation, ['6-up'])
        self.accept('7', self.setOperation, ['7'])
        self.accept('7-up', self.setOperation, ['7-up'])
        self.accept('8', self.setOperation, ['8'])
        self.accept('8-up', self.setOperation, ['8-up'])
        self.accept('9', self.setOperation, ['9'])
        self.accept('9-up', self.setOperation, ['9-up'])
        self.accept('0', self.setOperation, ['0'])
        self.accept('0-up', self.setOperation, ['0-up'])

        # mode keys
        self.accept('escape', self.setOperation, ['escape'])
        self.accept('v', self.setOperation, ['v'])
        self.accept('c', self.setOperation, ['c'])
        self.accept('b', self.setOperation, ['b'])
        self.accept('n', self.setOperation, ['n'])

        # misc
        self.accept('r', self.setOperation, ['r'])
        self.accept('r-up', self.setOperation, ['r-up'])
        self.accept('f', self.setOperation, ['f'])
        self.accept('g', self.setOperation, ['g'])
        self.accept('t', self.setOperation, ['t'])
        self.accept('tab', self.setOperation, ['tab'])
        self.accept('wheel_up', self.setOperation, ['wheel-up'])
        self.accept('wheel_down', self.setOperation, ['wheel-down'])
        self.accept('mouse1', self.setOperation, ['mouse1'])
        self.accept('mouse1-up', self.setOperation, ['mouse1-up'])

        # effect keys
        self.accept('1', self.setOperation, ['1'])
        self.accept('1-up', self.setOperation, ['1-up'])
        self.accept('2', self.setOperation, ['2'])
        self.accept('2-up', self.setOperation, ['2-up'])
        self.accept('3', self.setOperation, ['3'])
        self.accept('3-up', self.setOperation, ['3-up'])
        self.accept('4', self.setOperation, ['4'])
        self.accept('4-up', self.setOperation, ['4-up'])
        self.accept('5', self.setOperation, ['5'])
        self.accept('5-up', self.setOperation, ['5-up'])
        self.accept('6', self.setOperation, ['6'])
        self.accept('6-up', self.setOperation, ['6-up'])
        self.accept('7', self.setOperation, ['7'])
        self.accept('7-up', self.setOperation, ['7-up'])
        self.accept('8', self.setOperation, ['8'])
        self.accept('8-up', self.setOperation, ['8-up'])
        self.accept('9', self.setOperation, ['9'])
        self.accept('9-up', self.setOperation, ['9-up'])
        self.accept('0', self.setOperation, ['0'])
        self.accept('0-up', self.setOperation, ['0-up'])
        self.accept('`', self.toggleHud)

        self.taskMgr.doMethodLater(0.3, self.displayOperationHud, 'operationHud')
        self.taskMgr.add(self.executeOperation, 'action', sort = 1, priority = 2)
        self.taskMgr.add(self.spreadTheBeat, 'sound', sort = 1, priority = 1)
        self.taskMgr.add(self.controlCamera, 'cam', sort = 1, priority = 1)

        # GUI
        #self.GUI = GUI(self)
        self.startTk()

    #def destroy(self):
    #    self.snd.stop()

    def spreadTheBeat(self, task):
        map(lambda x: x.getBeat(), self.visuals.values())
        return task.cont

    def setSoundScale(self, task):
        self.activeVisual.scaleToBeat()
        return task.cont

    def displayOperationHud(self, task):
        self.hud.updateHUD()
        return task.again

    def toggleHud(self):
        self.hudToggle = -self.hudToggle
        if self.hudToggle < 0:
            self.taskMgr.remove('operationHud')
            self.hud.clear()
        else:
            self.taskMgr.doMethodLater(0.3, self.displayOperationHud, 'operationHud')

    def setOperation(self, key):
        if key == "v" : self.mode = 'visual'
        if key == "c" : self.mode = 'cam'
        if self.mode == "escaped" : self.setMode(key)
        if self.mode == "visual" : self.setVisualOperation(key)
        if self.mode == "cam" : self.setCamOperation(key)
        if self.mode == "light" : self.setLightOperation(key)
        if key == 'escape' : self.mode = 'escaped'

    def setMode(self, key):
        if key == "v" : self.mode = 'visual'
        if key == "c" : self.mode = 'cam'
        if key == "b" : self.mode = 'music'
        if key == "n" : self.mode = 'light'
        self.setOperationMap('mode', self.mode)

    def setCamOperation(self, key):
        if key == 'a' : self.setOperationMap('cam-left', 1)
        if key == 'a-up' : self.setOperationMap('cam-left', 0)
        if key == 'd' : self.setOperationMap('cam-right', 1)
        if key == 'd-up' : self.setOperationMap('cam-right', 0)
        if key == 'w' : self.setOperationMap('cam-forward', 1)
        if key == 'w-up' : self.setOperationMap('cam-forward', 0)
        if key == 's' : self.setOperationMap('cam-backward', 1)
        if key == 's-up' : self.setOperationMap('cam-backward', 0)
        if key == 'h' : self.setOperationMap('cam-rotate-left', 1)
        if key == 'h-up' : self.setOperationMap('cam-rotate-left', 0)
        if key == 'l' : self.setOperationMap('cam-rotate-right', 1)
        if key == 'l-up' : self.setOperationMap('cam-rotate-right', 0)
        if key == 'j' : self.setOperationMap('cam-rotate-down', 1)
        if key == 'j-up' : self.setOperationMap('cam-rotate-down', 0)
        if key == 'k' : self.setOperationMap('cam-rotate-up', 1)
        if key == 'k-up' : self.setOperationMap('cam-rotate-up', 0)
        if key == 'i' : self.setOperationMap('cam-roll-right', 1)
        if key == 'i-up' : self.setOperationMap('cam-roll-right', 0)
        if key == 'u' : self.setOperationMap('cam-roll-left', 1)
        if key == 'u-up' : self.setOperationMap('cam-roll-left', 0)
        if key == 'space' : self.setOperationMap('cam-up', 1)
        if key == 'space-up' : self.setOperationMap('cam-up', 0)
        if key == 'shift' : self.setOperationMap('cam-down', 1)
        if key == 'shift-up' : self.setOperationMap('cam-down', 0)
        if key == 'r' : self.setOperationMap('cam-reset', 1)
        if key == 'r-up': self.setOperationMap('cam-reset', 0)
        if key == 'f':
            self.setOperationMap('cam-sync-toggle', -self.op['cam-sync-toggle'])
            self.camAfterMath()
        if key == 'g':
            self.setOperationMap('cam-fix-toggle', -self.op['cam-fix-toggle'])
            self.camAfterMath()
        if key == 't':
            self.setOperationMap('cam-sync-to', -self.op['cam-sync-to'])
            self.camAfterMath()
        if key == "wheel-up" : self.increaseCamSpeed()
        if key == "wheel-down" : self.decreaseCamSpeed()
        if key == 'mouse1' :
            self.setOperationMap('cam-mouse-control', 1)
            self.win.movePointer(0, 100, 100)
        if key == 'mouse1-up' : self.setOperationMap('cam-mouse-control', 0)

    def setVisualOperation(self,key):
        if key == 'a' : self.setVisualOperationMap('visual-left', 1)
        if key == 'a-up' : self.setVisualOperationMap('visual-left', 0)
        if key == 'd' : self.setVisualOperationMap('visual-right', 1)
        if key == 'd-up' : self.setVisualOperationMap('visual-right', 0)
        if key == 'w' : self.setVisualOperationMap('visual-up', 1)
        if key == 'w-up' : self.setVisualOperationMap('visual-up', 0)
        if key == 's' : self.setVisualOperationMap('visual-down', 1)
        if key == 's-up' : self.setVisualOperationMap('visual-down', 0)
        if key == 'h' : self.setVisualOperationMap('visual-rotate-left', 1)
        if key == 'h-up' : self.setVisualOperationMap('visual-rotate-left', 0)
        if key == 'l' : self.setVisualOperationMap('visual-rotate-right', 1)
        if key == 'l-up' : self.setVisualOperationMap('visual-rotate-right', 0)
        if key == 'j' : self.setVisualOperationMap('visual-rotate-down', 1)
        if key == 'j-up' : self.setVisualOperationMap('visual-rotate-down', 0)
        if key == 'k' : self.setVisualOperationMap('visual-rotate-up', 1)
        if key == 'k-up' : self.setVisualOperationMap('visual-rotate-up', 0)
        if key == 'i' : self.setVisualOperationMap('visual-roll-right', 1)
        if key == 'i-up' : self.setVisualOperationMap('visual-roll-right', 0)
        if key == 'u' : self.setVisualOperationMap('visual-roll-left', 1)
        if key == 'u-up' : self.setVisualOperationMap('visual-roll-left', 0)
        if key == 'space' : self.setVisualOperationMap('visual-forward', 1)
        if key == 'space-up' : self.setVisualOperationMap('visual-forward', 0)
        if key == 'shift' : self.setVisualOperationMap('visual-backward', 1)
        if key == 'shift-up' : self.setVisualOperationMap('visual-backward', 0)
        if key == '1' : self.setVisualOperationMap('visual-effect1', 1)
        if key == '1-up' : self.setVisualOperationMap('visual-effect1', 0)
        if key == '2' : self.setVisualOperationMap('visual-effect2', 1)
        if key == '2-up' : self.setVisualOperationMap('visual-effect2', 0)
        if key == '3' : self.setVisualOperationMap('visual-effect3', 1)
        if key == '3-up' : self.setVisualOperationMap('visual-effect3', 0)
        if key == '4' : self.setVisualOperationMap('visual-effect4', 1)
        if key == '4-up' : self.setVisualOperationMap('visual-effect4', 0)
        if key == '5' : self.setVisualOperationMap('visual-effect5', 1)
        if key == '5-up' : self.setVisualOperationMap('visual-effect5', 0)
        if key == '6' : self.setVisualOperationMap('visual-effect6', 1)
        if key == '6-up' : self.setVisualOperationMap('visual-effect6', 0)
        if key == '7' : self.setVisualOperationMap('visual-effect7', 1)
        if key == '7-up' : self.setVisualOperationMap('visual-effect7', 0)
        if key == '8' : self.setVisualOperationMap('visual-effect8', 1)
        if key == '8-up' : self.setVisualOperationMap('visual-effect8', 0)
        if key == '9' : self.setVisualOperationMap('visual-effect9', 1)
        if key == '9-up' : self.setVisualOperationMap('visual-effect9', 0)
        if key == '0' : self.setVisualOperationMap('visual-effect0', 1)
        if key == '0-up' : self.setVisualOperationMap('visual-effect0', 0)
        if key == 'tab' : self.nextVisual()
        if key == 'wheel-up' : self.activeVisual.increaseValue()
        if key == 'wheel-down' : self.activeVisual.decreaseValue()
        if key == 'g': self.activeVisual.setMovementSpeedToggle()
        if key == 'f': self.activeVisual.setScaleToggle()
        if key == 't': self.activeVisual.setTransparencyToggle()
        if key == 'r': self.activeVisual.resetOperationMap()

    def setOperationMap(self, key, value):
        self.op[key] = value

    def setVisualOperationMap(self, key, value):
        if self.activeVisual != None:
            self.activeVisual.setOp(key, value)

    def executeOperation(self, task):
        # camera operations
        if self.op['cam-left'] == 1: self.moveCamLeft()
        if self.op['cam-right'] == 1: self.moveCamRight()
        if self.op['cam-up'] == 1: self.moveCamUp()
        if self.op['cam-down'] == 1: self.moveCamDown()
        if self.op['cam-forward'] == 1: self.moveCamForward()
        if self.op['cam-backward'] == 1: self.moveCamBackward()
        if self.op['cam-rotate-left'] == 1: self.rotateCamLeft()
        if self.op['cam-rotate-right'] == 1: self.rotateCamRight()
        if self.op['cam-rotate-up'] == 1: self.rotateCamUp()
        if self.op['cam-rotate-down'] == 1: self.rotateCamDown()
        if self.op['cam-roll-left'] == 1: self.rollCamLeft()
        if self.op['cam-roll-right'] == 1: self.rollCamRight()
        if self.op['cam-reset'] == 1: self.resetCam()

        # visual operations
        map(lambda x: x.update(), self.visuals.values())

        return task.cont

    def moveCamLeft(self):
        self.cam.setX(self.cam, -self.camSpeed)
        self.camAfterMath()

    def moveCamRight(self):
        self.cam.setX(self.cam, +self.camSpeed)
        self.camAfterMath()

    def moveCamUp(self):
        self.cam.setZ(self.cam, +self.camSpeed)
        self.camAfterMath()

    def moveCamDown(self):
        self.cam.setZ(self.cam, -self.camSpeed)
        self.camAfterMath()

    def moveCamForward(self):
        self.cam.setY(self.cam, +self.camSpeed)
        self.camAfterMath()

    def moveCamBackward(self):
        self.cam.setY(self.cam, -self.camSpeed)
        self.camAfterMath()

    def rotateCamLeft(self):
        self.cam.setH(self.cam, +self.camSpeed)
        self.camAfterMath()

    def rotateCamRight(self):
        self.cam.setH(self.cam, -self.camSpeed)
        self.camAfterMath()

    def rotateCamUp(self):
        self.cam.setP(self.cam, +self.camSpeed)
        self.camAfterMath()

    def rotateCamDown(self):
        self.cam.setP(self.cam, -self.camSpeed)
        self.camAfterMath()

    def rollCamLeft(self):
        self.cam.setR(self.cam, -self.camSpeed)
        self.camAfterMath()

    def rollCamRight(self):
        self.cam.setR(self.cam, +self.camSpeed)
        self.camAfterMath()

    def resetCam(self):
        pass

    def increaseCamSpeed(self):
        self.camSpeed = self.camSpeed + 0.1

    def decreaseCamSpeed(self):
        self.camSpeed = self.camSpeed - 0.1

    def camAfterMath(self):
        if self.op['cam-fix-toggle'] > 0:
            #self.cam.lookAt(self.activeVisual.path.getBounds().getCenter())
            if self.activeVisual != None:
                self.cam.lookAt(self.activeVisual.path)
        if self.op['cam-sync-toggle'] > 0:
            if self.op['cam-sync-to'] > 0:
                self.otherCam.setPos(self.cam.getPos())
                self.otherCam.setHpr(self.cam.getHpr())
            else:
                self.cam.setPos(self.otherCam.getPos())
                self.cam.setHpr(self.otherCam.getHpr())

    def controlCamera(self, task):
        # figure out how much the mouse has moved (in pixels)
        if self.op['cam-mouse-control'] == 1:
            md = self.win.getPointer(0)
            x = md.getX()
            y = md.getY()
            self.heading = self.cam.getH()
            self.pitch = self.cam.getP()
            if self.win.movePointer(0, 100, 100):
                self.heading = self.heading - (x - 100) * 0.1
                self.pitch = self.pitch - (y - 100) * 0.1
            self.cam.setHpr(self.heading,self.pitch, self.cam.getR())
            self.camAfterMath()
        return task.cont

    def setCamSpeed(self, value):
        self.camSpeed = value

    def displayInfo(self):
        self.hud.updateHUD()

    def nextVisual(self):
        active = self.activeVisual
        visuals = self.visuals.values()
        i = visuals.index(active)
        self.activeVisual = visuals[(i+1)%len(visuals)]
예제 #54
0
파일: game.py 프로젝트: ext/scfa
class Game(object):
    def __init__(self):
        self._running = False
        self.camera = Vector2f(0,5)

    def init(self, size, fullscreen=False):
        flags = OPENGL|DOUBLEBUF
        if fullscreen:
            flags |= FULLSCREEN

        pygame.display.set_mode(size.xy, flags)
        pygame.display.set_caption('Super Chainsaw Food Adventure')

        i = pygame.display.Info()
        self.size = Vector2i(i.current_w, i.current_h)

        glMatrixMode(GL_MODELVIEW)
        glEnable(GL_TEXTURE_2D)
        glDisable(GL_CULL_FACE)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)

        self.stage = 1
        self.projection = Matrix.perspective(75, self.size, 0.1, 100)
        self.ortho = Matrix.ortho(self.size)

        v = np.array([
                0,0,0, 0,0,
                1,0,0, 1,0,
                1,1,0, 1,1,
                0,1,0, 0,1,
                ], np.float32)
        i = np.array([0,1,2,3], np.uint32)
        self.quad = VBO(GL_QUADS, v, i)

        # parallax
        self.parallax_rep = 25
        v = np.array([
                0,0,0, 0,1,
                1,0,0, self.parallax_rep, 1,
                1,1,0, self.parallax_rep,0,
                0,1,0, 0,0,
                ], np.float32)
        i = np.array([0,1,2,3], np.uint32)
        self.repquad = VBO(GL_QUADS, v, i)
        self.parallax = Image('texture/sky.png', wrap=GL_REPEAT)
        self.parallax2 = Image('texture/sky2.png', wrap=GL_REPEAT)

        self.fbo = FBO(self.size, format=GL_RGB8, depth=True)

        self.shader = Shader('derp')
        self.passthru = Shader('passtru')
        self.herp = Shader('herp')

        self.map = Map('map.json')
        self.player = Player(Vector2f(55,-9))
        self.clock = pygame.time.Clock()
        self.hud = HUD(Vector2i(500,100))
        self.hpmeter = HUD(Vector2i(20, 500))
        self.font = self.hud.create_font(size=16)
        self.font2 = self.hud.create_font(size=12)

        self.land = pygame.mixer.Sound('data/sound/land.wav')
        self.ding = pygame.mixer.Sound('data/sound/ding.wav')
        self.eat = pygame.mixer.Sound('data/sound/eat.wav')
        self.wind = pygame.mixer.Sound('data/sound/wind.wav')

        self.wind.play(loops=-1)

        self.set_stage(1)
        self.killfade = None
        self.killfade2 = 1.0 # fade amount
        self.textbuf = []
        self.texttime = -10.0
        self.message('<b>Welcome adventurer!</b>\nYou can start exploring the world but beware of wandering away too far.')
        self.message('When outside of lights your <i>HP</i> will drain and you will get lost in the woods.')
        self.message('Eat food to temporary increase your <i>HP</i>.')
        self.message('Quest started: "Find the chainsaw".')
        self.message('Quest started: "Frobnicate something".')

        with self.hud:
            self.hud.clear((0,1,1,1))

    def running(self):
        return self._running

    @event(pygame.QUIT)
    def quit(self, event=None):
        self._running = False

    @event(pygame.KEYDOWN)
    def on_keypress(self, event):
        if event.key == 113 and event.mod & KMOD_CTRL: # ctrl+q
            return self.quit()
        if event.key == 27: # esc
            return self.quit()

        if event.key == 119:
            self.player.jump()

    @event(pygame.KEYUP)
    def on_keyrelease(self, event):
        if event.key == 119:
            self.player.unjump()

    def poll(self):
        global event_table
        for event in pygame.event.get():
            func = event_table.get(event.type, None)
            if func is None:
                continue
            func(self, event)

    def update(self):
        if self.killfade is not None:
            t = pygame.time.get_ticks() / 1000.0
            s = (t - self.killfade) / 2.5
            self.killfade2 = 1.0 - s

            if s > 1.0:
                self.quit()

            # so player keeps falling
            dt = 1.0 / self.clock.tick(60)
            self.player.vel.y = 0
            self.player.update(dt, self.map)

            return

        key = pygame.key.get_pressed()

        self.player.vel.x = 0
        if key[97 ]: self.player.vel.x = -0.15
        if key[100]: self.player.vel.x =  0.15

        if key[260]: self.camera.x -= 0.1
        if key[262]: self.camera.x += 0.1
        if key[258]: self.camera.y -= 0.1
        if key[264]: self.camera.y += 0.1

        dt = 1.0 / self.clock.tick(60)
        self.player.update(dt, self.map)
        self.player.frobnicate(self.map.pickups)
        self.map.update()

    def render(self):
        glClearColor(1,0,1,1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        with self.hpmeter as hud:
            hud.clear((0.3,0,0,1))
            hud.cr.identity_matrix()

            hud.rectangle(0,0, hud.width, hud.height * self.player.hp_ratio, (0,0.3,0,1))

            hud.cr.translate(18,0)
            hud.cr.rotate(math.pi*0.5)
            hud.text(' Energy: %d / %d' % (int(math.ceil(self.player.hp/10)) * 10, Player.max_hp), self.font2, color=(1,0.8,0,1))

        with self.hud:
            self.hud.clear((0,0,0,0))
            self.hud.cr.identity_matrix()

            t = pygame.time.get_ticks() / 1000.0
            s = (t - self.texttime) / 4.0

            if s > 1.0:
                if len(self.textbuf) > 0:
                    self.texttime = pygame.time.get_ticks() / 1000.0
                    self.text = self.textbuf.pop(0)
            else:
                a = min(1.0-s, 0.2) * 5
                self.hud.cr.translate(0,25)
                self.hud.text(self.text, self.font, color=(1,0.8,0,a), width=self.hud.width, alignment=ALIGN_CENTER)

        view = Matrix.lookat(
            self.player.pos.x, self.player.pos.y+7, 15,
            self.player.pos.x, self.player.pos.y+7, 0,
            0,1,0)

        with self.fbo as frame:
            frame.clear(0,0.03,0.15,1)

            Shader.upload_projection_view(self.projection, view)
            Shader.upload_player(self.player)
            self.shader.bind()

            # parallax background
            pm1 = Matrix.identity()
            pm1[3,0] = self.player.pos.x * 0.35 - 20
            pm1[3,1] = self.player.pos.y * 0.5 - 20
            pm1[0,0] = 42.0 * self.parallax_rep
            pm1[1,1] = 42.0
            self.parallax.texture_bind()
            Shader.upload_model(pm1)
            self.repquad.draw()

            Shader.upload_projection_view(self.projection, view)

            self.map.draw()

            # entities
            for obj in self.map.pickups:
                obj.draw(self.quad)
            self.player.draw()

            # parallax 2
            pm1 = Matrix.identity()
            pm1[3,0] = self.player.pos.x * -2.0 + 100
            pm1[3,1] = self.player.pos.y * 0.5 - 45 * 3 + 10
            pm1[0,0] = 45.0 * self.parallax_rep * 3
            pm1[1,1] = 45 * 3
            self.parallax2.texture_bind()
            Shader.upload_model(pm1)
            self.repquad.draw()

        mat = Matrix.identity()
        mat[0,0] = self.size.x
        mat[1,1] = self.size.y
        Shader.upload_projection_view(self.ortho, Matrix.identity())
        Shader.upload_model(mat)

        self.fbo.bind_texture()
        self.herp.bind()
        self.quad.draw()

        # messagebox
        mat = Matrix.identity()
        mat[3,0] = self.size.x / 2 - self.hud.width / 2
        mat[3,1] = self.size.y - self.hud.height
        Shader.upload_model(mat)
        self.hud.draw()

        # hpmeter
        mat = Matrix.identity()
        mat[3,1] = self.size.y / 2 - self.hpmeter.height / 2
        Shader.upload_model(mat)
        self.hpmeter.draw()

        Shader.unbind()

        pygame.display.flip()

    def run(self):
        self._running = True
        while self.running():
            self.poll()
            self.update()
            self.render()

    def message(self, text):
        self.textbuf.append(text)

    def set_stage(self, n):
        if n == 1:
            self.map.pickups.extend(self.map.obj1)
        elif n == 2:
            self.map.pickups.extend(self.map.obj2)
        elif n == 3:
            self.map.pickups.extend(self.map.obj3)

    def over(self):
        self.killfade = pygame.time.get_ticks() / 1000.0
예제 #55
0
파일: game.py 프로젝트: ext/scfa
    def init(self, size, fullscreen=False):
        flags = OPENGL|DOUBLEBUF
        if fullscreen:
            flags |= FULLSCREEN

        pygame.display.set_mode(size.xy, flags)
        pygame.display.set_caption('Super Chainsaw Food Adventure')

        i = pygame.display.Info()
        self.size = Vector2i(i.current_w, i.current_h)

        glMatrixMode(GL_MODELVIEW)
        glEnable(GL_TEXTURE_2D)
        glDisable(GL_CULL_FACE)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)

        self.stage = 1
        self.projection = Matrix.perspective(75, self.size, 0.1, 100)
        self.ortho = Matrix.ortho(self.size)

        v = np.array([
                0,0,0, 0,0,
                1,0,0, 1,0,
                1,1,0, 1,1,
                0,1,0, 0,1,
                ], np.float32)
        i = np.array([0,1,2,3], np.uint32)
        self.quad = VBO(GL_QUADS, v, i)

        # parallax
        self.parallax_rep = 25
        v = np.array([
                0,0,0, 0,1,
                1,0,0, self.parallax_rep, 1,
                1,1,0, self.parallax_rep,0,
                0,1,0, 0,0,
                ], np.float32)
        i = np.array([0,1,2,3], np.uint32)
        self.repquad = VBO(GL_QUADS, v, i)
        self.parallax = Image('texture/sky.png', wrap=GL_REPEAT)
        self.parallax2 = Image('texture/sky2.png', wrap=GL_REPEAT)

        self.fbo = FBO(self.size, format=GL_RGB8, depth=True)

        self.shader = Shader('derp')
        self.passthru = Shader('passtru')
        self.herp = Shader('herp')

        self.map = Map('map.json')
        self.player = Player(Vector2f(55,-9))
        self.clock = pygame.time.Clock()
        self.hud = HUD(Vector2i(500,100))
        self.hpmeter = HUD(Vector2i(20, 500))
        self.font = self.hud.create_font(size=16)
        self.font2 = self.hud.create_font(size=12)

        self.land = pygame.mixer.Sound('data/sound/land.wav')
        self.ding = pygame.mixer.Sound('data/sound/ding.wav')
        self.eat = pygame.mixer.Sound('data/sound/eat.wav')
        self.wind = pygame.mixer.Sound('data/sound/wind.wav')

        self.wind.play(loops=-1)

        self.set_stage(1)
        self.killfade = None
        self.killfade2 = 1.0 # fade amount
        self.textbuf = []
        self.texttime = -10.0
        self.message('<b>Welcome adventurer!</b>\nYou can start exploring the world but beware of wandering away too far.')
        self.message('When outside of lights your <i>HP</i> will drain and you will get lost in the woods.')
        self.message('Eat food to temporary increase your <i>HP</i>.')
        self.message('Quest started: "Find the chainsaw".')
        self.message('Quest started: "Frobnicate something".')

        with self.hud:
            self.hud.clear((0,1,1,1))