def __init__(self, int_screen, filename=''): if not filename: filename = str(CFG().start_level) with open(path.join(CFG().path_levels, filename), 'r') as file: level = loads(file.read()) self.int_screen = int_screen self.timer = 0 self.enemies = Group() self.enemy_hold = False self.show_name = False self.starting = True self.ending = False self.text = Text(int_screen, CFG().font_main, 16, (255, 255, 255)) self.layout = level['layout'] self.background = Background(self.int_screen, GFX().background[level['background']], type=level['background_type'], use_stars=level['stars'], lenght=len(self.layout)) self.story = Story(level['prestory'], level['poststory'], self.int_screen) self.next_level = level['nextlevel'] self.name = level['name'] self.music = level['music']
def __init__(self): # init event variables self.up_pressed = False self.down_pressed = False self.left_pressed = False self.right_pressed = False self.fire1_pressed = False self.fire2_pressed = False self.cancel_pressed = False self.up_released = False self.down_released = False self.left_released = False self.right_released = False self.fire1_released = False self.fire2_released = False self.cancel_released = False self.key_pressed = False # Gamepad self.gamepad = None self.gamepad_controls = {} if path.exists(CFG().path_gamepad): with open(CFG().path_gamepad, 'r') as file: self.gamepad_controls = loads(file.read()) if pygame.joystick.get_count() != 0 and self.gamepad_controls: self.gamepad = pygame.joystick.Joystick(0) self.gamepad.init()
def update(self, dt): """Updates ship movement and graphics""" # After shooting timer runs out remove shooting flag and reset ship image if self.shooting_timer < time(): self.shooting = False self.moving_center = True # Calculating ship movement and setting correct image if self.moving_left and self.rect.left > 0: self.pos_x -= CFG().ship_speed * dt self.image = GFX().ship['l_0'] self.mask = GFX().ship_mask['l_0'] elif self.moving_right and self.rect.right < self.screen_rect.right: self.pos_x += CFG().ship_speed * dt self.image = GFX().ship['r_0'] self.mask = GFX().ship_mask['r_0'] elif self.moving_center: self.image = GFX().ship['c_0'] self.mask = GFX().ship_mask['c_0'] self.moving_center = False # if shooting use special ship image if self.shooting: if self.moving_left: self.image = GFX().ship['l_1'] elif self.moving_right: self.image = GFX().ship['r_1'] else: self.image = GFX().ship['c_1'] # Apply ship movement self.rect.centerx = self.pos_x self.effects.update(dt)
def __init__(self, int_screen, image, type='flyby', use_stars=1, lenght=0): """ Inits level background, background types: flyby - image flies by exactly once on random x position repeat - image continually flies by on random x position, with short random pauses in repeat scroll - image scrolls continually from top to bottom, with no spaces in between and no randomness :param int_screen: screen surface :param image: background image :param type: background type :param use_stars: show random stars flying by :param lenght: lenght of the level lines """ self.background = image self.int_screen = int_screen self.back_rect = self.background.get_rect() self.use_stars = use_stars self.back_speed = 0.03 # set background type / animation, image position based on type if type in ['flyby', 'repeat']: if type == 'repeat': self.type = 2 else: self.type = 0 # calculate speed for fly-by times = lenght * CFG().spawn_speed self.back_speed = ( self.int_screen.get_rect().height + self.background.get_rect().height) / float(times) # random position on screen self.back_pos_y = 0.0 self.back_rect.bottom = 0 self.back_rect.centerx = randint(0, CFG().int_screen_width) elif type == 'scroll': self.type = 1 # Background image starts by already filling the entire screen self.back_rect.bottom = CFG().int_screen_height self.back_pos_y = float(self.back_rect.bottom) # and is aligned to left self.back_rect.left = 0 # Second rect is needed to draw to images on screen at once self.back_rect2 = self.back_rect.copy() self.back_rect2.bottom = self.back_rect.top self.back_pos2_y = float(self.back_rect2.bottom) # init stars if needed if self.use_stars: self.stars = Group() stars.generate_init_stars(self.stars, 20, self.int_screen, 180) self.gen_speed = 0.1 self.stars_timer = time() + self.gen_speed
def main(): """Entrance Function""" tornado_app = web.Application(handlers=routes, **O_O.application) tornado_server = httpserver.HTTPServer(tornado_app, **O_O.httpserver) tornado_server.listen(O_O.server.port) print('start listen...') O_O.show() ioloop.IOLoop.instance().start()
def main(): """Entrance Function""" controllers.load_controllers() for r in ROUTES: print(f'{r[0]:30s} {r[1]}') app = web.Application(handlers=ROUTES, **O_O.application) app.listen(O_O.server.port, **O_O.httpserver) print('\nstart listen...') O_O.show() ioloop.IOLoop.instance().start()
def music_play(self, song, loop=True): mixer.music.load(SFX().music[song]) mixer.music.set_volume(CFG().music_volume) if loop: mixer.music.play(-1) else: mixer.music.play(0)
def __init__(self, pos_x): """Init asteroid - square sprite with random image and rotation speed""" super(Asteroid, self).__init__() self.movement_speed = CFG().asteroid_small_speed # Stats self.health = 100 self.reward = 100 self.pickup = None # Select random asteroid image self.i = randint(0, len(GFX().asteroids)-1) self.image = GFX().asteroids[self.i][0] # Set starting position self.rect = self.image.get_rect() self.rect.centerx = pos_x self.rect.bottom = 0 self.size = self.rect.height self.timer = 0 self.num_frames = len(GFX().asteroids[self.i]) # Gen number of animation frames self.frame = randint(0, self.num_frames-1) # Current frame number of animation - set random one self.rotation_speed = uniform(0.08, 0.2) # time in seconds between animation frames self.direction = choice([1, -1]) self.image = GFX().asteroids[self.i][self.frame] self.mask = GFX().asteroids_mask[self.i][self.frame]
def show_loading(screen): """Show loading screen, renders independently on rest of the game""" text = gfx.Text(screen, CFG().font_main, 16, (255, 255, 255)) screen.fill((0,0,0)) rect = screen.get_rect() text.write('now loading...', rect.centerx, rect.centery, (255,255,255), origin='center') pygame.display.flip()
def pickup(self, status): """ Perform 'pickup process': add lives or score and remove pickup """ if status.lives < CFG().max_lives: status.lives += 1 else: status.score += 1000 self.kill()
def update_screen(screen, int_screen, hud): """Update images on the screen and flip to the new screen.""" screen.fill((25,25,25)) # Scale internal screen if CFG().scaling: int_screen = pygame.transform.scale(int_screen, (CFG().int_scale_width, CFG().int_scale_height)) # And put it on screen rect = int_screen.get_rect() rect.center = screen.get_rect().center screen.blit(int_screen, rect) # Draw HUD hud.draw() # Flip buffer pygame.display.flip()
def fire_bullet(self): # Set shooting flag self.ship.shooting = True # Set shooting timer self.ship.shooting_timer = time() + 0.1 # Add bullet if len(self.bullets) < CFG().bullet_count: self.bullets.add(Bullet(self.ship)) SFX().blaster1.play()
def update(self, dt, pause): """ Background update """ # Type flyby if self.type == 0: if not pause: self.back_pos_y += self.back_speed * (dt / 1000.0) self.back_rect.bottom = self.back_pos_y # Type scroll elif self.type == 1: # Move images self.back_pos_y += self.back_speed * dt self.back_pos2_y += self.back_speed * dt self.back_rect.bottom = self.back_pos_y self.back_rect2.bottom = self.back_pos2_y # If rect 1 bellow screen move rect to the top if self.back_rect.top > CFG().int_screen_height: self.back_rect.bottom = self.back_rect2.top self.back_pos_y = self.back_rect.bottom # If rect 2 bellow screen move rect to the top if self.back_rect2.top > CFG().int_screen_height: self.back_rect2.bottom = self.back_rect.top self.back_pos2_y = self.back_rect2.bottom # Type repeat elif self.type == 2: # If rect bellow set new random position on top if self.back_rect.top > CFG().int_scale_height: self.back_rect.centerx = randint(0, CFG().int_screen_width) self.back_pos_y = randint(0, CFG().int_screen_height / 2) * -1 # move image self.back_pos_y += self.back_speed * dt self.back_rect.bottom = self.back_pos_y # Stars if self.use_stars: self.stars.update(dt) # Add stars if self.stars_timer < time(): self.stars_timer = time() + self.gen_speed self.stars.add(stars.Star(self.int_screen, 180))
def __init__(self): self.game_running = False self.dead = False self.new_hs = False self.show_hs = False self.dead_timer = 0 self.lives = CFG().start_lives self.boss_lives = 0 self.score = 0 self.level = CFG().start_level self.high_scores = [['1', 10000], ['2', 9000], ['3', 8000], ['4', 7000], ['5', 6000], ['6', 5000], ['7', 4000], ['8', 3000], ['9', 2000]]
def update(self, dt): """Calculate position and move bullet""" if self.speedx != 0: self.pos_x += self.speedx * dt self.rect.x = self.pos_x self.pos_y += self.speedy * dt self.rect.y = self.pos_y if self.rect.top > CFG().int_screen_height: self.kill()
def load_story(self): ''' Loads all story images from story.pak (tar.gz file) :return: Dictionary {'filename w/o extension': image} ''' story = {} with tarfile.open(path.join(CFG().path_gfx, 'story/story.pak'), 'r:gz') as storytar: for file in storytar.getnames(): name = file.split('.')[0] story[name] = image.load(storytar.extractfile(file)).convert() return story
def load(self): """ Load Game status from file """ try: with open(CFG().path_save, 'r') as file: data = loads(file.read()) self.lives = data['lives'] self.score = data['score'] self.level = data['level'] self.high_scores = data['hscores'] except IOError: print 'Can\'t load saved game and high scores'
def __init__(self): # Sound effects self.blaster1 = mixer.Sound(path.join(CFG().path_sfx, 'blaster1.ogg')) self.blaster1.set_volume(CFG().sfx_volume) self.blaster2 = mixer.Sound(path.join(CFG().path_sfx, 'blaster2.ogg')) self.blaster2.set_volume(CFG().sfx_volume) self.boom1 = mixer.Sound(path.join(CFG().path_sfx, 'boom1.ogg')) self.boom1.set_volume(CFG().sfx_volume) # Music self.music = {} self.music['arpent'] = path.join(CFG().path_music, 'arpent.ogg')
def update_bullets(self, dt): """Manage bullets""" self.bullets.update(dt) self.enemy_bullets.update(dt) # Get rid of bullet out of screen for bullet in self.bullets: if bullet.rect.bottom <= 0: self.bullets.remove(bullet) for bullet in self.enemy_bullets: if bullet.rect.top >= CFG().int_screen_height: self.enemy_bullets.remove(bullet)
def __init__(self, ship): super(Bullet, self).__init__() # Create bullet at the correct position self.image = GFX().bullets[0] self.mask = GFX().bullets_mask[0] self.rect = self.image.get_rect() self.rect.centerx = ship.rect.centerx self.rect.bottom = ship.rect.top # Attributes self.pos_y = float(self.rect.y) self.speed = CFG().bullet_speed
def save(self): """ Save Game status to file """ data = {'lives': self.lives, 'score': self.score, 'level': self.level, 'hscores': self.high_scores} js_data = dumps(data, indent=4, separators=(',', ': ')) try: with open(CFG().path_save, 'w') as file: file.write(js_data) except IOError: print 'Can\'t save game and high scores'
def __init__(self, int_screen, status): """ Init text, set dimensions :param int_screen: Internal screen :param status: Game status :param s: Game settings """ self.int_screen = int_screen self.status = status self.font = Text(self.int_screen, CFG().font_main, 16, (255, 255, 255)) self.y = 40 self.spacing = 25 self.x_name = 230 self.x_score = 320
def draw_lives(self): x = self.lives_x lives = self.status.lives for a in range(CFG().max_lives): if lives != 0: self.screen.blit( GFX().hud_lives[0], (x, self.lives_y, self.lives_size, self.lives_size)) lives -= 1 else: self.screen.blit( GFX().hud_lives[1], (x, self.lives_y, self.lives_size, self.lives_size)) x += 22
def __init__(self, int_screen, status): """ Init dialog :param int_screen: Internal screen :param status: Game status :param s: Game settings """ self.int_screen = int_screen self.status = status self.letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!' self.name = '' self.cursor = 0 self.done = False self.highlight_color = (100, 100, 100) self.name_position = [320, 150] self.title = 'New high score!' self.title_position = [320, 50] self.x = 50 self.y = 220 self.font1 = Text(self.int_screen, CFG().font_main, 16, (255, 255, 255)) self.font2 = Text(self.int_screen, CFG().font_main, 40, (255, 255, 255)) self.cursor_surf = pygame.Surface((20, 20)) self.cursor_surf.fill(self.highlight_color) self.cursor_rect = self.cursor_surf.get_rect() self.cursor_rect.top = self.y - 3 self.cursor_rect.left = self.x - 3 self.highlight_surf = pygame.Surface((130, 50)) self.highlight_surf.fill(self.highlight_color) self.highlight_rect = self.highlight_surf.get_rect() self.highlight_rect.top = self.name_position[1] - 29 self.highlight_rect.left = self.name_position[0] - 69
def update(self): # If dead and timer elapsed - stop game if self.dead and self.dead_timer < time(): self.game_running = False return if self.lives == 0: # Add score to high scores - if high enough if self.score > self.high_scores[-1][1]: self.new_hs = True self.lives = CFG().start_lives self.dead = True self.show_hs = True self.dead_timer = time() + 3
def draw(self): if self.status.game_running: self.draw_lives() self.draw_boss_lives() self.text.write(str(self.status.score).zfill(8), self.score_x, self.score_y, origin='center') if self.status.dead: self.text.write('Game Over', self.rect.width / 2, self.rect.height / 2, origin='center') if CFG().show_fps: self.text.write(str(int(self.clock.get_fps())), 5, 5)
def __init__(self, status, screen, clock): self.status = status self.screen = screen self.rect = screen.get_rect() self.clock = clock self.text = Text(self.screen, CFG().font_main, 16, (255, 255, 255)) bottom_border = CFG().screen_height - ( (CFG().screen_height - CFG().int_scale_height) / 4) # Score position self.score_x = CFG().screen_width / 2 self.score_y = bottom_border # Lives position self.lives_size = GFX().hud_lives[0].get_rect().width self.lives_x = 20 self.lives_y = bottom_border - (self.lives_size / 2) # Boss lives position self.boss_x = CFG().screen_width / 2 self.boss_y = ((CFG().screen_height - CFG().int_scale_height) / 6) self.boss_rect = GFX().progressbar[0].get_rect()
def update(self, dt): """ Update movement and animation """ # If time between frames elapsed - set image of the sprite to the next frame if self.timer < time(): self.timer = time() + self.animation_speed self.frame += 1 # loop animation if self.frame == self.num_frames: self.frame = 0 self.image = self.animation[self.frame] # move the asteroid self.rect.bottom += self.movement_speed * dt # remove pickup when off screen if self.rect.top > CFG().int_screen_height: self.kill()
def __init__(self, start_story, end_story, screen): """ Init Story :param start_story: list of dict containing image name, time in seconds, and text :param end_story: list of dict containing image name, time in seconds, and text :param screen: surface to show the story on """ self.start_story = start_story self.end_story = end_story self.screen = screen self.font = Text(self.screen, CFG().font_main, 11, (255, 255, 255), True) self.story_image = None self.story_timer = 0 self.story_text = '' rect = self.screen.get_rect() self.text_x = rect.width / 2 self.text_y = rect.height - (rect.height / 16)
def main(): """Esign DB program main function.""" handlers = [ (r'/', IndexHandler), (r'/text', TextHandler), (r'/back/api/explain', TextHandler), (r'/test(?P<path>.*)?', TestHandler), (r'/service-worker.js', ServiceWorkerHandler), ] handlers += [(f'/middle{handler[0]}', handler[1]) for handler in HANDLER_LIST] # handlers += PAY_URLS tornado_app = web.Application( handlers=handlers, template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), cookie_secret='QiNDQXm6ReOfl1VOGhdLoZ0f3ZucyEg6psGNLu1tWZE=', ) tornado_server = httpserver.HTTPServer( tornado_app, xheaders=True, ) # if options.port == 0: # options.port = config.server.port # else: # config.server.port = options.port tornado_server.listen(config.server.port) print('start listen...') sys.stdout.write('\nconfig:\n') json.dump(config.traverse(), sys.stdout, indent=4, sort_keys=True) sys.stdout.write('\n\n\n') sys.stdout.flush() ioloop.IOLoop.instance().start()