コード例 #1
0
ファイル: game.py プロジェクト: mehedi-shafi/SnakeGame-Python
 def newgame(self):
     self.player = Snake()
     self.food = None
     self.hud = HUD()
     self.spawnfood()
     self.state = STATE_PLAY
     pass
コード例 #2
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
コード例 #3
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)
コード例 #4
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)
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()
コード例 #6
0
ファイル: gamelogic.py プロジェクト: YannThorimbert/TheRule
    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
ファイル: game.py プロジェクト: joelfad/TankCommanderPanic
    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)
コード例 #8
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
コード例 #9
0
ファイル: world.py プロジェクト: bartn8/SistemiDigitaliM20-21
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()
コード例 #10
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
コード例 #11
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)
コード例 #12
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
コード例 #13
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)
コード例 #14
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
コード例 #15
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
コード例 #16
0
ファイル: carla_lap_env.py プロジェクト: pranavAL/Carla-ppo
    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,
                 action_smoothing=0.9,
                 fps=30,
                 synchronous=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)
        """

        # 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.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)

            if self.synchronous:
                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 = 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

        # Generate waypoints along the lap
        self.route_waypoints = compute_route_waypoints(
            self.world.map,
            lap_start_wp,
            lap_start_wp,
            resolution=1.0,
            plan=[RoadOption.STRAIGHT] + [RoadOption.RIGHT] * 2 +
            [RoadOption.STRAIGHT] * 5)
        self.current_waypoint_index = 0
        self.checkpoint_waypoint_index = 0

        # Reset env to set initial state
        self.reset()
コード例 #17
0
ファイル: main.py プロジェクト: aeaa1998/raycaster-game
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()
コード例 #18
0
ファイル: carla_route_env.py プロジェクト: xjwhy/Carla-ppo
    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()
コード例 #19
0
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

        # Hardware
        if args.hardware == '2':
            from smv2_drive import DriveController
            smdrive = DriveController("/dev/ttyUSB0", 1, False)

            ##### Register Callbacks #####
            # smdrive.logCallback = self._logCallback
            # smdrive.errorCallback = self._errorCallback
            # smdrive.readingCallback = self._readingCallback
            # smdrive.connectedCallback = self._connectedCallback

            # Connect and start
            smdrive.connect()

            print("WAITING TO CONNECT TO MOTOR......")
            time.sleep(1)
            # Expect Motor to be connected

            # # turn motor to home
            smdrive.setAddedConstantTorque(350)
            self._goToAngle(0, 1000)

            smdrive.setAddedConstantTorque(150)

            smdrive.setZero()

            time.sleep(1)

        # Keyboard controller set up
        if args.hardware == '1':
            controller = DualControl(world, start_in_autopilot=True)
        elif args.hardware == '0':
            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()
        learning_flag = False
        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()

            # Agent learning
            if world.agent_name == "Learning":
                if world.is_learning:
                    world.agent.collect()
                    learning_flag = True
                elif not world.is_learning and learning_flag:
                    world.agent.end_collect()
                    learning_flag = False

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

            if args.hardware == '2':
                angle = control.steer * 90

                # Move motor to "angle" degrees
                smdrive.setAbsoluteSetpoint(int((angle / 360) * 10000), 1000,
                                            3, 0.05)

            # 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()
コード例 #20
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",
                 action_smoothing=0.9,
                 fps=30):
        """
            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.
        """

        # 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.")
コード例 #21
0
ファイル: game.py プロジェクト: AkaiTobira/Zombie2D
 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)
コード例 #22
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.")
コード例 #23
0
ファイル: game.py プロジェクト: wezu/pyweek21
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.hide()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Plane
        #shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        #mesh = BulletTriangleMesh()
        #geomNodes = loader.loadModel('levels/test1/collision').findAllMatches('**/+GeomNode')
        #geomNode = geomNodes.getPath(0).node()
        #geom = geomNode.getGeom(0)
        #mesh.addGeom(geom)
        #shape = BulletTriangleMeshShape(mesh, dynamic=False, bvh=True )
        #np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
        #np.node().addShape(shape)
        #np.setPos(0, 0, 20.0)
        #np.setCollideMask(BitMask32.allOn())
        #self.world.attachRigidBody(np.node())

        #sky dome
        self.sun_sky = Sky()
        self.sun_sky.setTime(17.0)

        #terrain
        self.ground = Terrain(self.world, self.worldNP)
        self.ground.loadMesh(path + 'levels/gandg2/collision')
        self.ground.setMaps(path + 'levels/gandg2/')
        self.ground.setTextures((39, 1, 2, 15, 4, 5))

        #grass
        self.grass = Grass()
        self.grass.setMap(path + 'levels/gandg2/grass.png')
        self.grass_to_cut = self.grass.getStatus()
        # Car
        self.car = Car(self.world, self.worldNP)
        self.car.setPos(161.0, 160.0, 26)
        #camera
        self.camera = FlyingCamera()

        #car to character scale 0.0128
        self.char = Character(self.world, self.worldNP)
        self.char.enterCar()
        #self.char.setPos(256, 250, 80)

        #filter manager, post process
        self.filters = Postprocess()
        #self.filters.setupFxaa()
        #no time to make it work, sorry...
        self.filters.setupFilters()

        #map objects .. hardcoded because of time
        self.object_root = render.attachNewNode('object_root')
        obj = [(path + 'models/pyweek_wall1', 0.0, (303.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (301.0, 405.0,
                                                    25.0980434417725),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (299.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (297.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (295.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (293.0, 405.0,
                                                    25.0980434417725),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (291.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (289.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (287.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (285.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (283.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (281.0, 405.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (281.0, 385.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (283.0, 385.0,
                                                    25.0980453491211),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (285.0, 385.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 404.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 402.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 400.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 398.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 396.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 394.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (304.0, 392.0,
                                                     25.237850189209),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 404.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 398.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 396.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 394.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 392.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 390.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 388.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 386.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (286.0, 386.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (286.0, 388.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (286.0, 390.0,
                                                     25.0980434417725),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (287.0, 391.0,
                                                    25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (289.0, 391.0,
                                                    25.1190624237061),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (291.0, 391.0,
                                                    25.1960334777832),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (293.0, 391.0,
                                                    25.1596641540527),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (295.0, 391.0,
                                                    25.2697868347168),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (297.0, 391.0,
                                                    25.3282146453857),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (299.0, 391.0,
                                                    25.3496627807617),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (301.0, 391.0,
                                                    25.2688617706299),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 0.0, (303.0, 391.0,
                                                    25.2534332275391),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_wall1', 90.0, (280.0, 402.0,
                                                     25.0980415344238),
                path + 'models/pyweek_wall1_collision'),
               (path + 'models/pyweek_box', 0.0,
                (279.600006103516, 401.700012207031, 25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0,
                (279.399993896484, 402.200012207031, 25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0,
                (279.600006103516, 402.700012207031, 25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0,
                (279.399993896484, 403.399993896484, 25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0,
                (278.799987792969, 402.799987792969, 25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0,
                (278.799987792969, 402.100006103516, 25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0, (279.0, 401.5,
                                                  25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0, (278.5, 401.600006103516,
                                                  25.0980415344238), None),
               (path + 'models/pyweek_box', 0.0,
                (278.799987792969, 401.899993896484, 25.5980415344238), None),
               (path + 'models/pyweek_box', 90.0, (279.5, 402.600006103516,
                                                   25.5980415344238), None),
               (path + 'models/pyweek_box', 90.0, (279.0, 402.5,
                                                   25.5980415344238), None),
               (path + 'models/pyweek_box', 90.0, (279.399993896484, 402.0,
                                                   25.5980415344238), None),
               (path + 'models/pyweek_box', 90.0,
                (278.100006103516, 402.299987792969, 25.0980415344238), None),
               (path + 'models/pyweek_box', 90.0,
                (277.799987792969, 401.700012207031, 25.0980415344238), None),
               (path + 'models/pyweek_box', 90.0,
                (278.200012207031, 401.899993896484, 25.5980415344238), None),
               (path + 'models/pyweek_box', 90.0,
                (279.399993896484, 402.399993896484, 26.0980415344238), None),
               (path + 'models/pyweek_box', 90.0, (279.0, 401.899993896484,
                                                   26.0980415344238), None),
               (path + 'models/pyweek_box', 90.0,
                (278.799987792969, 402.399993896484, 26.0980415344238), None)]
        for i in obj:
            loadObject(model=i[0],
                       H=i[1],
                       pos=i[2],
                       world=self.world,
                       worldNP=self.worldNP,
                       root=self.object_root,
                       collision_solid=i[3])
        self.object_root.flattenStrong()

        #models/pyweek_gate,90.0,(280.0,399.0,25.0980415344238))

        #gui
        self.hud = HUD()

        #volume
        sfxMgr = base.sfxManagerList[0]
        sfxMgr.setVolume(cfg['sound-volume'] * 0.01)
        musicMgr = base.musicManager
        musicMgr.setVolume(cfg['music-volume'] * 0.01)

        #music
        self.driving_music = loader.loadMusic(path + 'music/driving.ogg')
        self.driving_music.setLoop(True)
        self.driving_music.play()
        self.walking_music = loader.loadMusic(path + 'music/walking.ogg')
        self.walking_music.setLoop(True)

        print self.char.actor.getScale(render)
コード例 #24
0
def main():
    """ Main Program """
    pygame.init()

    pygame.font.init()

    # Play shitty annoying music
    pygame.mixer.init()
    # pygame.mixer.music.load('res/music.mp3')
    pygame.mixer.music.load('res/kingkhan.mp3')
    pygame.mixer.music.set_volume(0.1)
    pygame.mixer.music.play(-1)

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    pygame.display.set_mode(size)

    screen = pygame.display.get_surface()

    flags = screen.get_flags()

    pygame.display.set_caption("Marcio")

    pygame.display.set_icon(pygame.image.load("res/code.png"))

    # Create the player
    player = Player()

    # Create all the levels
    level_list = []

    # TODO remove this in 'prod'
    #level_list.append(TestLevel(player))
    level_list.append(HetLevelVanOnsSpel(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 5 * 30
    player.rect.y = SCREEN_HEIGHT - 5 * 30
    active_sprite_list.add(player)

    hud = HUD(player)

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # Controls (misschien met een GUI?)
    # Volgens marc kan dat wel als we tijd over hebben, voor nu eerst de spellen afmaken.
    controls_left = [pygame.K_LEFT, pygame.K_a]
    controls_right = [pygame.K_RIGHT, pygame.K_d]
    controls_up = [pygame.K_UP, pygame.K_w, pygame.K_SPACE]
    controls_shoot = [pygame.K_LCTRL, pygame.K_RCTRL]

    menu = GameMenu(screen, ('PLAY', 'EXIT', 'RESTART'))
    menu.run()

    # Dialogs
    gg = Dialog()
    gg.set_text(['Game over!!', '', 'Press any key to quit'])
    gg.onkeydown = lambda dialog, event: exit(1)

    win = Dialog()
    win.set_text(['You won the game!!! :D', '', 'Press any key to quit'])
    win.onkeydown = lambda dialog, event: exit(1)

    not_done = Dialog()
    not_done.set_text([
        'You haven\'t collected all of', 'the code yet. Come back later.', '',
        'Press any key to continue'
    ])
    not_done.onkeydown = lambda dialog, event: dialog.close()

    timerfont = pygame.font.Font('res/Pixeled.ttf', 12)

    # -------- Main Program Loop ----------- #
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if event.type == pygame.KEYDOWN:
                if hud.show_controls:
                    # Haal begin dialog weg, met uitleg.
                    hud.show_controls = False

                if event.key == pygame.K_ESCAPE:
                    menu = GameMenu(screen, ('RESUME', 'EXIT', 'RESTART'))
                    menu.run()

                # Toggle fullscreen with F11
                if event.key == pygame.K_F11:
                    if flags & pygame.FULLSCREEN == False:
                        flags |= pygame.FULLSCREEN
                        pygame.display.set_mode(size, flags)
                    else:
                        flags ^= pygame.FULLSCREEN
                        pygame.display.set_mode(size, flags)

                if event.key in controls_left:
                    player.go_left()
                if event.key in controls_right:
                    player.go_right()
                if event.key in controls_up:
                    player.jump()
                if event.key in controls_shoot:
                    player.shoot()

            if event.type == pygame.KEYUP:
                if event.key in controls_left and player.change_x < 0:
                    player.stop()
                if event.key in controls_right and player.change_x > 0:
                    player.stop()

        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()

        # Keep the player in the center of the level
        if player.rect.centerx != SCREEN_CENTER:
            diff = SCREEN_CENTER - player.rect.centerx

            if current_level.world_shift < 0:
                player.rect.centerx = SCREEN_CENTER

            if current_level.world_shift + diff > 0:
                diff = -current_level.world_shift

            # De rechterkant van de map werkt dus niet lekker, maak de map maar
            # langer zodat je daar nooit kan komen, ez fix.

            if diff != 0:
                current_level.shift_world(diff)

        usenicefont = False

        if player.can_finish_level():
            usenicefont = True
            dialog = 'Picked up all objectives'
        else:
            if player.next_objective > 0:
                dialog = player.level.objective_list.snippets[
                    player.next_objective - 1]
            else:
                dialog = None

        if player.hits_end():

            if not player.can_finish_level():
                # usenicefont = True
                # dialog = 'Not done yet!'
                player.rect.x -= player.change_x
                player.change_x = 0
                not_done.show()

            else:
                # Increment the current level
                current_level_no += 1

                if current_level_no + 1 > len(level_list):
                    win.show()

                current_level = level_list[current_level_no]

                # Misschien moeten we hier ook die Bullets resetten..
                # maar fck dat want we hebben toch maar 1 level. deze code
                # wordt nooit uitgevoerd lol

                player.level = current_level

                player.lives = constants.LIVES

        # If the player hits lava,
        # he will lose one heart and get teleported to the start of the level
        if player.in_lava():
            # rip
            player.die() or gg.show()
            # TODO: vervang exit(1) door iets dat een dialog laat zien

        # TODO detect what block we just hit so we can show the code
        # TODO choose to accept the code by pressing `E`
        touching_objectives = player.get_touching_objectives()
        if len(touching_objectives) > 0:
            objective = touching_objectives[0]

            if player.next_objective != objective.index:
                # Verkeerd objective
                player.die() or gg.show()
                # TODO: vervang exit(1) door iets dat een dialog laat zien

            else:
                # Goed objective
                objective.kill()
                player.next_objective += 1

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)
        hud.draw(screen, dialog, usenicefont)

        timertext = timerfont.render("%.2f" % (pygame.time.get_ticks() / 1000),
                                     False, constants.WHITE)
        screen.blit(timertext, (constants.SCREEN_WIDTH - 75, 16))

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(constants.TPS)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
コード例 #25
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()
コード例 #26
0
ファイル: main.py プロジェクト: dbingema/FactorySpiel
# Haupt Programm

import pyglet.resource
from cocos.director import director
import cocos.scene

from defineLevel import DefineLevel
from hud import HUD
from gameLayer import GameLayer

if __name__ == '__main__':

    pyglet.resource.path.append('img')
    pyglet.resource.reindex()
    cocos.director.director.init(width=1280, height=960)

    levelInfo = DefineLevel()
    hud = HUD()

    game_layer = GameLayer(levelInfo, hud)
    background = game_layer.create_background()

    scene = cocos.scene.Scene(background, game_layer)

    director.run(scene)
コード例 #27
0
    class __impl:
        """This implementation hides the singleton interface\
        in an inner class and creates exactly one instance of\
        the inner class. The outer class is a handle to the inner\
        class and delegates any requests to it. While the id() of\
        the handle objects changes, the id() of the inner class which\
        implements the singleton behaviour is constant."""

        #------------------------------------------------------------------------------#
        #                                                                              #
        #                              Class  Attributes                               #
        #                                                                              #
        #------------------------------------------------------------------------------#

        #reference to our game singletons
        __game = GameController()
        __camera = Camera()
        __hud = HUD()

        #reference to game timers
        timers = {}

        #------------------------------------------------------------------------------#
        #                                  Accessors                                   #
        #------------------------------------------------------------------------------#

        #get the game controller instance
        def getGame(this):
            return this.__game

        #get the camera instance
        def getCamera(this):
            return this.__camera

        #get the hud instance
        def getHud(this):
            return this.__hud

#------------------------------------------------------------------------------#
#                                  Mutators                                    #
#------------------------------------------------------------------------------#

#no mutators in here

#------------------------------------------------------------------------------#
#                                                                              #
#                               Class  Methods                                 #
#                                                                              #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
#                               Initilization                                  #
#------------------------------------------------------------------------------#

#Initlize our single instance

        def __init__(this):
            #Ninja Game constructor methods
            this.initGame()
            this.runGame()

        #loads any pygame functions or objects before the user gets a chance to act
        def initGame(this):
            #initilize pygame's sound component
            #frequency, size, channels, buffersize
            pygame.mixer.pre_init(44100, 16, 2, 4096)
            #boot up pygame and print boot info
            message = pygame.init()
            print("Successes, Failures\n", message)
            #set the resolution of the game display
            this.getGame().setDisplay(
                pygame.display.set_mode(this.getGame().getResolution()))
            #set the name of the game
            pygame.display.set_caption(this.getGame().getGameName())
            this.getGame().setTimer(this, "quitTimer", 10)
            this.getGame().setTimer(this, "spaceTimer", 5)

#------------------------------------------------------------------------------#
#                              Game Processes                                  #
#------------------------------------------------------------------------------#

        def runGame(this):
            #the game loop to keep the game running
            while this.getGame().getGameRunning():
                #If we are in the menu
                if this.getGame().getAtMainMenu():
                    this.runMainMenu()
                #If we are in the options menu
                elif this.getGame().getAtOptionsMenu():
                    this.runOptionsMenu()
                #If we are in the game...
                elif this.getGame().getAtGame():
                    this.startGameplay()

            #if we manage to break out of the loop without quitting...
            #automatically call the quit method
            this.quitGame()

        #this is where the actual game gets played
        def startGameplay(this):
            pygame.mixer.music.load('sounds/music/level.wav')
            pygame.mixer.music.play(-1)
            #load the map and all of the objects
            this.loadMap()
            this.getHud().initGameHUD()
            #reset the game over flag so this does not repeat
            this.getGame().setGameOver(False)
            this.getGame().setVictory(False)
            this.getGame().setGameOverPlayed(False)

            #------------------ Game Loop Begin -------------------

            #setup the event timer so that the game does not freeze by itself
            #set the event ID to be Uservent + 1 (25)
            timer_event = pygame.USEREVENT + 1
            #set up the timer event to occur every set of miliseconds determined by the second argument
            pygame.time.set_timer(timer_event, 1)

            #while we are considered in the game
            while (this.getGame().getAtGame()):

                #------------ Event Processes ------------
                #check to see if the player has a game over and if has been played yet
                if this.getGame().getGameOver()\
                   and not this.getGame().getGameOverPlayed():
                    #use the game over method if this is the case
                    this.gameOver()

                #checks to see if the player is trying to use input and assigns the action
                #takes the pygame event argument that was created from the for loop
                command = this.processInput()

                #as long as the game isnt over...
                #player selects the new action and the player procces it
                if not this.getGame().getGameOver():
                    this.getGame().getPlayer().recieveCommand(command)
                else:
                    this.getGame().getPlayer().recieveCommand("idle")

                #AI selects the new action and the AI processes it
                this.checkAIStates(this.getGame().getNPCSprites())

                #check to see if all characters are in the middle of an action
                #finishes the action if the chracters are in the middle of one
                this.checkStates(this.getGame().getNPCSprites())
                this.checkStates(this.getGame().getPlayer())

                #add forces (including gravity) to all object lists, then the player
                this.addForces(this.getGame().getTerrainSprites())
                this.addForces(this.getGame().getItemSprites())
                this.addForces(this.getGame().getNPCSprites())
                this.addForces(this.getGame().getPlayer())

                #check to see if any triggers have been activated
                this.checkTriggers()

                #---------- Camera Update ----------------

                #check to see if the camera needs to move
                this.getCamera().checkMove()

                #update the position of all sprites according to how the camera is shifting
                this.getCamera().update(this.getGame().getTerrainSprites())
                this.getCamera().update(this.getGame().getItemSprites())
                this.getCamera().update(this.getGame().getNPCSprites())
                this.getCamera().update(this.getGame().getTriggerSprites())
                this.getCamera().update(this.getHud().getMovingHUDSprites())
                """
                #update the position of all sprite buffers
                this.getCamera().update(this.getGame().terrainSpriteBuffer)
                this.getCamera().update(this.getGame().itemSpriteBuffer)
                this.getCamera().update(this.getGame().NPCSpriteBuffer)
                this.getCamera().update(this.getGame().triggerSpriteBuffer)
                """

                this.getCamera().update(this.getGame().getPlayer())

                #----------- Graphics Rendering -----------

                #run the render graphics method
                this.renderGraphics()

                #----------- Graphics Update Process --------------

                #updates all sprites to their proper positions
                this.getGame().getTerrainSprites().update()
                this.getGame().getItemSprites().update()
                this.getGame().getNPCSprites().update()
                this.getGame().getTriggerSprites().update()
                this.getGame().getPlayer().update()
                this.getHud().getHUDSprites().update()

                #update the display outside of the update loop to reflect any changes
                pygame.display.update()
                """
                buffering methods to be added in at a later date
                #---------- Appearing and Vanishing ----------
                
                #a method that removes all sprites out of view
                this.vanish(this.getGame().getTerrainSprites())
                this.vanish(this.getGame().getItemSprites())
                this.vanish(this.getGame().getNPCSprites())
                this.vanish(this.getGame().getTriggerSprites())
                this.vanish(this.getHud().getMovingHUDSprites())

                this.appear(this.getGame().terrainSpriteBuffer)
                this.appear(this.getGame().itemSpriteBuffer)
                this.appear(this.getGame().NPCSpriteBuffer)
                this.appear(this.getGame().triggerSpriteBuffer)
                """
                #---------- Game Timers ----------------

                this.getGame().countdownTimers(this)

                #---------- Update Process ---------------

                #update frames per second outside fo the update loop and set the delta time to the variable
                this.getGame().deltaTime = (
                    this.getGame().clock.tick(this.getGame().gameFPS) / 4)

                #ensure the pygame event system is still working properly
                pygame.event.pump()

            #-------------------- Game Loop End ------------------------

        def loadMap(this):
            this.loadMapLayer('map1/', 'terrain.txt', "terrain")
            this.loadMapLayer('map1/', 'character.txt', "character")
            this.loadMapLayer('map1/', 'item.txt', "item")
            this.loadMapLayer('map1/', 'triggers.txt', "trigger")

        def loadMapLayer(this, mapPath, filename, objectType):
            path1 = 'maps/'
            filepath = path1 + mapPath + filename
            mapfile = open(filepath, 'r')
            idxX = 0
            idxY = 1

            #loop through the map file to find the dimmensions of the map
            with open(filepath, 'r') as mapfile:
                while True:
                    block = mapfile.read(1)
                    if not block:
                        break
                    elif block == '\n':
                        idxY += 1
                        idxX = 0
                    else:
                        idxX += 1
            mapfile.close()

            #reset the coordinate index values
            idxX = 0
            idxY = 0
            #loop through the map file to turn the character array into an objects array
            with open(filepath, 'r') as mapfile:
                while True:
                    block = mapfile.read(1)
                    if not block:
                        break
                    elif block == '\n':
                        idxY += 1
                        idxX = 0
                    else:
                        this.loadObject(block, objectType, idxX, idxY)
                        idxX += 1
            mapfile.close()

        def loadObject(this, block, objectType, idxX, idxY):
            blockScale = this.getGame().getBlockScale()
            tBuffer = this.getGame().terrainSpriteBuffer
            iBuffer = this.getGame().itemSpriteBuffer
            nBuffer = this.getGame().NPCSpriteBuffer

            if objectType == "terrain":
                #match the character with the object and add it to the map array
                if block == 'b':
                    tBuffer[str(idxX) + "," + str(idxY)] = Brick(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 'w':
                    tBuffer[str(idxX) + "," + str(idxY)] = Wall(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 's':
                    tBuffer[str(idxX) + "," + str(idxY)] = Sky(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 'd':
                    tBuffer[str(idxX) + "," + str(idxY)] = Door(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 'g':
                    tBuffer[str(idxX) + "," + str(idxY)] = Ground(
                        (idxX * blockScale), (idxY * blockScale))
            #if it is a character type object
            elif objectType == "character":
                #match the character with the object and add it to the map array
                if block == 'r':
                    nBuffer[str(idxX) + "," + str(idxY)] = Gaurd(
                        "Standing Gaurd", (idxX * blockScale),
                        (idxY * blockScale))
                elif block == 'p':
                    Player((idxX * blockScale), (idxY * blockScale))
            #if it is an item type object
            elif objectType == "item":
                pass
            #if it is a trigger type object
            elif objectType == "trigger":
                #match the character with the object and add it to the map array
                if block == 'm':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "howToMoveMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'a':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "howToAttackMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'e':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "enemyInfoMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'r':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "enemyBroadcastMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'v':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "victory", (idxX * blockScale), (idxY * blockScale),
                        blockScale, (blockScale * 2))
                elif block == 'c':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "clearMessages", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))

        def renderGraphics(this):
            """ The way this works, is that it builds the display
            in layers based on what comes first and the last thing
            that gets drawn is the sprite/shape on the bottom of the
            graphics rendering code block """

            #wipe the slate clean
            this.getGame().getDisplay().fill(this.getGame().getColor("black"))

            #add all sprites to the game display
            this.getGame().getTerrainSprites().draw(
                this.getGame().getDisplay())
            this.getGame().getItemSprites().draw(this.getGame().getDisplay())
            this.customDraw(this.getGame().getNPCSprites())
            this.customDraw(this.getGame().getPlayer())
            this.getHud().getHUDSprites().draw(this.getGame().getDisplay())

        #function for using the custome draw function for a sprite group
        def customDraw(this, sObject):
            #if the object instance is a single sprite
            if isinstance(sObject, pygame.sprite.Sprite):
                #use the custom-made draw function
                sObject.draw(this.getGame().getDisplay())

            #if the object instance is a sprite group
            if isinstance(sObject, pygame.sprite.Group):
                #loop through the sprite group
                for sprite in sObject:
                    #use the custom-made draw function
                    sprite.draw(this.getGame().getDisplay())

        """
        functions to be added in at a later date

        def vanish(this, spriteGroup):
            block = this.getGame().getBlockScale()
            vanishRect = pygame.Rect((0,0),(this.getGame().getResolution()))
            #expand the rect to account for the loading buffer
            vanishRect.inflate_ip(block * this.getGame().loadingBuffer,\
                                block * this.getGame().loadingBuffer)
            
            #loop through the sprite group
            for sprite in spriteGroup:
                #if the sprite is not within the load rect...
                if not vanishRect.contains(sprite.getRect()):
                    #remove the sprite
                    sprite.remove()

        def appear(this, spriteList):
            block = this.getGame().getBlockScale()
            vanishRect = pygame.Rect((0,0),(this.getGame().getResolution()))
            #expand the rect to account for the loading buffer
            loadRect = vanishRect.inflate(block * (this.getGame().loadingBuffer + 2),\
                                block * (this.getGame().loadingBuffer + 2))
            #expand the vanishing buffer
            vanishRect.inflate_ip(block * (this.getGame().loadingBuffer + 2),\
                                block * (this.getGame().loadingBuffer))

            #loop through each sprite in the sprite buffer
            for key, value in spriteList.items():
                #if the sprite is not within the vanish rect
                #but is within the load rect....
                if not vanishRect.contains(value.getRect())\
                   and loadRect.contains(value.getRect()):
                    #ensure the item gets added to the correct list
                    if isinstance(value, Block):
                        this.getGame().getTerrainSprites().add(value)
                    elif isinstance(value, Item):
                        this.getGame().getItemSprites().add(value)
                    elif isinstance(value, NPC):
                        this.getGame().getNPCSprites().add(value)                        
                    elif isinstance(value, Trigger):
                        this.getGame().getTriggerSprites().add(value)
        """

        def processInput(this):
            """Will go back and change jump to a MOD key to try to fix jumping issue"""

            #assign the reference to the game keys list
            keys = this.getGame().keys
            mods = pygame.key.get_mods()

            #keysPressed = this.getGame().noKeysPressed
            keysPressed = pygame.key.get_pressed()

            #reset all the keys that are pressed
            for idx in range(0, len(keys)):
                keys[idx] = False

            #if the keys that are pressed = the boolean tuple
            if keysPressed == this.getGame().wPressed:
                keys[0] = True
            elif keysPressed == this.getGame().sPressed:
                keys[1] = True
            elif keysPressed == this.getGame().aPressed:
                keys[2] = True
            elif keysPressed == this.getGame().dPressed:
                keys[3] = True
            elif keysPressed == this.getGame().upPressed:
                keys[4] = True
            elif keysPressed == this.getGame().downPressed:
                keys[5] = True
            elif keysPressed == this.getGame().leftPressed:
                keys[6] = True
            elif keysPressed == this.getGame().rightPressed:
                keys[7] = True
            elif keysPressed == this.getGame().spacePressed:
                keys[8] = True
            elif keysPressed == this.getGame().escPressed:
                keys[9] = True

            #if the mods are pressed = one number for a specific key
            if mods == this.getGame().rCtrlPressed:
                keys[10] = True

            #print(keysPressed)
            #print(keys)
            #print (mods)

            if keysPressed == this.getGame().noKeysPressed:
                return "idle"
            #return a command based on which keys are pressed
            if keys[8]:
                if this.getGame().checkTimer(this, "spaceTimer"):
                    #ensure we dont press the button twice
                    this.getGame().setTimer(this, "spaceTimer", 5)
                    return "jump"
            elif keys[9]:
                if this.getGame().checkTimer(this, "quitTimer"):
                    if not this.getGame().getAtMainMenu():
                        this.quitLevel()
                        #ensure we dont press the button twice
                        this.getGame().setTimer(this, "quitTimer", 10)
                    else:
                        return this.quitGame()
            elif keys[10]:
                return "attack"
            elif keys[0] or keys[4]:
                return "goUp"
            elif keys[1] or keys[5]:
                return "goDown"
            elif keys[2] or keys[6]:
                return "goLeft"
            elif keys[3] or keys[7]:
                return "goRight"

            #if no actions are being taken or no keys are being pressed... return idle
            return "idle"

        #function for using the check AI state function for a group of sprites
        def checkAIStates(this, sObject):
            #loop through the sprite group
            for sprite in sObject:
                #use the checkState function
                sprite.checkAIState()

        #function for using the check state function for a sprite or group
        def checkStates(this, sObject):
            #if the object instance is a single sprite
            if isinstance(sObject, pygame.sprite.Sprite):
                #use the checkState function
                sObject.checkState()

            #if the object instance is a sprite group
            if isinstance(sObject, pygame.sprite.Group):
                #loop through the sprite group
                for sprite in sObject:
                    #use the checkState function
                    sprite.checkState()

        #add gravity to an object array or just the player
        def addForces(this, sObject):

            #if the object instance is a single sprite
            if isinstance(sObject, pygame.sprite.Sprite):
                #add force to a single object
                this.addSingleForce(sObject)

            #if the object instance is a sprite group
            elif isinstance(sObject, pygame.sprite.Group):
                #loop through the sprite group
                for sprite in sObject:
                    #add force to a single object
                    this.addSingleForce(sprite)

        def addSingleForce(this, sObject):
            #if the object instance is a character or NPC sprite
            if isinstance(sObject, Character)\
               or isinstance(sObject, NPC):
                #have gravity affect the object if they are in the air
                if sObject.mass > 0:
                    sObject.addForce(0, (this.getGame().gravity / 2))

                #implement speed loss over time
                if sObject.getState("isIdle"):
                    if not sObject.speedX == 0:
                        if sObject.speedX > 0:
                            sObject.addForce(-this.getGame().speedLoss, 0)
                        elif sObject.speedX < 0:
                            sObject.addForce(this.getGame().speedLoss, 0)
                        #if there is less than 1 unit of force
                        if abs(sObject.speedX) < 1:
                            #set the speed to 0
                            sObject.speedX = 0

                # if the object is in the middle of moving left or right...
                if sObject.speedX > 0 or sObject.speedX < 0:
                    #move the object and see if they collides with another object
                    if not sObject.move(
                            sObject.speedX * this.getGame().deltaTime, 0):
                        if not sObject.getState("isJumping"):
                            #if they collide, then set the x speed to 0
                            sObject.speedX = 0

                #if the object is in the air
                if sObject.speedY > 0 or sObject.speedY < 0:
                    #move the object and see if he collides with another object
                    if not sObject.move(
                            0, (sObject.speedY * this.getGame().deltaTime)):
                        #if they collides, set the y speed to 0
                        sObject.speedY = 0

            #if the object is not a character sprite
            else:
                #if the object has mass
                if sObject.mass > 0:
                    #make the object fall
                    sObject.move(0, (this.getGame().deltaTime / 2) *
                                 this.getGame().gravity)

        def checkTriggers(this):
            #loop through each trigger
            for trigger in this.getGame().getTriggerSprites():
                #check to see if the trigger is colliding with the player
                if this.getGame().getPlayer().getRect().colliderect(
                        trigger.getRect()):
                    #trigger the event
                    trigger.event()

            #countdown the timers on the triggers
            Trigger.game.countdownTimers(Trigger)

        #a method to run if the player has a game over
        def gameOver(this):
            #if it is not a victorious game over
            if not this.getGame().getVictory():
                pygame.mixer.music.load('sounds/music/gameOver.wav')
                pygame.mixer.music.play(-1)
                #remove any text box elements (if there is any)
                this.getHud().removeTextBox()
                #Create a text box with a message
                this.getHud().createBoxWithMessage(  "*-----------------------------------------------*"\
                                                    +"|     _____                 ____                |"\
                                                    +"|    / ___/__ ___ _  ___   / __ \_  _____ ____  |"\
                                                    +"|   / (_ / _ `/  ` \/ -_) / /_/ / |/ / -_) __/  |"\
                                                    +"|   \___/\_,_/_/_/_/\__/  \____/|___/\__/_/     |"\
                                                    +"|                                               |"\
                                                    +"|                                               |"\
                                                    +"|   Press ESC key to go back to the main menu   |"\
                                                    +"*-----------------------------------------------*",\
                           this.getHud().getTextBoxLocX(), this.getHud().getTextBoxLocY(),\
                           this.getHud().getTextBoxSizeX(), this.getHud().getTextBoxSizeY() + 2,\
                           False)
            #if it is a victorious game over
            elif this.getGame().getVictory():
                pygame.mixer.music.load('sounds/music/victory.wav')
                pygame.mixer.music.play(-1)
                #remove any text box elements (if there is any)
                this.getHud().removeTextBox()
                #Create a text box with a message
                this.getHud().createBoxWithMessage("   _    ___      __                     "\
                                                  +"  | |  / (_)____/ /_____  _______  __   "\
                                                  +"  | | / / / ___/ __/ __ \/ ___/ / / /   "\
                                                  +"  | |/ / / /__/ /_/ /_/ / /  / /_/ /    "\
                                                  +"  |___/_/\___/\__/\____/_/   \__, /     "\
                                                  +"                            /____/      "\
                                                  +"                                        "\
                                                  +"                                        "\
                                                  +"  Press ESC to return to the main menu  ",\
                                                   128,212,43,13, False)
            #reset the game over flag so this does not repeat
            this.getGame().setGameOverPlayed(True)

    #----------------------------- Main Menu Method -------------------------

        def runMainMenu(this):
            pygame.mixer.music.load('sounds/music/title.wav')
            pygame.mixer.music.play(-1)
            #Create a main menu and while bool to store selection
            this.getHud().createBoxWithMessage("*-----------------------------------------------------*"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|               P r e s s     S P A C E               |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|         S  T  A  R  T          G  A  M  E           |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"*-----------------------------------------------------*",\
                                               8,8,58,18, False)
            this.getHud().createBoxWithMessage("*-----------------------------------------------------*"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|            Q  U  I  T          G  A  M  E           |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                P r e s s    E S C                   |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"*-----------------------------------------------------*",\
                                               8,328,58,18, False)
            this.getHud().createBoxWithMessage("        ______   _           __   _     "\
                                              +"       / __/ /  (_)__  ___  / /  (_)    "\
                                              +"      _\ \/ _ \/ / _ \/ _ \/ _ \/ /     "\
                                              +"     /___/_//_/_/_//_/\___/_.__/_/      "\
                                              +"                                        "\
                                              +"     ___                        _       "\
                                              +"    / _ | ___ ___ ___ ____ ___ (_)__    "\
                                              +"   / __ |(_-<(_-</ _ `(_-<(_-</ / _ \   "\
                                              +"  /_/ |_/___/___/\_,_/___/___/_/_//_/   ",\
                                               128,212,43,13, False)
            mainMenu = Menu("Main")
            mainMenu.addMenuItem("Start",
                                 this.getGame().imgBlank, 0, 0, 960, 320)
            #mainMenu.addMenuItem("Start", this.getGame().startImage, 0,0,480,320)
            #mainMenu.addMenuItem("Options", this.getGame().optionsImage, 480,0,480,320)
            mainMenu.addMenuItem("Quit",
                                 this.getGame().imgBlank, 0, 320, 960, 320)

            #------------------ Main Menu Loop Begin -------------------

            #while we are considered in the main menu
            while (this.getGame().getAtMainMenu()):
                #for event in pygame.event.get():

                #------------ Event Processes ------------

                #a method that checks to see if a menu item get pressed
                #and assigns the process name to a process variable
                #process = mainMenu.selectOption(this.getGame().getDisplay(), event)

                process = this.processInput()

                this.runSelectedProcess(process)
                #----------- Graphics Rendering -----------
                """ The way this works, is that it builds the display
                in layers based on what comes first and the last thing
                that gets drawn is the sprite/shape on the bottom of the
                graphics rendering code block """

                #draw the HUD sprites on the screen
                this.getHud().getHUDSprites().update()

                #run the render graphics method
                this.renderGraphics()

                #update the screen
                pygame.display.update()

                #Run the display menu items method
                #mainMenu.displayMenuItems(this.getGame().getDisplay())

                #------------ Game Timers ----------------

                this.getGame().countdownTimers(this)

                #----------- Update Process --------------

                #update the display outside of the event loop to reflect any changes
                pygame.display.update()

                #update frames per second outside fo the update loop and set the delta time to the variable
                this.getGame().deltaTime = (
                    this.getGame().clock.tick(this.getGame().gameFPS) / 4)

                #ensure the pygame event system is still working properly
                pygame.event.pump()

            #-------------------- Main Menu Loop End ------------------------

        def runOptionsMenu(this):
            print("You are in the options menu, nothing here yet...")
            this.runSelectedProcess("Main Menu")

        def runSelectedProcess(this, process):
            if process == "jump":
                print("Starting Start Process...")
                this.getGame().setAtMainMenu(False)
                this.getGame().setAtOptionsMenu(False)
                this.getGame().setAtGame(True)

            elif process == "Main Menu":
                print("Returning to the Main Menu...")
                this.getGame().setAtMainMenu(True)
                this.getGame().setAtOptionsMenu(False)
                this.getGame().setAtGame(False)

            elif process == "Options":
                print("Starting Options Process...")
                this.getGame().setAtMainMenu(False)
                this.getGame().setAtOptionsMenu(True)
                this.getGame().setAtGame(False)

            elif process == "Quit":
                print("Continuing Quit Process...")
                this.getGame().setGameRunning(False)
                this.getGame().setAtMainMenu(False)
                this.getGame().setAtOptionsMenu(False)
                this.getGame().setAtGame(False)
                this.quitGame()

            elif process == "Invalid":
                print(
                    "You have selected an invalid proceess... please try again"
                )

            else:
                pass

        def quitLevel(this):
            #Clear out all sprite groups
            this.getGame().getTerrainSprites().empty()
            this.getGame().getItemSprites().empty()
            this.getGame().getNPCSprites().empty()
            this.getGame().getTriggerSprites().empty()
            this.getHud().getHUDSprites().empty()
            #Remove the player
            this.getGame().getPlayer().kill()
            #reset the camera
            this.getCamera().reset()
            #reset the game over flag
            this.getGame().setGameOver(False)
            #reset the victory flag
            this.getGame().setVictory(False)
            #remove the game over text Box
            this.getHud().removeTextBox()
            #run the main menu process
            this.runSelectedProcess("Main Menu")

        def quitGame(this):
            pygame.quit()
            quit()
コード例 #28
0
class Trigger(GameObject):
    def __init__(this, name, posX, posY, sizeX, sizeY):
        this.__name = name
        image = this.game.imgBlank
        this.rect = pygame.Rect(posX, posY, sizeX, sizeY)
        super().__init__(name, image, posX, posY, sizeX, sizeY)
        #add this Trigger to the list of Trigger Sprites
        this.game.getTriggerSprites().add(this)
        #initilize the trigger
        this.init()

    hud = HUD()

    #------------------------------------------------------------------------------#
    #                                                                              #
    #                              Class  Attributes                               #
    #                                                                              #
    #------------------------------------------------------------------------------#

    __isTriggered = False  #a boolean to represent if the event has happened recently
    timers = {}  #a dictonary of timers

    #------------------------------------------------------------------------------#
    #                                  Accessors                                   #
    #------------------------------------------------------------------------------#

    def getIsTriggered(this):
        return this.__isTriggered

#------------------------------------------------------------------------------#
#                                  Mutators                                    #
#------------------------------------------------------------------------------#

    def setIsTriggered(this, boolean):
        this.__isTriggered = boolean

#------------------------------------------------------------------------------#
#                                                                              #
#                               Class  Methods                                 #
#                                                                              #
#------------------------------------------------------------------------------#

    def init(this):
        this.game.setTimer(this, "triggerTimer", -1)
        this.game.setTimer(this, "messageTimer", -1)

    #set off the trigger event
    def event(this):
        #check to see if the event has already been triggered
        #and there are no game overs
        if not this.getIsTriggered()\
           and not this.game.getGameOver():

            if this.game.checkTimer(this, "triggerTimer"):
                if this.getName() == "clearMessages":
                    this.hud.removeTextBox()
                    #ensure that we dont spam this trigger
                    this.game.setTimer(this, "triggerTimer", 25)

            #if enough time has passed to display another message
            if this.game.checkTimer(this, "messageTimer"):
                if this.getName() == "howToMoveMessage":
                    #remove any text box elements (if there is any)
                    this.hud.removeTextBox()
                    #Create a text box with a message
                    this.hud.createBoxWithMessage( "-----------Welcome to Shinobi Assassin-----------"\
                                                  +"                                                 "\
                                                  +"The goal of the game is to make it to the end of "\
                                                  +"   the level without losing all of your hearts   "\
                                                  +"   --Press W,A,S,D or the ARROW keys to move--   "\
                                                  +"         --Press the SPACE-BAR to jump--         "\
                                                  +"          --Press the ESC key to quit--          ",
                               this.hud.getTextBoxLocX(), this.hud.getTextBoxLocY(),\
                               this.hud.getTextBoxSizeX(), this.hud.getTextBoxSizeY(),\
                               False)
                    this.game.setTimer(this, "messageTimer", 50)

                elif this.getName() == "howToAttackMessage":
                    #remove any text box elements (if there is any)
                    this.hud.removeTextBox()
                    #Create a text box with a message
                    this.hud.createBoxWithMessage( "--------------------Attacking--------------------"\
                                                  +"                                                 "\
                                                  +"In order to make an attack, you must approach the"\
                                                  +" enemy carefully and then press the attack button"\
                                                  +"      --Attack Button: RIGHT CONTROL (ctrl)--    "\
                                                  +"Be careful not to get too close or else the enemy"\
                                                  +"         will try to attack you instead          ",\
                               this.hud.getTextBoxLocX(), this.hud.getTextBoxLocY(),\
                               this.hud.getTextBoxSizeX(), this.hud.getTextBoxSizeY(),\
                               False)
                    this.game.setTimer(this, "messageTimer", 50)

                elif this.getName() == "enemyInfoMessage":
                    #remove any text box elements (if there is any)
                    this.hud.removeTextBox()
                    #Create a text box with a message
                    this.hud.createBoxWithMessage( "----------------Enemy  Behavior------------------"\
                                                  +"                                                 "\
                                                  +"  When an enemy spots you, they will attempt to  "\
                                                  +"   chase you down and stab you. They will only   "\
                                                  +"   follow your last known location. After doing  "\
                                                  +"  so, they will continue to search for a period  "\
                                                  +" of time until they go back to their posted area.",\
                               this.hud.getTextBoxLocX(), this.hud.getTextBoxLocY(),\
                               this.hud.getTextBoxSizeX(), this.hud.getTextBoxSizeY(),\
                               False)
                    this.game.setTimer(this, "messageTimer", 50)

                elif this.getName() == "enemyBroadcastMessage":
                    #remove any text box elements (if there is any)
                    this.hud.removeTextBox()
                    #Create a text box with a message
                    this.hud.createBoxWithMessage( "---------------Enemy  Broadcasting---------------"\
                                                  +"                                                 "\
                                                  +"   When an enemy spots you, they will alert all  "\
                                                  +"  other enemies around them. In order to prevent "\
                                                  +"  a group of enemies trying to attack you all at "\
                                                  +"    once, it is better to try and make your way  "\
                                                  +"     through the level without getting spotted   ",\
                               this.hud.getTextBoxLocX(), this.hud.getTextBoxLocY(),\
                               this.hud.getTextBoxSizeX(), this.hud.getTextBoxSizeY(),\
                               False)
                    this.game.setTimer(this, "messageTimer", 50)

                elif this.getName() == "victory":
                    this.game.setVictory(True)
                    this.game.setGameOver(True)
コード例 #29
0
    def __init__(self,
                 client: carla.Client,
                 strategy: EgoStrategy = None,
                 name: str = 'hero',
                 render: bool = False,
                 debug: bool = False,
                 record: bool = False,
                 is_standalone: bool = False,
                 grid_radius: float = OCCUPANCY_RADIUS_DEFAULT,
                 lidar_angle: float = LIDAR_ANGLE_DEFAULT):
        self.killer: GracefulKiller = GracefulKiller(
        ) if is_standalone else None
        self.sim: carla.Client = client
        self.client: TalkyClient = None
        self.world: carla.World = client.get_world()
        self.map: carla.Map = self.world.get_map()
        self.alive: bool = True
        self.name: str = name
        self.vehicle: carla.Vehicle = None
        self.player: carla.Vehicle = None  # for compatibility
        self.grid: Grid = None
        self.hud: HUD = None
        self.strategy: EgoStrategy = strategy
        self.debug: bool = debug
        self.record: bool = record
        self.n_ticked: int = 0
        self.display = None
        self.sensor_tick_pool: ThreadPool = ThreadPool(processes=6)
        self.sensors: Dict[str, carla.Sensor] = {
            'gnss': None,
            'lidar': None,
            'camera_rgb': None,
            'position': None,
        }

        # Initialize visual stuff
        if render:
            pygame.init()
            pygame.display.set_caption(f'PyGame – {name}')
            pygame.font.init()
            self.display = pygame.display.set_mode(
                (RES_X, RES_Y), pygame.HWSURFACE | pygame.DOUBLEBUF)
            self.hud = HUD(RES_X, RES_X)

        # Initialize strategy
        if not self.strategy:
            self.strategy = ManualEgoStrategy(
            ) if render else EmptyEgoStrategy()
        self.strategy.init(self)

        # Initialize callbacks
        if self.hud:
            self.world.on_tick(self.hud.on_world_tick)

        # Initialize player vehicle
        self.vehicle = self.strategy.player
        self.player = self.vehicle

        # Initialize Talky Client
        self.client = TalkyClient(for_subject_id=self.vehicle.id,
                                  dialect=ClientDialect.CARLA)
        self.client.gm.radius = grid_radius

        # Initialize sensors
        grid_range = grid_radius * QuadKey('0' * OCCUPANCY_TILE_LEVEL).side()
        lidar_min_range = (grid_range + .5) / math.cos(
            math.radians(lidar_angle))
        lidar_range = min(
            LIDAR_MAX_RANGE,
            max(lidar_min_range,
                LIDAR_Z_OFFSET / math.sin(math.radians(lidar_angle))) * 2)

        self.sensors['gnss'] = GnssSensor(self.vehicle,
                                          self.client,
                                          offset_z=GNSS_Z_OFFSET)
        self.sensors['lidar'] = LidarSensor(self.vehicle,
                                            self.client,
                                            offset_z=LIDAR_Z_OFFSET,
                                            range=lidar_range,
                                            angle=lidar_angle)
        self.sensors['actors'] = ActorsSensor(
            self.vehicle, self.client,
            with_noise=True)  # Set to false for evaluation
        self.sensors['position'] = PositionSensor(self.vehicle, self.client)
        if render:
            self.sensors['camera_rgb'] = CameraRGBSensor(
                self.vehicle, self.hud)

        # Initialize subscriptions
        def on_grid(grid: OccupancyGridObservation):
            self.grid = grid.value

        self.client.outbound.subscribe(OBS_GRID_LOCAL, on_grid)

        if is_standalone:
            lock = Lock()
            clock = pygame.time.Clock()

            def on_tick(*args):
                if lock.locked() or self.killer.kill_now:
                    return

                lock.acquire()
                clock.tick_busy_loop(60)
                if self.tick(clock):
                    self.killer.kill_now = True
                lock.release()

            self.world.on_tick(on_tick)

            while True:
                if self.killer.kill_now:
                    try:
                        self.destroy()
                        return
                    finally:
                        return

                try:
                    self.world.wait_for_tick()
                except RuntimeError:
                    self.killer.kill_now = True
                    continue
コード例 #30
0
class Player(Character):

    def __init__(this, posX, posY):
        super().__init__("Player", this.game.playerImage, posX, posY,\
                         this.game.getBlockScale() * 1, this.game.getBlockScale() * 2, 1, 1)

        #initilize the player
        this.init()
        

#------------------------------------------------------------------------------#
#                                                                              #
#                              Class  Attributes                               #
#                                                                              #
#------------------------------------------------------------------------------#

    #player images
    imgIdle = [pygame.image.load("sprites/characters/peasant/tile000.png"),\
                    pygame.image.load("sprites/characters/peasant/tile001.png"),\
                    pygame.image.load("sprites/characters/peasant/tile002.png"),\
                    pygame.image.load("sprites/characters/peasant/tile003.png"),\
                    pygame.image.load("sprites/characters/peasant/tile004.png"),\
                    pygame.image.load("sprites/characters/peasant/tile005.png"),\
                    pygame.image.load("sprites/characters/peasant/tile006.png"),\
                    pygame.image.load("sprites/characters/peasant/tile007.png"),\
                    pygame.image.load("sprites/characters/peasant/tile008.png"),\
                    pygame.image.load("sprites/characters/peasant/tile009.png")]
    imgUse = [pygame.image.load("sprites/characters/peasant/tile010.png"),\
                   pygame.image.load("sprites/characters/peasant/tile011.png"),\
                   pygame.image.load("sprites/characters/peasant/tile012.png"),\
                   pygame.image.load("sprites/characters/peasant/tile013.png"),\
                   pygame.image.load("sprites/characters/peasant/tile014.png"),\
                   pygame.image.load("sprites/characters/peasant/tile015.png"),\
                   pygame.image.load("sprites/characters/peasant/tile016.png"),\
                   pygame.image.load("sprites/characters/peasant/tile017.png"),\
                   pygame.image.load("sprites/characters/peasant/tile018.png"),\
                   pygame.image.load("sprites/characters/peasant/tile019.png")]
    imgRun = [pygame.image.load("sprites/characters/peasant/tile020.png"),\
                    pygame.image.load("sprites/characters/peasant/tile021.png"),\
                    pygame.image.load("sprites/characters/peasant/tile022.png"),\
                    pygame.image.load("sprites/characters/peasant/tile023.png"),\
                    pygame.image.load("sprites/characters/peasant/tile024.png"),\
                    pygame.image.load("sprites/characters/peasant/tile025.png"),\
                    pygame.image.load("sprites/characters/peasant/tile026.png"),\
                    pygame.image.load("sprites/characters/peasant/tile027.png"),\
                    pygame.image.load("sprites/characters/peasant/tile028.png"),\
                    pygame.image.load("sprites/characters/peasant/tile029.png")]
    imgAttack = [pygame.image.load("sprites/characters/peasant/tile030.png"),\
                      pygame.image.load("sprites/characters/peasant/tile031.png"),\
                      pygame.image.load("sprites/characters/peasant/tile032.png"),\
                      pygame.image.load("sprites/characters/peasant/tile033.png"),\
                      pygame.image.load("sprites/characters/peasant/tile034.png"),\
                      pygame.image.load("sprites/characters/peasant/tile035.png"),\
                      pygame.image.load("sprites/characters/peasant/tile036.png"),\
                      pygame.image.load("sprites/characters/peasant/tile037.png"),\
                      pygame.image.load("sprites/characters/peasant/tile038.png"),\
                      pygame.image.load("sprites/characters/peasant/tile039.png")]
    imgDeath = [pygame.image.load("sprites/characters/peasant/tile040.png"),\
                     pygame.image.load("sprites/characters/peasant/tile041.png"),\
                     pygame.image.load("sprites/characters/peasant/tile042.png"),\
                     pygame.image.load("sprites/characters/peasant/tile043.png"),\
                     pygame.image.load("sprites/characters/peasant/tile044.png"),\
                     pygame.image.load("sprites/characters/peasant/tile045.png"),\
                     pygame.image.load("sprites/characters/peasant/tile046.png"),\
                     pygame.image.load("sprites/characters/peasant/tile047.png"),\
                     pygame.image.load("sprites/characters/peasant/tile048.png"),\
                     pygame.image.load("sprites/characters/peasant/tile049.png")]
    imgBlank = pygame.image.load("sprites/characters/peasant/blank.png")


    #Hud Reference
    __hud = HUD()

#------------------------------------------------------------------------------#
#                                  Accessors                                   #
#------------------------------------------------------------------------------#

    #get the hud instance
    def getHud(this):
        return this.__hud

#------------------------------------------------------------------------------#
#                                  Mutators                                    #
#------------------------------------------------------------------------------#

    #no mutators in here
             
#------------------------------------------------------------------------------#
#                                                                              #
#                               Class  Methods                                 #
#                                                                              #
#------------------------------------------------------------------------------#

    #initilize the player
    def init(this):
        this.setCharacterDefaults()
        this.setPlayerDefaults()
        this.setupTimers()
        this.setupStates()
        this.adjustImage()
        this.game.setPlayer(this)

    #set the default values of the player that will be different than
    #the character default values
    def setPlayerDefaults(this):
        #player game attributes
        this.healthMax = 3          #maximum number of health
        this.health = 3             #current health

        #player image variables
        this.imageOffsetX = this.game.getBlockScale()
        this.imageOffsetY = 0       #how much an image needs to be adjusted on the Y axis

        #player physics variables
        this.jumpForceX = 1.5       #how much X force is put into a jump
        this.jumpForceY = 4         #how much Y force is put into a jump
        this.runSpeed = 0.5         #how fast a character runs
        this.maxSpeed = 2           #the maximum speed a character can achieve
        this.attackForce = 3.5        #how much force a character adds when they hit with an attack


        #player timer and triggers
        this.jumpTimeTrig = 15      #how long a jump lasts
        this.midJumpTimeTrig = 7    #how long before it is considered mid-jump
        this.jumpCool = 18          #how long before a character can jump again
        this.attackCool = 10        #how long before a character can attack again        
        this.hurtCool = 200         #how long before you can take damage again

        #player sounds
        this.wavJump = pygame.mixer.Sound("sounds/effects/playerJump.wav")
        this.wavAttack = pygame.mixer.Sound("sounds/effects/playerAttack.wav")
        this.wavHurt = pygame.mixer.Sound("sounds/effects/playerHurt.wav")
        this.wavDeath = pygame.mixer.Sound("sounds/effects/playerDeath.wav")