def __init__(self,*args,**kwargs): super(Instructions_display,self).__init__(inst_1_img,*args,**kwargs) self.key_handler=key.KeyStateHandler() self.counter=1 self.keypress_delay=1 self.complete=False
def __init__(self, joystick, **kwargs): super(GameWindow, self).__init__(**kwargs) if not self.fullscreen: self.set_location(20, 35) self.set_vsync(True) self.set_mouse_visible(False) self.userInput = Attributes() self.userInput.joystick = None self.userInput.keys = key.KeyStateHandler() self.userInput.mousePosition = (0, 0) props = WindowProps() w = props.windowWidth = self.width h = props.windowHeight = self.height self.props = props # We need to keep references to batched sprites or they get garbage collected! self.sprites = [] self.gameElements = GameElements(props) self.gameElements.populateGame(gAssets) self.score = Score() maxSpeed = 200 self.zombies = [] #self.runner = Runner(w//2, h//2, maxSpeed) self.zombies.append(Zombie(100, h // 2, maxSpeed)) self.zombies.append(Zombie(800, h // 2, maxSpeed)) self.grassBatch = pyglet.graphics.Batch() grass = self.tileRegion(self.grassBatch, gAssets.getImage('grass'), (0, w), (0, h)) for g in grass: g.opacity = 180 self.wallImgBatch = pyglet.graphics.Batch() self.wallPolygons = xsect.PolygonList() brk = gAssets.getImage('brick') #self.addWall( (400,450), (320,600)) #self.addWall( (450,900), (550,600)) #self.addWall( (850,900), (400,600)) #self.addWall( (200,250), (100,400)) #self.addWall( (600,650), (100,350)) self.runner = Runner(530, 400, maxSpeed) self.countdowntimer = countdowntimer.CountDownTimer(110) # Window border self.wallPolygons.add(xsect.Polygon((0, 0), (w, 0))) self.wallPolygons.add(xsect.Polygon((w, 0), (w, h))) self.wallPolygons.add(xsect.Polygon((w, h), (0, h))) self.wallPolygons.add(xsect.Polygon((0, h), (0, 0))) #self.keys = key.KeyStateHandler() #self.push_handlers(self.keys) self.push_handlers(self.userInput.keys) # I think extending Window automatically has this as a handler #self.push_handlers(self.on_key_press) self.push_handlers(self.on_mouse_motion)
from pyglet.window import key import constants space = pymunk.Space() space.gravity = (0, 0) with open('client_config.json', encoding='utf-8') as file: config = json.load(file) PORT = config["port"] host = config["host"] number_tile_x = config["number_tile_x"] number_tile_y = config["number_tile_y"] full_width = number_tile_x * 50 full_height = number_tile_y * 50 keys = key.KeyStateHandler() bg_group = pyglet.graphics.OrderedGroup(0) tracks_group = pyglet.graphics.OrderedGroup(1) tank_group = pyglet.graphics.OrderedGroup(2) smoke_group = pyglet.graphics.OrderedGroup(3) barrel_group = pyglet.graphics.OrderedGroup(4) explosion_group = pyglet.graphics.OrderedGroup(5) hud_group = pyglet.graphics.OrderedGroup(100) bg_batch = pyglet.graphics.Batch() fg_batch = pyglet.graphics.Batch() hud_batch = pyglet.graphics.Batch() gui_batch = pyglet.graphics.Batch() projectiles = dict() tanks = dict()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.keys = key.KeyStateHandler() self.push_handlers(self.keys) self.game_init()
def __init__(self, window): self.window = window self.window_sizes = [(800, 600), (1024, 768), (1680, 1050)] self.current_size = len(self.window_sizes) - 1 self.keys = key.KeyStateHandler()
def __init__(self, dt=0.5, fullscreen=False, name='unnamed', iters=1000, magnify=1.): self.autoquit = False self.frame = None self.subframes = None self.visible_cars = [] self.magnify = magnify self.camera_center = None self.name = name self.output = None self.iters = iters self.objects = [] self.event_loop = pyglet.app.EventLoop() self.window = pyglet.window.Window(600, 600, fullscreen=fullscreen, caption=name) self.grass = pyglet.resource.texture('grass.png') self.window.on_draw = self.on_draw self.lanes = [] self.cars = [] self.dt = dt self.anim_x = {} self.prev_x = {} self.feed_u = None self.feed_x = None self.prev_t = None self.joystick = None self.keys = key.KeyStateHandler() self.window.push_handlers(self.keys) self.window.on_key_press = self.on_key_press self.main_car = None self.heat = None self.heatmap = None self.heatmap_valid = False self.heatmap_show = False self.cm = matplotlib.cm.jet self.paused = False self.label = pyglet.text.Label('Speed: ', font_name='Times New Roman', font_size=24, x=30, y=self.window.height - 30, anchor_x='left', anchor_y='top') def centered_image(filename): img = pyglet.resource.image(filename) img.anchor_x = img.width / 2. img.anchor_y = img.height / 2. return img def car_sprite(color, scale=0.15 / 600.): sprite = pyglet.sprite.Sprite(centered_image( 'car-{}.png'.format(color)), subpixel=True) sprite.scale = scale return sprite def object_sprite(name, scale=0.15 / 600.): sprite = pyglet.sprite.Sprite(centered_image( '{}.png'.format(name)), subpixel=True) sprite.scale = scale return sprite self.sprites = { c: car_sprite(c) for c in ['red', 'yellow', 'purple', 'white', 'orange', 'gray', 'blue'] } self.obj_sprites = {c: object_sprite(c) for c in ['cone', 'firetruck']}
def main(): window = pyglet.window.Window(1000, 1000, "Rumble in the Bronchs", resizable=True) # Store objects in a batch to load them efficiently main_batch = pyglet.graphics.Batch() # groups - 0 drawn first, 10 drawn last groups = [] for i in range(10): groups.append(pyglet.graphics.OrderedGroup(i)) # load required resources assets = GameAssets() # background music score background_music = assets.audio_assets["ost_music"] p = pyglet.media.Player() p.queue(background_music) p.loop = True p.play() # common game state for all the game objects state = GameState() # initialize dummy background and foreground state.bkg = GameObject(img=assets.image_assets["img_dummy"], x=-1, y=-1, batch=main_batch, group=groups[0]) state.bkg.type = "art" state.frg = GameObject(img=assets.image_assets["img_dummy"], x=-1, y=-1, batch=main_batch, group=groups[9]) state.frg.type = "art" state.game_level = -1 # pre launch state # keyboard input handler key_handler = key.KeyStateHandler() window.push_handlers(key_handler) # list of all game objects game_objects = [] lbl_score = pyglet.text.Label('score: ' + str(state.score), font_name='Times New Roman', font_size=36, x=870, y=window.height - 50, anchor_x='center', anchor_y='center', batch=main_batch, group=groups[8]) lbl_timer = pyglet.text.Label('time left: ' + str(state.level_time), font_name='Times New Roman', font_size=36, x=850, y=window.height - 100, anchor_x='center', anchor_y='center', batch=main_batch, group=groups[8]) @window.event def on_draw(): window.clear() main_batch.draw() def handle_game_launch(): state.frg.image = assets.image_assets["img_start_screen_C"] state.game_level = 0 def handle_start_screen(): if key_handler[key.RIGHT]: state.frg.image = assets.image_assets["img_start_screen_D"] if key_handler[key.LEFT]: state.frg.image = assets.image_assets["img_start_screen_C"] if key_handler[key.ENTER]: state.game_level = 1 load_stage_1() def handle_game_over_screen(): state.frg.image = assets.image_assets["img_game_over"] state.frg.group = groups[9] if key_handler[key.R]: state.game_level = 0 state.infection_level = 0 state.player_life = 100 state.score = 0 remove_all_non_essential_game_objects() load_stage_1() def handle_win_screen(): state.frg.image = assets.image_assets["img_win"] state.frg.group = groups[9] if key_handler[key.R]: state.game_level = 1 state.infection_level = 0 state.player_life = 100 state.score = 0 remove_all_non_essential_game_objects() load_stage_1() def handle_level_change(): if state.game_level == -2: remove_all_non_essential_game_objects() handle_game_over_screen() if state.infection_level < 50: # if under threshold TODO: make this a variable state.game_level += 1 # move to next level state.game_level = min(state.game_level, 4) else: state.game_level = -2 # game over if state.game_level == 2: assets.audio_assets["snd_level_change"].play() remove_all_non_essential_game_objects() state.infection_level = 0 load_stage_2() elif state.game_level == 3: assets.audio_assets["snd_level_change"].play() state.infection_level = 0 remove_all_non_essential_game_objects() load_stage_3() elif state.game_level == 4: remove_all_non_essential_game_objects() handle_win_screen() elif state.game_level == -2: remove_all_non_essential_game_objects() handle_game_over_screen() def load_stage_1(): state.time_counter = 0 # background and foreground state.bkg.image = assets.image_assets["img_bkg_level_1"] state.frg.image = assets.image_assets["img_frg_level_1"] state.frg.group = groups[7] # player player = Player(state, assets, x=100, y=400, batch=main_batch, group=groups[5]) window.push_handlers(player) window.push_handlers(player.key_handler) # health bar health_bar = HealthBar(state, assets, x=state.player_life, y=900, batch=main_batch, group=groups[8]) # infection bar infection_bar = InfectionBar(state, assets, x=state.infection_level, y=970, batch=main_batch, group=groups[8]) # virus spawner spawn_locations = [(166, 705), (406, 721), (809, 542), (452, 220), (195, 208), (116, 393), (417, 862), (755, 617), (123, 502), (901, 496)] virus_spawner = VirusSpawner(state, assets, spawn_locations, x=-5, y=0, batch=main_batch, group=groups[5]) # stage - polygon colliders vertices1 = [1001, 200, 824, 225, 537, 177, 435, 108, 415, 0, 1001, 0] vertices2 = [0, 272, 0, 0, 255, 0, 232, 73, 45, 266] vertices3 = [ 256, 481, 375, 364, 606, 334, 697, 447, 627, 599, 402, 623 ] vertices4 = [ 576, 1001, 601, 902, 744, 851, 837, 712, 969, 651, 1001, 665, 1001, 1001 ] vertices5 = [0, 1001, 0, 811, 137, 810, 282, 876, 275, 1001] polygon1 = PolygonCollider(util.get_points(vertices1), state, assets, "poly1", group=groups[5]) polygon2 = PolygonCollider(util.get_points(vertices2), state, assets, "poly2", group=groups[5]) polygon3 = PolygonCollider(util.get_points(vertices3), state, assets, "poly3", group=groups[5]) polygon4 = PolygonCollider(util.get_points(vertices4), state, assets, "poly4", group=groups[5]) polygon5 = PolygonCollider(util.get_points(vertices5), state, assets, "poly5", group=groups[5]) # list of all game objects # game_objects.append(state.bkg) # game_objects.append(state.frg) game_objects.append(player) game_objects.append(health_bar) game_objects.append(infection_bar) game_objects.append(virus_spawner) game_objects.append(polygon1) game_objects.append(polygon2) game_objects.append(polygon3) game_objects.append(polygon4) game_objects.append(polygon5) def load_stage_2(): state.time_counter = 0 # background and foreground state.bkg.image = assets.image_assets["img_bkg_level_2"] state.frg.image = assets.image_assets["img_frg_level_2"] # player player = Player(state, assets, x=500, y=200, batch=main_batch, group=groups[5]) window.push_handlers(player) window.push_handlers(player.key_handler) # health bar health_bar = HealthBar(state, assets, x=state.player_life, y=900, batch=main_batch, group=groups[8]) # infection bar infection_bar = InfectionBar(state, assets, x=state.infection_level, y=970, batch=main_batch, group=groups[8]) # virus spawner spawn_locations = [(139, 828), (293, 603), (330, 291), (101, 141), (483, 71), (754, 214), (941, 221), (634, 521), (782, 665), (871, 845)] virus_spawner = VirusSpawner(state, assets, spawn_locations, x=-5, y=0, batch=main_batch, group=groups[5]) # stage - polygon colliders vertices1 = [403, 0, 343, 122, 173, 46, 151, 1] vertices2 = [600, 58, 660, 0, 1001, 0, 998, 35, 656, 167] vertices3 = [1001, 730, 795, 555, 739, 379, 871, 275, 1001, 275] vertices4 = [1, 742, 0, 193, 170, 269, 204, 500, 123, 701] vertices5 = [289, 1001, 374, 696, 626, 657, 730, 865, 657, 1000] polygon1 = PolygonCollider(util.get_points(vertices1), state, assets, "poly1", group=groups[5]) polygon2 = PolygonCollider(util.get_points(vertices2), state, assets, "poly2", group=groups[5]) polygon3 = PolygonCollider(util.get_points(vertices3), state, assets, "poly3", group=groups[5]) polygon4 = PolygonCollider(util.get_points(vertices4), state, assets, "poly4", group=groups[5]) polygon5 = PolygonCollider(util.get_points(vertices5), state, assets, "poly5", group=groups[5]) # list of all game objects game_objects.append(player) game_objects.append(health_bar) game_objects.append(infection_bar) game_objects.append(virus_spawner) game_objects.append(polygon1) game_objects.append(polygon2) game_objects.append(polygon3) game_objects.append(polygon4) game_objects.append(polygon5) def load_stage_3(): state.time_counter = 0 # background and foreground state.bkg.image = assets.image_assets["img_bkg_level_3"] state.frg.image = assets.image_assets["img_frg_level_3"] # player player = Player(state, assets, x=150, y=800, batch=main_batch, group=groups[5]) window.push_handlers(player) window.push_handlers(player.key_handler) # health bar health_bar = HealthBar(state, assets, x=state.player_life, y=900, batch=main_batch, group=groups[8]) # infection bar infection_bar = InfectionBar(state, assets, x=state.infection_level, y=970, batch=main_batch, group=groups[8]) # virus spawner spawn_locations = [(97, 733), (96, 551), (169, 363), (468, 394), (659, 167), (774, 346), (896, 544), (732, 742), (570, 905), (359, 863)] virus_spawner = VirusSpawner(state, assets, spawn_locations, x=-5, y=0, batch=main_batch, group=groups[5]) # stage - polygon colliders vertices1 = [449, 252, 241, 209, 0, 239, 0, 0, 509, 0] vertices2 = [1001, 404, 889, 352, 815, 145, 830, 0, 1001, 0] vertices3 = [ 187, 601, 286, 489, 440, 532, 591, 509, 652, 627, 600, 739, 320, 742 ] vertices4 = [ 699, 910, 864, 889, 977, 793, 1001, 799, 1001, 1001, 784, 1001 ] polygon1 = PolygonCollider(util.get_points(vertices1), state, assets, "poly1", group=groups[5]) polygon2 = PolygonCollider(util.get_points(vertices2), state, assets, "poly2", group=groups[5]) polygon3 = PolygonCollider(util.get_points(vertices3), state, assets, "poly3", group=groups[5]) polygon4 = PolygonCollider(util.get_points(vertices4), state, assets, "poly4", group=groups[5]) # list of all game objects game_objects.append(player) game_objects.append(health_bar) game_objects.append(infection_bar) game_objects.append(virus_spawner) game_objects.append(polygon1) game_objects.append(polygon2) game_objects.append(polygon3) game_objects.append(polygon4) def remove_all_non_essential_game_objects(): for obj in game_objects: if obj.type != "art": if obj.type in ["virus_spawner"]: pyglet.clock.unschedule(obj.spawn_virus) if obj.type in ["virus"]: pyglet.clock.unschedule(obj.release_particle) obj.dead = True else: obj.dead = False def update(dt): if state.game_level == -1: handle_game_launch() elif state.game_level == 0: handle_start_screen() elif state.game_level == -2: # game over handle_level_change() elif state.game_level > 0 and state.game_level < 5 and state.time_counter > state.level_time: handle_level_change() # primitive collision detection # loop over pairs of game objects for i in range(len(game_objects)): for j in range(i + 1, len(game_objects)): object_one = game_objects[i] object_two = game_objects[j] # if either of the objects are not dead if not object_one.dead and not object_two.dead: # check collision if object_one.collides_with(object_two): # handle collision with each other object_one.handle_collision_with(object_two) object_two.handle_collision_with(object_one) objects_to_add = [] # list of new objects to add # update positions, state of each object and # collect all children that each object may spawn for obj in game_objects: obj.update_object( dt) # update the current position and state of objects objects_to_add.extend( obj.child_objects ) # add objects that this game object wants to spawn obj.child_objects = [] # clear the list # remove objects that are dead for object_to_remove in [obj for obj in game_objects if obj.dead]: object_to_remove.delete() game_objects.remove(object_to_remove) # add new objects game_objects.extend(objects_to_add) # count number of viruses. if more than a set amount, dont add any more virus_count = 0 for obj in game_objects: if obj.type in ["virus"]: virus_count += 1 if virus_count > 4: state.should_create_new_viruses = False else: state.should_create_new_viruses = True # if infection is max, dont fire off new virus particles if state.infection_level >= 100: state.should_fire_new_particles = False else: state.should_fire_new_particles = True state.time_counter += dt # update text lbl_score.text = 'score: ' + str(state.score) lbl_timer.text = 'time left: ' + str( max(0, state.level_time - int(state.time_counter))) # player death if state.player_life <= 0: state.game_level = -2 pyglet.clock.schedule_interval(update, 1 / 120.0) pyglet.app.run()
def main(duckie_env: DuckietownEnv, debug: bool): """ Main loop that allows to control duckiebot with keyboard and uses visual servo when bot is detected Args: duckie_env: the environment in which our duckiebot evolves debug: will log debug message if True """ duckie_env.reset() duckie_env.render() logger = logging.getLogger(__name__) if debug: logger.setLevel("DEBUG") else: logger.setLevel("INFO") pose_estimator = PoseEstimator(min_area=CIRCLE_MIN_AREA, min_dist_between_blobs=CIRCLE_MIN_DISTANCE, height=CIRCLE_PATTERN_HEIGHT, width=CIRCLE_PATTERN_WIDTH, target_distance=TARGET_DIST, camera_mode=CAMERA_MODE) # This is the object that computes the next command from the estimated pose trajectory = Trajectory() @duckie_env.unwrapped.window.event def on_key_press(symbol, modifier): """ This handler processes keyboard commands that control the simulation Args: symbol: key pressed """ if symbol in [key.BACKSPACE, key.SLASH]: logger.info("RESET") trajectory.reset() duckie_env.reset() duckie_env.render() elif symbol == key.PAGEUP: duckie_env.unwrapped.cam_angle[0] = 0 elif symbol == key.ESCAPE: duckie_env.close() sys.exit(0) # Register a keyboard handler key_handler = key.KeyStateHandler() duckie_env.unwrapped.window.push_handlers(key_handler) def update(dt: float): """ This function is called at every frame to handle movement/stepping and redrawing Args: dt: change in time (in secs) since last update """ action = np.array([0.0, 0.0]) if key_handler[key.UP]: action += np.array([0.44, 0.0]) if key_handler[key.DOWN]: action -= np.array([0.44, 0]) if key_handler[key.LEFT]: action += np.array([0, 1]) if key_handler[key.RIGHT]: action -= np.array([0, 1]) # Speed boost if key_handler[key.LSHIFT]: action *= 1.5 # TODO get observation before taking step # For now, we do nothing, get image, compute action, execute it. So 2 steps for one action # It should be get observations, compute action, take step, repeat. (1 action/step) obs, reward, done, info = duckie_env.step(action) target_detected, estimated_pose = pose_estimator.get_pose(obs) # Only for debugging, slows things down considerably and is not necessary # if detect: # cv2.drawChessboardCorners(obs, # (8, 3), centers, detection) # im = Image.fromarray(obs) # im.save("circle_grid.png") # Here we get the ground_truth to see the accuracy of our estimate # Note: This is in global frame, while the estimate is in robot frame. # Also, the exact distance from the center of the duck to the bumper is unknown so it is set approximately goal_position = np.array([2.5 - TARGET_DIST - BUMPER_TO_CENTER_DIST, 0, 2.5]) # Because duckie is at [2.5, 0. 2.5] in visual_servo.yaml env file goal_angle = 0 # Because duckie faces 0 angle in visual_servo.yaml env file cur_position = np.array(info["Simulator"]["cur_pos"]) cur_angle_rad = info["Simulator"]["cur_angle"] cur_angle_deg = np.rad2deg(cur_angle_rad) if cur_angle_deg > 179: cur_angle_deg -= 360 relative_position = goal_position - cur_position relative_angle = goal_angle - cur_angle_deg relative_pose = [relative_position, relative_angle] np.set_printoptions(precision=2) logger.debug(f"gt: {relative_pose}, estimate: {estimated_pose}") if target_detected: trajectory.update(estimated_pose) elif trajectory.is_initialized(): trajectory.predict(dt) else: logger.warning("object not found, cannot compute initial trajectory") # TODO for now we can move the duckie with the arrows. Eventually we just want # to reset the environment, and maybe log the starting pose to plot where we detect or not. if trajectory.is_initialized(): action = trajectory.get_commands() obs, reward, done, info = duckie_env.step(action) if key_handler[key.RETURN]: im = Image.fromarray(obs) im.save("screen.png") if done: logger.info("done!") duckie_env.reset() duckie_env.render() duckie_env.render() pyglet.clock.schedule_interval(update, 1.0 / duckie_env.unwrapped.frame_rate) # Enter main event loop pyglet.app.run() duckie_env.close()
def __init__(self, *args, **kwargs): super(Player, self).__init__(img=resources.car_image, *args, **kwargs) self.thrust = 2000.0 self.rotate_speed = 200.0 self.key_handler = key.KeyStateHandler()
def __init__(self, *args, **kwargs): super(Wall, self).__init__(img=resources.wall_image, *args, **kwargs) # Tell the game handler about any event handlers self.key_handler = key.KeyStateHandler() self.event_handlers = [self, self.key_handler]
class GameWindow(pyglet.window.Window, Thread): tile_width = 480 tile_height = 240 scale = 0.25 keyboard = key.KeyStateHandler() fx, fy = 0, 0 def __init__(self, x, y, g, *args, **kwargs): self.window_width = kwargs.get('window_width', 800) self.window_height = kwargs.get('window_height', 600) Thread.__init__(self) super(GameWindow, self).__init__(*args, **kwargs) pyglet.clock.schedule_interval(self.update, 1.0 / 30.0) self.daemon = True self.tile_batch = pyglet.graphics.Batch() self.floor_batch = pyglet.graphics.Batch() self.egg_batch = pyglet.graphics.Batch() self.clients_batch = pyglet.graphics.Batch() self.s, self.clients, self.eggs, self.sprites, self.floor, self.bucket = [], [], [], [], [], [] self.x, self.y, self.g = x, y, g self.push_handlers(self.keyboard) self.tile_img = pyglet.image.load('cube.png') self.tile_img2 = pyglet.image.load('cube2.png') self.player = pyglet.image.load('char.png') self.map = [[0] * x for _ in range(0, y)] self.fps_display = pyglet.clock.ClockDisplay() self.print_map() self.start() def run(self): while True: message = self.g.s.read().split() data = self.bucket.append(message) def move_eggs(self): for i in range(0, len(self.eggs)): cx, cy = self.to_iso(self.eggs[i].map_x, self.eggs[i].map_y) cx += (self.tile_width / 2) * self.scale - 30 cy += self.tile_height * self.scale + 30 self.eggs[i].set_position(cx, cy) def move_players(self): for i in range(0, len(self.clients)): cx, cy = self.to_iso(self.clients[i].map_x, self.clients[i].map_y) cx += (self.tile_width / 2) * self.scale - 15 cy += self.tile_height * self.scale + 30 self.clients[i].set_position(cx, cy) def update_egg(self, num): for i in range(0, len(self.eggs)): if self.eggs[i].number == num: self.eggs.remove(self.eggs[i]) return def update_player(self, x, y, pnumber, dead=0): for i in range(0, len(self.clients)): if self.clients[i].pnumber == pnumber: if dead != 0: self.clients.remove(self.clients[i]) return else: cx, cy = self.to_iso(x, y) cx += (self.tile_width / 2) * self.scale - 15 cy += self.tile_height * self.scale + 30 self.clients[i].set_position(cx, cy) def print_player(self, x, y, pnumber): cx, cy = self.to_iso(x, y) cx += (self.tile_width / 2) * self.scale + 30 cy += self.tile_height * self.scale + 30 client = pyglet.sprite.Sprite(self.player, x=cx, y=cy, batch=self.clients_batch) client.pnumber = pnumber client.map_x, client.map_y = x, y self.clients.append(client) def print_map(self): if self.s is not None: del self.s[:] for y in reversed(range(0, self.y)): for x in reversed(range(0, self.x)): cx, cy = self.to_iso(x, y) sprite = pyglet.sprite.Sprite(self.tile_img2, x=cx, y=cy, batch=self.tile_batch) sprite.scale = self.scale self.s.append(sprite) def print_all_objects(self): for i in range(0, len(self.floor)): cx, cy = self.to_iso(self.floor[i].map_x, self.floor[i].map_y) cx += (self.tile_width / 2) * self.scale + coord[self.floor[i].type][0] cy += self.tile_height * self.scale + coord[self.floor[i].type][1] self.floor[i].set_position(cx, cy) def print_objects(self, x, y, liste): if liste == 0: return self.map[y][x] = liste for i in range(0, len(liste)): var = False for elem in self.floor: if elem.map_x == x and elem.map_y == y and elem.type == i: if liste[i] == 1: var = True elif liste[i] == 0: self.floor.remove(elem) var = True elif liste[i] == 0: var = True if var == False: cx, cy = self.to_iso(x, y) cx += (self.tile_width / 2) * self.scale + coord[i][0] cy += self.tile_height * self.scale + coord[i][1] sprite = pyglet.sprite.Sprite(objects[i], x=cx, y=cy, batch=self.floor_batch) sprite.set_position(cx, cy) sprite.map_x, sprite.map_y = x, y sprite.type = i sprite.scale = self.scale self.floor.append(sprite) def add_egg(self, num, x, y): cx, cy = self.to_iso(x, y) cx += (self.tile_width / 2) * self.scale - 30 cy += self.tile_height * self.scale + 30 _egg = pyglet.sprite.Sprite(egg, x=cx, y=cy, batch=self.egg_batch) _egg.number = num _egg.scale = self.scale _egg.map_x, _egg.map_y = x, y self.eggs.append(_egg) def to_iso(self, x, y): screen_x = floor( (x - y) * (self.scale * self.tile_width / 2)) + self.fx screen_y = floor( (x + y) * (self.scale * self.tile_height / 2)) + self.fy return [screen_x, screen_y] def update(self, dt): redraw = False try: data = self.bucket.pop() except IndexError: pass else: if data[0] == 'bct': data.pop(0) x, y = int(data.pop(0)), int(data.pop(0)) list = [] for i in data: i = int(i) if i > 0: i = 1 list.append(i) self.print_objects(x, y, list) redraw = True elif data[0] == 'pnw': data.pop(0) self.print_player(int(data[1]), int(data[2]), int(data[0][1:])) redraw = True elif data[0] == 'ppo': data.pop(0) self.update_player(int(data[1]), int(data[2]), int(data[0][1:])) elif data[0] == 'pdi': data.pop(0) self.update_player(0, 0, int(data[0][1:]), dead=1) elif data[0] == 'enw': data.pop(0) self.add_egg(int(data[0][1:]), int(data[2]), int(data[3])) elif data[0] == 'eht' or data[0] == 'edi': data.pop(0) self.update_egg(int(data[0][1:])) if self.keyboard[key.Q]: pyglet.app.exit() fx = self.fx + (self.keyboard[key.RIGHT] - self.keyboard[key.LEFT]) * 350 * dt fy = self.fy + (self.keyboard[key.DOWN] - self.keyboard[key.UP]) * 350 * dt if fy != self.fy or fx != self.fx: self.fx = fx self.fy = fy redraw = True if redraw == True: self.print_map() self.print_all_objects() self.move_eggs() self.move_players() def on_draw(self): self.clear() self.tile_batch.draw() self.floor_batch.draw() self.egg_batch.draw() self.clients_batch.draw()
def __init__(self, dt=0.5, fullscreen=False, name='unnamed', iters=1000, magnify=1.): self.autoquit = False # om den ska stanga av nar resultaten ar uppnat self.frame = None # vad som ska synas self.subframes = None # mindre saker som ska synas self.visible_cars = [] # alla bilar som ska synas self.magnify = magnify # hur inzoomad kameran ska vara self.camera_center = None # center positionet av kameran self.name = name self.output = None self.iters = iters self.objects = [] # all objekt self.event_loop = pyglet.app.EventLoop() # event loop skapad av pyglet som forsoker ha 60hz self.window = pyglet.window.Window(600, 600, fullscreen=fullscreen, caption=name) # storleken av pyglet fonstret self.grass = pyglet.resource.texture('grass.png') # graset som ritas i varlden self.window.on_draw = self.on_draw # sager till den att rita fonstreet self.lanes = [] # alla lanes self.cars = [] # alla bilar self.dt = dt # delta_t, aka nuvarande tiden self.anim_x = {} # alla animationer self.prev_x = {} self.feed_u = None self.feed_x = None self.prev_t = None self.joystick = None self.keys = key.KeyStateHandler() # tar hand om input fran anvandare self.window.push_handlers(self.keys) # -||- self.window.on_key_press = self.on_key_press # -||- self.main_car = None # hittar main bilen self.heat = None # alla heat saker ar en heatmap for hur rewardsen ser ut self.heatmap = None self.heatmap_valid = False self.heatmap_show = False self.cm = matplotlib.cm.jet self.paused = False self.label = pyglet.text.Label( 'Speed human: ', font_name='Times New Roman', font_size=24, x=30, y=self.window.height-30, anchor_x='left', anchor_y='top' ) self.label2 = pyglet.text.Label( 'Speed robot: ', font_name='Times New Roman', font_size=24, x=30, y=self.window.height-60, anchor_x='left', anchor_y='top' ) # centrerar cemeran over 1 bil def centered_image(filename): img = pyglet.resource.image(filename) img.anchor_x = img.width/2. img.anchor_y = img.height/2. return img #ritar ut bilen def car_sprite(color, scale=0.15/600.): sprite = pyglet.sprite.Sprite(centered_image('car-{}.png'.format(color)), subpixel=True) sprite.scale = scale return sprite # ritar ut andra objekt def object_sprite(name, scale=0.15/600.): sprite = pyglet.sprite.Sprite(centered_image('{}.png'.format(name)), subpixel=True) sprite.scale = scale return sprite # alla bil sprites self.sprites = {c: car_sprite(c) for c in ['red', 'yellow', 'purple', 'white', 'orange', 'gray', 'blue', 'blue-dark', 'green']} # ala objekt sprites self.obj_sprites = {c: object_sprite(c) for c in ['cone', 'firetruck']}
def __init__(self, pos, speed=200.0, *args, **kwargs): super().__init__(*args, **kwargs) self.__pos = pos self.speed = speed self.__key_handler = key.KeyStateHandler()
class Constants(): SCREEN = Screens.TITLE # SCREEN = Screens.GAME # SCREEN = Screens.OPTIONS #CONVENIENCE VARIABLES IMG = pyglet.resource.image GRID = pyglet.image.ImageGrid ANIM = pyglet.image.Animation.from_image_sequence SPRITE = pyglet.sprite.Sprite LABEL = pyglet.text.Label #FLAGS #TODO, move the flags into enum classes #DEBUG DEBUG = False ALL_RED_MUSHROOMS = False ALL_GREEN_MUSHROOMS = False ALL_YOSHI_COINS = False ALL_PIRAHNA_PLANTS = False ALL_SPINY_BEETLES = False ALL_POW_BUTTONS = False ALL_BOMBOMBS = False #IMPORTANT LISTS #items ALL_ITEMS = [] ITEM_SPOTS = [] QUESTION_ITEM = [] #players ALL_PLAYERS = [] PLAYERS = [] PLAYER_SPOTS = [] #scores SCORE_DISPLAY = [] SCORE_SPOTS = [] #SETTINGS NUM_PLAYERS = 6 NUM_ITEMS = 9 GRADES = [1, 2, 3] PAGE_RANGE = [0, 500] MIN_OPACITY = 0 MAX_OPACITY = 255 FONT = "Comic Sans MS" FONT_SIZE = 24 BLACK = (0, 0, 0, 255) WHITE = (255, 255, 255, 255) FONT_COLOR = (0, 0, 0, 255) DIFFICULTY = Difficulty.SUPER_HARD ITEM_SCALE = 1.5 ITEM_START_LEFT = 216 #be careful changing this value ITEM_PLATFORM_H = 264 ITEM_PLATFORM_W = 300 ITEM_X_SPEED = 2 #set to 1 or 2 when not in debug mode ITEM_Y_SPEED = 1 PLAYER_X_SPEED = 3 PLAYER_Y_SPEED = 6 #PROBABILITIES #for 7 items, waiting to debug the 3 new ones (star, feather, question block) #[bombomb, pow button, spiny beetle, pirahna plant, yoshi coin, green mushroom, red mushroom] #actual ranges <-hard items easy items-> #probabilities (% of appearance) SUPER_EASY_RANGE = [1, 2, 3, 8, 18, 55, 100] # 1, 1, 1, 5, 10, 37, 45 EASY_RANGE = [2, 5, 10, 20, 35, 65, 100] # 2, 3, 5, 10, 15, 30, 35 MEDIUM_RANGE = [5, 10, 20, 35, 50, 75, 100] # 5, 5, 10, 15, 15, 25, 25 HARD_RANGE = [15, 30, 45, 60, 75, 90, 100] #15, 15, 15, 15, 15, 15, 10 SUPER_HARD_RANGE = [10, 20, 40, 60, 80, 90, 100] #10, 10, 20, 20, 20, 10, 10 #DRAWING SPRITES ANIMATION_BATCH = pyglet.graphics.Batch() BACKGROUND_BATCH = pyglet.graphics.Batch() GROUND_BATCH = pyglet.graphics.Batch() ITEM_BATCH = pyglet.graphics.Batch() MAIN_BATCH = pyglet.graphics.Batch() OPTIONS_BATCH = pyglet.graphics.Batch() PLAYER_BATCH = pyglet.graphics.Batch() PROBLEM_BATCH = pyglet.graphics.Batch() SCORE_BATCH = pyglet.graphics.Batch() TITLE_BATCH = pyglet.graphics.Batch() TITLE_BACKGROUND_BATCH = pyglet.graphics.Batch() YAMMY_BATCH = pyglet.graphics.Batch() #GAMEPLAY SETTINGS FRAME_SPEED = 1 / 90 GAME_WINDOW = pyglet.window.Window(1000, 563) KH = key.KeyStateHandler() # Key Handler GAME_WINDOW.push_handlers(KH) SCREEN_W = GAME_WINDOW.width SCREEN_H = GAME_WINDOW.height OFF_SCREEN_R = 1100 OFF_SCREEN_L = -100 FLOAT_H = 120 WALK_H = 63 MAIN_TIME = 0 POINT_X_OFFSET = 40 POINT_Y_OFFSET = 10 SCORE_SPRITE_Y = 0 MUSIC = True SCORES = True TIMER = True QUESTIONS = True #CHANGING POINTS OF FOCUS DURING GAMEPLAY P1 = None TRANSFER_ITEM = None #QUESTION SETTINGS NEW_QUESTION = None #MUSIC and SOUND EFFECTS # source = pyglet.media.load('explosion.wav') THEME_SONG = pyglet.media.load('./music/overworld_extended.mp3') MUSIC_PLAYER = pyglet.media.Player() MUSIC_PLAYER.volume = 0.4 MUSIC_PLAYER.loop = True MUSIC_PLAYER.queue(THEME_SONG) MUSIC_PLAYER.play()
def main(): global keyboard, scroller, old_ij, old_cell, old_highlighted_color from cocos.director import director director.init(width=600, height=300, autoscale=False, resizable=True) car_layer = layer.ScrollableLayer() car = cocos.sprite.Sprite('car.png') car_layer.add(car) car.position = (200, 100) car.max_forward_speed = 200 car.max_reverse_speed = -100 car.do(DriveCar()) scroller = layer.ScrollingManager() map_loaded = tiles.load('hexmap.tmx') # In Tiled we named 'tile_layer_1' our sample layer test_layer = map_loaded['tile_layer_1'] tint_green_hexmap_borders(test_layer) scroller.add(test_layer) scroller.add(car_layer) old_ij = 'nonexist' old_highlighted_color = None old_cell = None main_scene = cocos.scene.Scene(scroller) keyboard = key.KeyStateHandler() director.window.push_handlers(keyboard) def on_key_press(key, modifier): if key == pyglet.window.key.Z: if scroller.scale == .75: scroller.do(actions.ScaleTo(1, 2)) else: scroller.do(actions.ScaleTo(.75, 2)) elif key == pyglet.window.key.D: test_layer.set_debug(True) elif key == pyglet.window.key.Q: tint_red_hexmap_borders(test_layer) director.window.push_handlers(on_key_press) def on_mouse_motion(x, y, dx, dy): global scroller, old_ij, old_cell, old_highlighted_color #vh, vy = director.get_virtual_coordinates(x, y) vx, vy = scroller.screen_to_world(x, y) ij = test_layer.get_key_at_pixel(vx, vy) if ij == old_ij: return # restore color if old_cell: p, q = old_ij if old_highlighted_color is None: test_layer.set_cell_color(p, q, (255, 255, 255)) del old_cell.properties['color4'] else: test_layer.set_cell_color(p, q, old_highlighted_color[:3]) # record info and set color old_ij = ij i, j = ij print(i, j) old_cell = test_layer.get_cell(i, j) if old_cell is None: return old_highlighted_color = old_cell.properties.get('color4', None) test_layer.set_cell_color(i, j, (255, 0, 0)) director.window.push_handlers(on_mouse_motion) director.run(main_scene)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.key_handler = key.KeyStateHandler()
import pyglet from pyglet.window import key import math import random #import game files import Resources import Object_Functions global_key_handler = key.KeyStateHandler() #GENERAL PHYSICAL OBJECTS class PhyiscalObject(pyglet.sprite.Sprite): def __init__(self, x=0.0, y=0.0, *args, **kwargs): super().__init__(*args, **kwargs) #Location of object on screen self.x = x self.y = y #Velocity self.velocity_x = 0.0 self.velocity_y = 0.0 #Gravity self.gravity = 5 #Is object alive? self.dead = False self.destructable = True
def run(): # setup visualization and user input window = pyglet.window.Window(width=600, height=600, visible=False) keyboard = key.KeyStateHandler() window.push_handlers(keyboard) # help text label = pyglet.text.Label('ESC: quit, arrow-keys: move', font_size=20, x=window.width // 2, y=window.height // 20, anchor_x='center', anchor_y='center') # build simulation environment env = pymunk.Space() # build Rob the robot rob_mass = 1 # 1 kg rob_radius = 0.1 * M_TO_PIXELS # 0.1 meter radius, converted to pixels for display rob_I = pymunk.moment_for_circle(rob_mass, 0, rob_radius) # moment of inertia for disk rob_body = pymunk.Body(rob_mass, rob_I) rob_body.position = 300, 300 rob_shape = pymunk.Circle(rob_body, rob_radius) rob_shape.color = 255, 0, 0 # red # add Rob to the simulation env.add(rob_body, rob_shape) # define how to draw the visualization @window.event def on_draw(): # always clear and redraw for graphics programming window.clear() label.draw() pymunk.pyglet_util.draw(rob_shape) # this is gold right here # use keyboard to control Rob def process_user_input(dt): angular_vel = 0.2 * 2 * pi # rotations/sec -> radians/second angular_delta = angular_vel * dt linear_speed = 0.6 # m/s distance = linear_speed * dt * M_TO_PIXELS # m/s * s -> pixels # calculate linear displacement before updating rotation heading = unit_direction_vector(rob_body.angle) displacement = tuple([distance * x for x in heading]) # a discrete "jump" in space # direction if keyboard[key.RIGHT]: rob_body.angle -= angular_delta if keyboard[key.LEFT]: rob_body.angle += angular_delta if keyboard[key.UP]: rob_body.position += displacement if keyboard[key.DOWN]: rob_body.position -= displacement # update simulation at regular interval pyglet.clock.schedule_interval(env.step, 1.0 / 60) # process input at regular interval pyglet.clock.schedule_interval(process_user_input, 1.0 / 60) # start simulation window.set_visible(True) pyglet.app.run()
def __init__(self, dt=0.5, fullscreen=False, name='unnamed', iters=1000, magnify=1.): pyglet.resource.path = [PNG_PATH] self.visible_cars = [] self.magnify = magnify self.camera_center = None self.name = name self.objects = [] self.event_loop = pyglet.app.EventLoop() self.window = pyglet.window.Window(1800, 1800, fullscreen=fullscreen, caption=name) self.grass = pyglet.resource.texture('grass.png') self.window.on_draw = self.on_draw self.lanes = [] self.auto_cars = [] self.human_cars = [] self.dt = dt self.auto_anim_x = {} self.human_anim_x = {} self.mock_anim_x = [] self.obj_anim_x = {} self.prev_x = {} self.vel_list = [] self.main_car = None self.sess = None self.rounds = 0 self.turn_flag = 1 self.sec_turn_flag = 0 self.arrive_flag = 0 self.leader_list = [] self.SEKIRO = [] self.mock = [] self.timerounds = 0 self.finalcnnt = 0 self.controller = control.controller() self.doublecheck = [0 for i in range(5)] self.historical_mock = [] self.stop_flag = 0 def centered_image(filename): img = pyglet.resource.image(filename) img.anchor_x = img.width / 2. img.anchor_y = img.height / 2. return img def car_sprite(color, scale=0.17 / 600.): sprite = pyglet.sprite.Sprite(centered_image( '{}.png'.format(color)), subpixel=True) sprite.scale = scale return sprite def object_sprite(name, scale=0.15 / 900.): sprite = pyglet.sprite.Sprite(centered_image( '{}.png'.format(name)), subpixel=True) sprite.scale = scale return sprite self.sprites = { c: car_sprite(c) if c != 'black' else car_sprite(c, scale=0.2 / 600.) for c in ['red', 'white', 'gray', 'blue', 'black'] } self.obj_sprites = {c: object_sprite(c) for c in ['tree', 'firetruck']} self.keys = key.KeyStateHandler() self.window.push_handlers(self.keys) self.window.on_key_press = self.on_key_press
def __init__(self): self.createLayers() self.loadResources() self.window = pyglet.window.Window( width=1280, height=720, caption="Test", resizable=True ) self.window.push_handlers(self) self.debug_mode = False self.fps_display = pyglet.window.FPSDisplay(window=self.window) self.space = pymunk.Space() self.space.damping = 0 self.createCollisionHandlers() self.world_batch = pyglet.graphics.Batch() self.world_camera = source.camera.Camera( scroll_speed=0, min_zoom=0, max_zoom=float("inf") ) self.key_handler = key.KeyStateHandler() self.mouse_handler = mouse.MouseStateHandler() self.mouse_handler["x"] = 0 self.mouse_handler["y"] = 0 self.window.push_handlers(self.key_handler, self.mouse_handler) self.projectiles = [] self.enemies = [] self.player = source.player.Player(self) self.enemy_timer = 0 self.floor = {} for x in range(-c.WORLD_DIMENSIONS[0]//200, c.WORLD_DIMENSIONS[0]//200+1): for y in range(-c.WORLD_DIMENSIONS[1]//200, c.WORLD_DIMENSIONS[1]//200+1): self.floor[(x, y)] = pyglet.sprite.Sprite( img=self.resources["floor"], x=x*100, y=y*100, batch=self.world_batch, group=self.layers["floor"] ) self.borders = { "top": source.basic.Basic( self, -c.WORLD_DIMENSIONS[0]//2, c.WORLD_DIMENSIONS[1]//2, collider={ "type": "rect", "x": 0, "y": 0, "width": c.WORLD_DIMENSIONS[0]+100, "height": 100, "radius": 0, "id": c.COLLISION_TYPES["obstacle"] }, sprite=pyglet.shapes.Rectangle( x=0, y=0, width=c.WORLD_DIMENSIONS[0]+100, height=100, batch=self.world_batch, group=self.layers["obstacle"] ) ), "bottom": source.basic.Basic( self, -c.WORLD_DIMENSIONS[0]//2 - 100, -c.WORLD_DIMENSIONS[1]//2 - 100, collider={ "type": "rect", "x": 0, "y": 0, "width": c.WORLD_DIMENSIONS[0]+100, "height": 100, "radius": 0, "id": c.COLLISION_TYPES["obstacle"] }, sprite=pyglet.shapes.Rectangle( x=0, y=0, width=c.WORLD_DIMENSIONS[0]+100, height=100, batch=self.world_batch, group=self.layers["obstacle"] ) ), "left": source.basic.Basic( self, -c.WORLD_DIMENSIONS[0]//2 - 100, -c.WORLD_DIMENSIONS[1]//2, collider={ "type": "rect", "x": 0, "y": 0, "width": 100, "height": c.WORLD_DIMENSIONS[1]+100, "radius": 0, "id": c.COLLISION_TYPES["obstacle"] }, sprite=pyglet.shapes.Rectangle( x=0, y=0, width=100, height=c.WORLD_DIMENSIONS[1]+100, batch=self.world_batch, group=self.layers["obstacle"] ) ), "right": source.basic.Basic( self, c.WORLD_DIMENSIONS[0]//2, -c.WORLD_DIMENSIONS[1]//2 - 100, collider={ "type": "rect", "x": 0, "y": 0, "width": 100, "height": c.WORLD_DIMENSIONS[1]+100, "radius": 0, "id": c.COLLISION_TYPES["obstacle"] }, sprite=pyglet.shapes.Rectangle( x=0, y=0, width=100, height=c.WORLD_DIMENSIONS[1]+100, batch=self.world_batch, group=self.layers["obstacle"] ) ) } self._position_camera()
def __init__(self, refreshrate=240, *args, **kwargs): super(WinPygletGame, self).__init__(*args, **kwargs) self.icoords = [0,0] self.refreshrate = refreshrate self.angle = 0 self.angleYUpDown = 0 texturefile = "./textures/brick.png" self.texture = pyglet.image.load(texturefile).get_texture() #glClearColor(0.5, 0.69, 1.0, 1) glClearColor(0.902, 0.902, 1, 0.0) glLightfv(GL_LIGHT0, GL_POSITION, (0, 50, 0, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (0.2, 0.2, 0.2, 1.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.5, 0.5, 0.5, 1.0)) glEnable(GL_LIGHT0) glEnable(GL_LIGHTING) glEnable(GL_COLOR_MATERIAL) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) # most obj files expect to be smooth-shaded #glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE) glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) #glDisable(GL_TEXTURE_2D) #glEnable(GL_DEPTH_TEST) # glEnable(GL_BLEND) # glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # glEnable(GL_POINT_SMOOTH) # glHint(GL_POINT_SMOOTH_HINT, GL_NICEST) glEnable(GL_CULL_FACE) glCullFace(GL_FRONT) # so that objects do not appear to rotate self.map = WorldMap() self.selected_obj = len(self.map.objs) # added just to move around the world with mouse self.map.objs.append( OBJworld(name='world',x='',swapyz=False,id=0, rx=0, ry=0, tx=0, ty=0) ) #self.frame_times = [] #self.start_t = time.time() self.storeit = None self.rotate = False self.move = False self.zpos = 5 self.oo = self.map.objs[self.selected_obj] self.position = [30, 0, -65] self.rotation = [180, 0] self.angle = self.rotation[0] x, y = self.width // 2, self.height // 2 n = 10 self.reticle = pyglet.graphics.vertex_list(4, ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n)) ) self.text = None self.reticle_select_mode = True if self.reticle_select_mode: self.set_exclusive_mouse(True) self.mousebuttons = MouseStateHandler() self.push_handlers(self.mousebuttons) self.keyboard = key.KeyStateHandler() self.push_handlers(self.keyboard) self.start_press = 0 # on_key_press code to jump strafe self.just_jumped = 0 # on_key_press code to jump strafe self.lastbutton = None # on_key_press code to jump strafe self.fViewDistance_x_z = 0 # for zoom glulookat self.x = 0 self.y = 0 self.dx = 0 self.dy = 0 self.rapidFire = True pyglet.clock.schedule_interval(self.update, 1/refreshrate)
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.stimtype = 'image_sequence' #session_start self.session_start_time = datetime.datetime.now() # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved. self.accept('q', self.close) self.accept('Q', self.close) self.AUTO_REWARD = AUTO_REWARD # disable mouse control so that we can place the camera base.disableMouse() camera.setPosHpr(0, 0, 10, 0, -90, 0) mat = Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) # base.enableMouse() props = WindowProperties() props.setOrigin(1920, 0) props.setFullscreen(True) props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_relative) base.win.requestProperties(props) base.setBackgroundColor(0, 0, 0) # set the background color to black #set up the textures # we now get buffer thats going to hold the texture of our new scene altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024) # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8) # altBuffer = base.win.makeDisplayRegion() # altBuffer.makeDisplayRegion(0,1,0,1) # now we have to setup a new scene graph to make this scene self.dr2 = base.win.makeDisplayRegion(0, 0.1, 0, 0.1) altRender = NodePath("new render") # this takes care of setting up ther camera properly self.altCam = self.makeCamera(altBuffer) self.dr2.setCamera(self.altCam) self.altCam.reparentTo(altRender) self.altCam.setPos(0, -10, 0) self.bufferViewer.setPosition("llcorner") # self.bufferViewer.position = (.1,.4,.1,.4) self.bufferViewer.setCardSize(1.0, 0.0) print(self.bufferViewer.position) self.imagesTexture = MovieTexture("image_sequence") # success = self.imagesTexture.read("models/natural_images.avi") success = self.imagesTexture.read("models/movie_5hz.mpg") self.imagesTexture.setPlayRate(1.0) self.imagesTexture.setLoopCount(10) # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff") # self.imagesTexture.reparentTo(altRender) cm = CardMaker("stimwindow") cm.setFrame(-4, 4, -3, 3) # cm.setUvRange(self.imagesTexture) self.card = NodePath(cm.generate()) self.card.reparentTo(altRender) if self.stimtype == 'image_sequence': self.card.setTexture(self.imagesTexture, 1) # self.imagesTexture.play() # self.bufferViewer.setPosition("lrcorner") # self.bufferViewer.setCardSize(1.0, 0.0) self.accept("v", self.bufferViewer.toggleEnable) self.accept("V", self.bufferViewer.toggleEnable) # Load the tunnel self.initTunnel() #initialize some things # for the tunnel construction: self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH self.current_number_of_segments = 8 #task flow booleans self.in_waiting_period = False self.stim_started = False self.looking_for_a_cue_zone = True self.in_reward_window = False self.show_stimulus = False #for task control self.interval = 0 self.time_waiting_in_cue_zone = 0 self.wait_time = 1.83 self.stim_duration = 4.0 # in seconds self.max_stim_duration = 6.0 # in seconds self.stim_elapsed = 0.0 # in seconds self.last_position = base.camera.getZ() self.position_on_track = base.camera.getZ() #for reward control self.reward_window = 1.0 # in seconds self.reward_elapsed = 0.0 # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time self.reward_volume = REWARD_VOLUME # in uL, for the stepper motor self.reward_time = 0.1 # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling # self.lick_buffer = [] #INITIALIZE NIDAQ self.nidevice = 'Dev2' self.encodervinchannel = 1 self.encodervsigchannel = 0 self.invertdo = False self.diport = 1 self.lickline = 1 self.doport = 0 self.rewardline = 0 self.rewardlines = [0] self._setupDAQ() self.do.WriteBit(1, 1) self.do.WriteBit( 3, 1 ) #set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd) self.previous_encoder_position = self.ai.data[0][ self.encodervsigchannel] self.encoder_gain = -10 #INITIALIZE LICK SENSOR self._lickSensorSetup() #INITIALIZE output data self.lickData = [] self.x = [] self.t = [] self.trialData = [] self.rewardData = [] #INITIALIZE KEY SENSOR, for backup inputs and other user controls self.keys = key.KeyStateHandler() self.accept('r', self._give_reward, [self.reward_volume]) self.accept('l', self._toggle_reward) img_list = glob.glob('models/NaturalImages/*.tiff')[:10] print(img_list) self.imageTextures = [loader.loadTexture(img) for img in img_list] self._setupEyetracking() self._startEyetracking() if AUTO_MODE: self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2") self.rewardTask = taskMgr.add(self.rewardControl, "reward") self.cue_zone = concatenate((self.cue_zone,arange(\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH,\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-TUNNEL_SEGMENT_LENGTH-80,\ -1))) self.auto_position_on_track = 0 self.auto_restart = False self.auto_running = True self.contTunnel() else: # Now we create the task. taskMgr is the task manager that actually # calls the function each frame. The add method creates a new task. # The first argument is the function to be called, and the second # argument is the name for the task. It returns a task object which # is passed to the function each frame. self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus") self.lickTask = taskMgr.add(self.lickControl, "lick") self.rewardTask = taskMgr.add(self.rewardControl, "reward")
def __init__(self, xs, ys, playercontrolled): super().__init__(width=xs, height=ys, caption="Chrome Dino x Neural Network") self.dinobatch = pyglet.graphics.Batch() self.enemybatch = pyglet.graphics.Batch() self.backgroundbatch = pyglet.graphics.Batch() pyglet.font.add_file("resources/PressStart2P-Regular.ttf") self.font = pyglet.font.load('Press Start 2P', 16) RGBA = (255, 255, 255, 255) self.background = pyglet.image.SolidColorImagePattern( RGBA).create_image(self.width, self.height) self.counter = pyglet.window.FPSDisplay(window=self) self.counter.label.x = 20 self.counter.label.y = 340 self.counter.label.font_name = "Press Start 2P" self.counter.label.font_size = 15 self.counter.label.color = (83, 83, 83, 255) self.key_handler = key.KeyStateHandler() self.keyboard = [self, self.key_handler] self.score = 0 self.gameovertext = 0 self.gameobjects = [] self.eventstacksize = 0 self.successcount = 0 self.cinput = [False, False] self.nninput = { "dheight": None, "dwidth": None, "djumpheight": None, "dvdirection": None, "dcdistance": None, "cheight": None, "cwidth": None, "dbdistance": None, "bheight": None, "bwidth": None, "bypos": None, "gamespeed": None, } self.gameover = False self.playercontrolled = playercontrolled self.birdlocations = [20, 76, 175] self.distancewait = 30 self.wait = 0 self.cloudwaittime = 100 self.cloudwait = 0 self.basespeed = 30 self.gamespeed = 1 self.gameaccel = 0.0001 self.collided = False self.reset()
def __init__(self, *args, **kwargs): super(Player, self).__init__(*args, **kwargs) self.key_handler = key.KeyStateHandler() self.event_handlers = [self, self.key_handler] self.facing_x = 'East' self.facing_y = 'Neutral'
def __init__(self, width=800, height=600, caption="Would you like to play a game?"): self.levelname = sys.argv[-1] self.level = imp.load_source('happy', self.levelname + '.py') # Build the OpenGL / Pyglet Window self.window = pyglet.window.Window(width=width, height=height, caption=caption) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.keys = key.KeyStateHandler() # Create the Background self.background = pyglet.resource.image(self.level.background) self.background_x = 0 #Background music self.music = pyglet.media.load(self.level.music) self.music.play() #dictionary of hero sounds self.heroSounds = { "fire": pyglet.media.load(self.level.heroSoundFire, streaming=False) } self.heroSounds.update({ "win": pyglet.media.load(self.level.heroSoundWin, streaming=False) }) self.heroSounds.update({ "jump": pyglet.media.load(self.level.heroSoundJump, streaming=False) }) self.heroSounds.update({ "attack": pyglet.media.load(self.level.heroSoundAttack, streaming=False) }) self.heroSounds.update({ "death": pyglet.media.load(self.level.heroSoundDeath, streaming=False) }) #dictionary of enemy sounds self.enemySounds = { "death": pyglet.media.load(self.level.enemySoundDeath, streaming=False) } #keys pressed dictionary self.keys_pressed = { 'jump': False, 'left': False, 'right': False, 'attack': False, 'throw': False, 'sprint': False } #dictionary to hold all sprites self.SPRITES = {} #get hero pictures runImages = [] jumpImages = [] idleImages = [] deadImages = [] throwImages = [] attackImages = [] for i in range(10): runImages.append( pyglet.image.load("sprites/hero/Run (" + str(i + 1) + ").png")) jumpImages.append( pyglet.image.load("sprites/hero/Jump (" + str(i + 1) + ").png")) idleImages.append( pyglet.image.load("sprites/hero/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/hero/Dead (" + str(i + 1) + ").png")) throwImages.append( pyglet.image.load("sprites/hero/Throw (" + str(i + 1) + ").png")) attackImages.append( pyglet.image.load("sprites/hero/Attack (" + str(i + 1) + ").png")) self.SPRITES.update({ "hero": { "run": runImages, "jump": jumpImages, "idle": idleImages, "dead": deadImages, "throw": throwImages, "attack": attackImages } }) #get hero pictures runImages = [] idleImages = [] deadImages = [] attackImages = [] for i in range(8): runImages.append( pyglet.image.load("sprites/enemy-1/Run (" + str(i + 1) + ").png")) idleImages.append( pyglet.image.load("sprites/enemy-1/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/enemy-1/Dead (" + str(i + 1) + ").png")) attackImages.append( pyglet.image.load("sprites/enemy-1/Attack (" + str(i + 1) + ").png")) for i in range(8, 10): runImages.append( pyglet.image.load("sprites/enemy-1/Run (" + str(i + 1) + ").png")) idleImages.append( pyglet.image.load("sprites/enemy-1/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/enemy-1/Dead (" + str(i + 1) + ").png")) for i in range(10, 12): idleImages.append( pyglet.image.load("sprites/enemy-1/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/enemy-1/Dead (" + str(i + 1) + ").png")) for i in range(12, 15): idleImages.append( pyglet.image.load("sprites/enemy-1/Idle (" + str(i + 1) + ").png")) self.SPRITES.update({ "enemy1": { "run": runImages, "idle": idleImages, "dead": deadImages, "attack": attackImages } }) #get hero pictures runImages = [] idleImages = [] deadImages = [] attackImages = [] for i in range(8): runImages.append( pyglet.image.load("sprites/enemy-2/Run (" + str(i + 1) + ").png")) idleImages.append( pyglet.image.load("sprites/enemy-2/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/enemy-2/Dead (" + str(i + 1) + ").png")) attackImages.append( pyglet.image.load("sprites/enemy-2/Attack (" + str(i + 1) + ").png")) for i in range(8, 10): runImages.append( pyglet.image.load("sprites/enemy-2/Run (" + str(i + 1) + ").png")) idleImages.append( pyglet.image.load("sprites/enemy-2/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/enemy-2/Dead (" + str(i + 1) + ").png")) for i in range(10, 12): idleImages.append( pyglet.image.load("sprites/enemy-2/Idle (" + str(i + 1) + ").png")) deadImages.append( pyglet.image.load("sprites/enemy-2/Dead (" + str(i + 1) + ").png")) for i in range(12, 15): idleImages.append( pyglet.image.load("sprites/enemy-2/Idle (" + str(i + 1) + ").png")) self.SPRITES.update({ "enemy2": { "run": runImages, "idle": idleImages, "dead": deadImages, "attack": attackImages } }) runImages = [] for i in range(10): runImages.append( pyglet.image.load("sprites/weapon/Kunai (" + str(i + 1) + ").png")) self.SPRITES.update({"weapon": {"move": runImages}}) self.hero = Player(self.level.playerStartRow, self.level.playerStartCol, self.SPRITES["hero"], self.heroSounds) # Schedule player movements pyglet.clock.schedule_interval(self.movement, .02) self.window.push_handlers(self.keys) # Event Handler for drawing the screen @self.window.event def on_draw(): self.window.clear() self.background.blit(self.background_x, 0, height=height) self.level.drawBoard(self.level.level) self.level.drawBoard(self.level.goals) self.hero.sprite.draw() @self.window.event def on_key_press(symbol, modifiers): if symbol == key.SPACE or symbol == key.UP: self.keys_pressed['jump'] = True if symbol == key.LEFT: self.keys_pressed['left'] = True if symbol == key.RIGHT: self.keys_pressed['right'] = True if symbol == key.LALT or symbol == key.RALT: self.keys_pressed['attack'] = True if symbol == key.LCTRL or symbol == key.RCTRL: self.keys_pressed['throw'] = True if symbol == key.LSHIFT or symbol == key.RSHIFT: self.keys_pressed['sprint'] = True print(self.keys_pressed) @self.window.event def on_key_release(symbol, modifiers): if symbol == key.SPACE or symbol == key.UP: self.keys_pressed['jump'] = False if symbol == key.LEFT: self.keys_pressed['left'] = False if symbol == key.RIGHT: self.keys_pressed['right'] = False if symbol == key.LALT or symbol == key.RALT: self.keys_pressed['attack'] = False if symbol == key.LCTRL or symbol == key.RCTRL: self.keys_pressed['throw'] = False if symbol == key.LSHIFT or symbol == key.RSHIFT: self.keys_pressed['sprint'] = False print(self.keys_pressed)
def __init__(self, window=None): self.window = window self.keys = key.KeyStateHandler() self.window.push_handlers(self.keys)
from cocos.tiles import load, RectMapCollider from cocos.layer import ScrollingManager, ScrollableLayer, ColorLayer from cocos.director import director from cocos.scene import Scene from cocos.actions import Action from pyglet.window import key # For this scene, we'll be using a map with a high rectangular block that we don't want the player to be able to pass # Just as before, I start by initializing the director director.init(width=700, height=500, autoscale=False, resizable=True) # This is because, as stated before, many other objects depend on the director being initialized # And, one again, we set the keyboard and scrolling managers scroller = ScrollingManager() keyboard = key.KeyStateHandler() # I'll also throw in the line that pushes Cocos's handlers to the keyboard object director.window.push_handlers(keyboard) # We'll also load the tilemap here for clarity, as I will be using it in the class below map_layer = load("assets/platformer_map.xml")['map0'] # I use Cocos's XML spec for this map! Check it out if you want to see how to code your own Cocos style maps # This time we'll make an action that extends both the Action class and the new RectMapCollider # The RectMapCollider, you guessed it, lets us collide with rectmaps (A.K.A. tilemaps) class GameAction(Action, RectMapCollider): # To begin, we'll add a function for when the Action starts # I use the start function instead of an __init__ function because of the way the Action parent class is structured
game_window = pyglet.window.Window(1200, 700) t = 0 lable = pyglet.text.Label('Come On Baby', font_name='Times New Roman', font_size=36, x=game_window.width / 2, y=game_window.height / 2, anchor_x='center', anchor_y='center') image_s = pyglet.image.load('n.png') image_dabian = pyglet.image.load('h.png') man = pyglet.sprite.Sprite(img=image_s, x=500, y=0) #顯示位置 初始化遊戲主角 keys = key.KeyStateHandler() #獲取按键狀態 game_window.push_handlers(keys) #按鍵 dabian_lives = [] for i in range(5): rand_x = random.randrange(0, 1200, 1) new_sprite = pyglet.sprite.Sprite(img=image_dabian, x=rand_x, y=700) #顯示位置 new_sprite.scale = 0.3 #咚咚的大小 dabian_lives.append(new_sprite) #咚咚範圍 def check_bounds(self): if self.y < -100: rand_x = random.randrange(-200, 200, 10)
elif symbol == key.PAGEUP: env.unwrapped.cam_angle[0] = 0 elif symbol == key.ESCAPE: env.close() sys.exit(0) # Take a screenshot # UNCOMMENT IF NEEDED - Skimage dependency # elif symbol == key.RETURN: # print('saving screenshot') # img = env.render('rgb_array') # save_img('screenshot.png', img) # Register a keyboard handler key_handler = key.KeyStateHandler() env.unwrapped.window.push_handlers(key_handler) def update(dt): """ This function is called at every frame to handle movement/stepping and redrawing """ action = np.array([0.0, 0.0]) if key_handler[key.UP]: action = np.array([0.44, 0.0]) if key_handler[key.DOWN]: action = np.array([-0.44, 0])
def __init__(self, recent_files, drawing_specs, **kwargs): super().__init__(**kwargs, caption="Oldpaint", resizable=True, vsync=False) self.drawings = Drawings( [Drawing.from_spec(s) for s in drawing_specs or []]) self.tools = Selectable2({ tool: tool for tool in [ PencilTool, InkTool, PointsTool, SprayTool, LineTool, RectangleTool, EllipseTool, FillTool, SelectionTool, PickerTool ] }) self.brushes = Selectable([ RectangleBrush(1, 1), RectangleBrush(2, 2), RectangleBrush(3, 3), CircleBrush(8), EllipseBrush(20, 35), SquareBrush(20), ]) self.highlighted_layer = None # self.show_selection = False # Some gl setup self.copy_program = Program(VertexShader("glsl/copy_vert.glsl"), FragmentShader("glsl/copy_frag.glsl")) self.line_program = Program(VertexShader("glsl/triangle_vert.glsl"), FragmentShader("glsl/triangle_frag.glsl")) self.vao = VertexArrayObject() # All the drawing will happen in a thread, managed by this executor self.executor = ThreadPoolExecutor(max_workers=1) # Current stroke, if any self.stroke = None # Mouse cursor setup self.mouse_texture = ImageTexture(*load_png("icons/cursor.png")) self.mouse_position = None self.brush_preview_dirty = None # A hacky way to keep brush preview dirt away # Background texture #self.background_texture = ImageTexture(*load_png("icons/background.png")) # UI stuff self.icons = { name: ImageTexture(*load_png(f"icons/{name}.png")) for name in [ "selection", "ellipse", "floodfill", "line", "spray", "pencil", "picker", "points", "rectangle", "ink" ] } self.border_vao = VertexArrayObject(vertices_class=SimpleVertices) self.border_vertices = self.border_vao.create_vertices([((0, 0, 0), ), ((0, 0, 0), ), ((0, 0, 0), ), ((0, 0, 0), )]) self.selection_vao = VertexArrayObject(vertices_class=SimpleVertices) self.selection_vertices = self.selection_vao.create_vertices([ ((0, 0, 0), ), ((0, 0, 0), ), ((0, 0, 0), ), ((0, 0, 0), ) ]) self._new_drawing = None # Set when configuring a new drawing self.unsaved_drawings = None self._error = None self.recent_files = OrderedDict((k, None) for k in recent_files) self.window_visibility = { "edits": False, "colors": False, "color_editor": False, "metrics": False } # TODO this works, but figure out a way to exit automatically when the application closes. # @contextmanager # def blah(): # yield self.overlay # rect = self.overlay.dirty # self.drawing.update(self.overlay, rect) # self.overlay.clear(rect, frame=0) # Thread(target=start_ipython, # kwargs=dict(colors="neutral", user_ns={"drawing": self.drawing, "blah": blah})).start() self.plugins = {} init_plugins(self) # ways to directly access current keys and mouse buttons self.keys = key.KeyStateHandler() self.push_handlers(self.keys) self.mousebuttons = mouse.MouseStateHandler() self.push_handlers(self.mousebuttons) # Setup pressure sensitive drawing tablet (if available) self.tablet = TabletStateHandler(self) self._mru_cycling = False # Whether Alt+Tabbing through drawings