def __init__(self, _parent=None): self.parent = _parent # Containers self.game_objects = {} self.game_doors = {} self.game_objects_np = render.attachNewNode("Game_Objects") self.game_doors_np = render.attachNewNode("Player_Doors") self.game_doors_np.setPos(0, 0, 0) self.game_counter_node = None self.game_collector_nodes = [] self.redDudesCount = 0 self.blueDudesCount = 0 # Physics world self.physics_world = None self.builder = Builder(self) # level lights self.directLight = None # Dude class self.dude = None self.spawnPoints = self.builder.spawnPoints # HUD self.hud = Hud() # Lightshow self.elapsed = 0.0
def start_loop(self): """Loop for start screen""" selected = False background = Background(START_BG, [0, 0]) top_score = Hud(10, 350, 200, 40, "TOP SCORE") def launch_game(): nonlocal selected selected = True self.game_loop() while not selected: for event in pygame.event.get(): if event.type == pygame.QUIT: selected = True top_score.prop = self.scores.top_score self.clock.tick(20) pygame.mouse.set_visible(True) self.screen.blit(background.image, background.rect) large_text = pygame.font.Font('freesansbold.ttf', 80) text_surf, text_rect = text_objects("OMEGA!", large_text, (210, 208, 224)) text_rect.center = ((self.screen_width / 2), (self.screen_height / 2.75)) self.screen.blit(text_surf, text_rect) top_score.update(dest=self.screen) button('PLAY', ((self.screen_width / 2) - 50), 240, 100, 40, ((37, 31, 71), (108, 100, 153), (210, 208, 224)), self.screen, launch_game)
def __init__(self, virtual_width, virtual_height, map_height, map_width): self.v_rect = pygame.Rect(0, 0, virtual_width, virtual_height-config.hud_size) self.map_rect = pygame.Rect(0, 0, map_width, map_height) self.hud_rect = pygame.Rect(0, virtual_height-config.hud_size, virtual_width, config.hud_size) self.map_layer = [] self.map_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h)) self.item_layer = [] self.item_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA) self.unit_layer = [] self.unit_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA) self.unit_action_surf = pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA) self.hud = Hud(0, virtual_height-config.hud_size, virtual_width, config.hud_size, self) self.hud_surf = pygame.Surface((self.hud_rect.w, self.hud_rect.h)) self.hud_surf.fill(pygame.Color("#737373")) self.hud_font = pygame.font.Font("assets/bitwise/bitwise.ttf", 25) self.dirty = 1 self.font = pygame.font.Font(None, 20) self.mouse_events = []
def run_game(): pygame.init() m_settings = Settings() stats = Estadisticas(m_settings) fj.cargar_puntuacion(stats) screen = pygame.display.set_mode((m_settings.screen_width, m_settings.screen_height)) #dibujar pantalla nave = Nave(screen, m_settings) #Dibujar nave balas = Group() #Un grupo es una lista con funciones añadidas marcianitos = Group() fj.crear_flota(m_settings, screen, nave, marcianitos) icon = pygame.image.load("images/alien.bmp") pygame.display.set_icon(icon) pygame.display.set_caption("Marcianitos") boton = Boton(m_settings, screen, "Jugar") hud = Hud(m_settings, screen, stats) m.musica_fondo() while True: fj.comprobar_eventos(m_settings, screen, nave, balas, stats, marcianitos, boton) if stats.jugando: nave.actualizar_posicion(m_settings) fj.actualizar_balas(m_settings, screen, nave, marcianitos, balas, stats, hud) fj.actualizar_flota(m_settings, stats, screen, balas, marcianitos, nave, hud) fj.actualizar_pantalla(m_settings, screen, nave, marcianitos, balas, boton, stats, hud)
def __init__(self, dir_sprites, dir_sounds, dir_fonts, lifes=constants['MAX_PLAYER_LIFES'], hjump=constants['INITIAL_PLAYER_HJUMP'], gravity=constants['INITIAL_PLAYER_GRAVITY'], position=list(constants['START_POSITION_PLAYER'])): self.hud = Hud(dir_sprites, dir_fonts, lifes=lifes) self.sprites = { 'wait': pygame.image.load(dir_sprites['player_wait']).convert_alpha(), 'run': pygame.image.load(dir_sprites['player_run']).convert_alpha(), 'hurt': pygame.image.load(dir_sprites['player_hurt']).convert_alpha() } #the following attribute will be modified in method _run... self.sprite_base = self.sprites['wait'] self.sounds = { 'score_plus': pygame.mixer.Sound(dir_sounds['sound_player_score_plus']) } self.attributes = { 'hjump': hjump, 'gravity': gravity, 'position': position }
def init_game(): """ Инициализирует игру и создает объект экрана""" pygame.init() global screen screen = pygame.display.set_mode( (game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption("Aliens") # Создание кнопки Play global play_button play_button = Button(game_settings, screen, "Play") global hud hud = Hud(game_settings, screen, stats) # Создание корабля global ship ship = Ship(game_settings, screen) # Создание группы для хранения пуль global bullets bullets = pygame.sprite.Group() # Создание пришельцев global aliens aliens = pygame.sprite.Group() # Создание флота пришельцев create_fleet()
def postInit(self): # # initialize game content # base.cTrav = CollisionTraverser("base collision traverser") base.pusher = CollisionHandlerPusher() self.menu = Menu() self.credits = Credits() self.charSelection = CharacterSelection() self.levelSelection = LevelSelection() self.koScreen = KoScreen() self.hud = Hud() self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg") self.menuMusic.setLoop(True) self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg") self.fightMusic.setLoop(True) base.audio3d = Audio3DManager(base.sfxManagerList[0], camera) # # Event handling # self.accept("escape", self.__escape) # # Start with the menu # self.request("Menu")
def __init__(self) -> None: self.game_objects = { "check": [], "switch": [], "robot": [], "platform": [], "laser": [], "shot": [], "gate": [], "plr": [self.plr], "hud": [Hud(self)] } self.game_data = {} pyxel.init(SCREEN_WIDTH, SCREEN_HEIGHT, caption="Jumpstick robo") pyxel.load( os.path.join(os.path.dirname(__file__), 'assets', 'jumpy_robot.pyxres'), ) self.load_objects() first_check = self.game_objects["check"][0] first_check.activate() self.plr.current_checkpoint = first_check self.plr.kill(True) self.plr.current_checkpoint.restore() self.game_data = json.loads(game_data) self.update_gate_status() self.draw_state = self.draw_title self.update_state = self.update_title pyxel.run(self.update, self.draw)
def __init__(self): ShowBase.__init__(self) pman.shim.init(self) #props = WindowProperties() #props.setCursorHidden(True) #props.setMouseMode(WindowProperties.M_relative) #base.win.requestProperties(props) base.disableMouse() self.mouse = [0, 0] self.setFrameRateMeter(True) self.win.setClearColor((0, 0, 0, 1)) self.cTrav = CollisionTraverser() self.cTrav.setRespectPrevTransform(True) self.delay = [0, 5] base.win.display_regions[1].dimensions = (0, 1, 0.25, 1) render.setShaderAuto() self.music = None self.shuffleSong() self.mode = "edit" self.defineKeys() self.hud = Hud(self) self.road = RoadMan(self) self.road.enableEditing() self.spawn() self.taskMgr.add(self.update)
def start_game(self): self.logger.info("STARTGAME") self.tank = tanks[self.cl_id] self.hud = Hud() self.camera = Camera() self.camera.init_gl(Game.WIDTH, Game.HEIGHT) self.on_resize = self.camera.on_resize self.bg_player.play() self.running = True self.gui.remove(self.stack)
def get_new_game(): scene = Scene() game = Game() hud = Hud() end_game = EndGame() game_ctrl = GameCtrl(game, hud, end_game) scene.add(game, z=0, name="game layer") scene.add(game_ctrl, z=1, name="game control layer") scene.add(hud, z=2, name="hud layer") scene.add(end_game, z=3, name="end game layer") return scene
def initAttr(self): self.turn = True self.hudWidth = HUD["HUD_WIDTH"] self.edgeWidth = GAME["EDGE_WIDTH"] # 先获取 board 部分的大小,再自适应自己的大小 self.board = Board((self.hudWidth, self.edgeWidth)) Div.__init__(self, (self.board.width + self.hudWidth, self.board.height + self.edgeWidth * 2)) # 根据窗口高度设置 HUD 高度 self.hud = Hud((0, self.height), (0, 0)) self.hud.setMark(self.turn) self.board.setTurn(self.turn) self.gameID = 0 self.order = None
def __init__(self): GameBase.__init__(self, debug=False) FSM.__init__(self, "GUI FSM") base.disableMouse() self.menu = Menu() self.missionScreen = MissionScreen() self.debrief = Debrief() self.hud = Hud() self.missionSelect = MissionSelect() base.camLens.setFov(90) self.setMusic("audio/music.mp3", volume=0.5) self.setMusic("audio/engine1.wav", volume=0.3) self.request("Menu") base.taskMgr.add(self.missionOverTask, "is mission over")
def load(self): super().load() blockWidth = blocks.Block.width blockHeight = blocks.Block.height self.gameArea = Rect(Game.curGame.width - blockWidth, Game.curGame.height - Hud.height, 0, 0) if (self.len() == 0): self.generateMap() playerStartX = blockWidth playerStartY = blockHeight self.player = characters.EditCursor(playerStartX, playerStartY) # Add player self.addGameObject(self.player, 1) self.addGameObject(Hud(blockWidth, self.gameArea.height + blockHeight))
def restart(self, game_data): """Start a new game with the current game_data""" self.game_data = game_data self.state = MonorailGame.STATE_INTRO self.scenario = self.game_data.get_quest().create_scenario( self.game_data.skill_level.value) self.playfield = self.scenario.playfield self.controller = ctrl.GroundControl(self.playfield) self.init_goldcars() self.hud = Hud(self.scenario, self.controller, self.game_data) self.hud.start_intro_screen() self.begin_timeout = 25 * 3 self.ingame_menu = None self.gui_state = GuiState() self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT self.is_paused = False
def load(self): super().load() blockWidth = blocks.Block.width blockHeight = blocks.Block.height self.gameArea = Rect(Game.curGame.width - blockWidth, Game.curGame.height - Hud.height, 0, 0) playerStartX = blockWidth playerStartY = blockHeight # If there are playerSpawn blocks if (self.hasAny(blocks.PlayerSpawn)): # Get the location of the block playerSpawn = self.getGameObjectsByType(blocks.PlayerSpawn) # Create a player if there is not one already if not (self.player): self.player = characters.Player(playerStartX, playerStartY) # Spawn the player on the block self.player.x = playerSpawn[0].x self.player.y = playerSpawn[0].y self.removeGameObjectsByType(blocks.PlayerSpawn) self.addGameObject(self.player) # If there are not Player Objects create one elif (not self.hasAny(characters.Player)): if not (self.player): self.player = characters.Player(0, 0) self.player.x = playerStartX self.player.y = playerStartY self.addGameObject(self.player) # If there are Player Objects elif (self.hasAny(characters.Player)): self.player = self.getGameObjectsByType(characters.Player)[0] self.addGameObject(Hud(blockWidth, self.gameArea.height + blockHeight)) self.originalGos = self.gameObjects
def setup_hud(self): self.hud = Hud(entities=self.entities) self.hud.add_counter('clock', 'hud/clock.png') self.hud.add_counter('pigeons', 'hud/pigeon.png') self.hud.add_counter('sticks', 'hud/stick.png') self.hud.hide()
def main(): """ Main Program """ pygame.init() # Set the height and width of the screen size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Dungeon Dreams Demo") # Create the player map_pix_size = 30 # Create all the levels level_list = [] # level_list.append( Level_01(player) ) # Set the current level current_level_no = 0 current_level = 0 # current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() all_sprites_list = pygame.sprite.LayeredDirty() collid_list = pygame.sprite.LayeredDirty() mobiles_list = pygame.sprite.Group() m_attacks = pygame.sprite.Group() area = None image_files = glob.glob('HumanMage.PNG') hud = Hud(screen) player = Player(100, 100, image_files, hud) hud.display_player_stats(player.stats) player.set_all_sprites(all_sprites_list) screen_size = (screen.get_width(), screen.get_height()) m_fact = Monster_Factory(area, collid_list, 50, screen_size, all_sprites_list, player) map_tool = Map_Handler(screen, all_sprites_list, collid_list, player, mobiles_list, m_fact, hud) map_tool.build_area() item_fact = map_tool.get_item_fact() shift_x = 0 shift_y = 0 all_mobiles = m_fact.get_mobiles_group() dam_mod = 1 #init path finding... path_finder = a_star(collid_list, 50) player.group_add(all_mobiles) image_files = glob.glob('*.PNG') #init events for following and monsters, start at 3 seconds because #player needs a second or two catch bearings FOLLOW_EVENT = USEREVENT + 1 M_ATTACK_EVENT = USEREVENT + 2 pygame.time.set_timer(FOLLOW_EVENT, 3000) pygame.time.set_timer(M_ATTACK_EVENT, 3000) game_start = False #-------- Main Program Loop ----------- while not done: #Probably would make a class just to handle #client events. #These handle the movements keys = pygame.key.get_pressed() if keys[pygame.K_h]: player.changespeed(-1, 0) if keys[pygame.K_l]: player.changespeed(1, 0) if keys[pygame.K_k]: player.changespeed(0, -1) if keys[pygame.K_j]: player.changespeed(0, 1) if keys[pygame.K_n]: player.changespeed(1, 1) if keys[pygame.K_b]: player.changespeed(-1, 1) if keys[pygame.K_y]: player.changespeed(-1, -1) if keys[pygame.K_u]: player.changespeed(1, -1) #More events, quit and attacks and stopping the player #when the button goes up. for event in pygame.event.get(): if event.type == pygame.QUIT: done = True player.check_events(event) if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: r_attack = player.ranged_attack(all_sprites_list, None, player.r_attack_images, dam_mod) m_fact.set_check_attack(r_attack) if event.type == pygame.KEYUP: if event.key == pygame.K_h: player.stop() if event.key == pygame.K_y: player.stop() if event.key == pygame.K_k: player.stop() if event.key == pygame.K_u: player.stop() if event.key == pygame.K_l: player.stop() if event.key == pygame.K_n: player.stop() if event.key == pygame.K_j: player.stop() if event.key == pygame.K_b: player.stop() #Really for testing pathfinding, pathfinding is really for monsters. if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() player.follow_path(path_finder.get_path(player.get_pos(), pos), map_pix_size, pos) #Monsters follow every two seconds to cut down on pathfinding #Calculations if event.type == FOLLOW_EVENT: m_fact.monster_group_follow(player.get_pos()) pygame.time.set_timer(FOLLOW_EVENT, 2000) #Attack every second which is kind of a lot still #Otherwise player would get hurt too fast or too slow. if event.type == M_ATTACK_EVENT: m_attacks = m_fact.monsters_attack(player.get_pos()) player.set_check_attack(m_attacks) pygame.time.set_timer(M_ATTACK_EVENT, 1000) #Move the player and then check for game end or picked up item. player_pos = player.move(collid_list, all_mobiles) lost = player.damaged() m_fact.move_monsters(all_mobiles) got_item = item_fact.is_picked_up() #For now just one item and if it is picked up the player wins. if got_item: end_text = [] end_text.append( 'You Found the Scepter of Yendor and Won the Game!') end_text.append('To replay press r!') end_text.append('To quit press q!') end_text.append('To continue press Space Bar!') done = game_end(True, end_text, screen, map_tool) map_tool.map_move(0, 0) player.stop() player.ranged_item = 3 player.speed = 8 player.dam_mod = 10 elif (lost): end_text = [] end_text.append('You perished!') end_text.append('To replay press r!') end_text.append('To quit press q!') done = game_end(False, end_text, screen, map_tool) if (map_tool.map_section_change(player_pos)): area = map_tool.get_area() m_fact.gen_monsters(area) player.is_moving(map_pix_size) all_mobiles.update(None, None) if m_attacks: m_attacks.update() all_sprites_list.draw(screen) clock.tick(25) pygame.display.flip() pygame.quit()
def __init__(self, app, screen): # tock started out random, but now is an important variable. # It is a frames count, used for periodic updates on certain # frames. self.p_max_health = 5 self.won = False self.won_msg = "WINNER!" self.particle_ban = False self.wait_stop_count = -1 # -1 means do not count self.wait_stop_max = 120 # wait this many frames after decay # before showing menu self.tock = 0 self.stage_e_bullet_odds = 15 self.mouse_rect = None self.temp_rect = None self.app = app self.screen = screen self.app.music_name = "intro.ogg" # self.app.continue_music() if self.app.settings['music']: # self.app.music_loaded = self.app.music_name # pygame.mixer.music.load(self.app.resource_find( # self.music_name)) # pygame.mixer.music.play() # plays once PLUS repeats param pass left_border = 50 right_border = 50 w, h = screen.get_size() self.world_rect = pygame.Rect(left_border, 0, w-right_border-left_border, h) self.bg = BackgroundManager(self.world_rect) # Yay spritegroups! They make the world go round, and iterate. # Basically each visible game object resides in its own special # spritegroup & then all one needs to do is go through these & # call functions & stuff. # It makes sense in here *points to brain* self.p_swarm = Swarm(self.world_rect) self.particles = Swarm(self.world_rect) self.explosion_images = self.app.load_seq('ex-medium') self.shield_hit_images = self.app.load_seq('shield_hit-tiny') self.damage_images = self.app.load_seq('ex-tiny') # Load player sprite as image list. self.p_unit_images = self.app.load_seq('pship') # self.p_unit_images = [] # self.p_unit_images.append(self.load_file('pship.png')) # self.p_unit_images.append(self.load_file('pship1.png')) # self.p_unit_images.append(self.load_file('pship2.png')) # self.p_unit_images.append(self.load_file('pship3.png')) # Load enemy ship image. self.e_ship_image = self.load_file('eship.png') if self.app.settings['sounds']: self.p_shoot_sound = self.app.load_file('p-weapon0.wav', file_type='sound') self.p_shoot_sound.set_volume(.3) self.e_ex_sound = self.app.load_file('e-ex.wav', file_type='sound') self.p_ex_sound = self.app.load_file('p-ex.wav', file_type='sound') self.e_damage_sound = self.app.load_file('e-damage.wav', file_type='sound') self.e_shield_sound = self.app.load_file('e-shield.wav', file_type='sound') self.p_shield_sound = self.app.load_file('p-shield.wav', file_type='sound') self.p_damage_sound = self.app.load_file('p-damage.wav', file_type='sound') print("loaded sounds...") self.menus = None self.tock = 0 self.lagcount = 0 self.leftkeydown = 0 self.rightkeydown = 0 # self.enemylist = [] # list of dirty rects self.swarm = Swarm(self.world_rect, shoot_odds=self.stage_e_bullet_odds) self.stage = Stage(self.swarm, self.p_swarm) self.p_shot_image = self.load_file('p-laser.png') self.e_shot_image = self.load_file('e-laser.png') self.p_bullet_swarm = Swarm(self.world_rect) self.e_bullet_swarm = Swarm(self.world_rect) # self.bullet_width = 10 self.hud_rect = pygame.Rect(0, 0, 5, 150) self.hud = Hud() self.hud.generate_blip('player.score', 100, fg_color=(255,243,207), text_color=(192,180,180), caption="SCORE") self.hud.generate_blip('player.health', self.p_max_health, fg_color=(0,255,42), text_color=(192,180,180), caption="SHIELD") self.statcounter = self.hud.get_blip('player.score')
from hud import Hud from scene import Scene from window import Window from character import Character # Create a grid with a specific atlas. g = Grid(10, 10, 50, 50, "terrain_atlas.json") # Create a character. goo = Character("goo", "../images/goo_hl.gif", 7, 7, "animation") g.add_character(goo, 5, 5) goo.scale(.10) # Create a few HUDs. meter_hud = Hud(x_offset=15, y_offset=80, hud_image_loc="../images/ui/hud-test.png") heart_hud0 = Hud(x_offset=120, y_offset=40, hud_image_loc="../images/ui/heart.png") heart_hud0.image.scale = 0.55 heart_hud1 = Hud(x_offset=140, y_offset=40, hud_image_loc="../images/ui/heart.png") heart_hud1.image.scale = 0.55 huds = [meter_hud, heart_hud0, heart_hud1] # Create a scene with a grid and some huds attached. s = Scene(g, huds) # Create the window.
def __init__(self, player): self.level_type = "none" self.background = None self.player = player self.hud = Hud()
pygame.display.set_caption('TETRIS') pygame.key.set_repeat(75) while 1: area = Area(width - 100, height) tetrino_queue = [] for i in range(5): tetrino_queue.append(randint(0, 6)) tetrino_color = (randint(1, 255), randint(1, 255), randint(1, 255)) tetrino = Tetrino(tetrino_color, tetrino_queue[0]) hud = Hud(width, height) gameOver = Gameover(width, height, area.score) screen.fill((0, 0, 0)) hud.draw_hud(screen) menu = Menu(width, height, (255, 255, 255), (0, 0, 0)) menu.draw_menu(screen) menu.update_menu(screen) pygame.display.flip() core = Core(tetrino, area, menu, screen) core.menu_input() init = 1000 start_time = pygame.time.get_ticks() while menu.singlePlayer and tetrino.game_state:
def __init__(self): """initialise the engine""" ShowBase.__init__(self) base.notify.info("Version {}".format(versionstring)) FSM.__init__(self, "FSM-Game") # # BASIC APPLICATION CONFIGURATIONS # # disable pandas default camera driver self.disableMouse() # set antialias for the complete sceen to automatic self.render.setAntialias(AntialiasAttrib.MAuto) # shader generator render.setShaderAuto() # Enhance font readability DGG.getDefaultFont().setPixelsPerUnit(100) # get the displays width and height for later usage self.dispWidth = self.pipe.getDisplayWidth() self.dispHeight = self.pipe.getDisplayHeight() # # CONFIGURATION LOADING # # load given variables or set defaults # check if particles should be enabled # NOTE: If you use the internal physics engine, this always has # to be enabled! particles = ConfigVariableBool("particles-enabled", True).getValue() if particles: self.enableParticles() def setFullscreen(): """Helper function to set the window fullscreen with width and height set to the screens size""" # set window properties # clear all properties not previously set base.win.clearRejectedProperties() # setup new window properties props = WindowProperties() # Fullscreen props.setFullscreen(True) # set the window size to the screen resolution props.setSize(self.dispWidth, self.dispHeight) # request the new properties base.win.requestProperties(props) # Set the config variables so we correctly store the # new size and fullscreen setting later winSize = ConfigVariableString("win-size") winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight)) fullscreen = ConfigVariableBool("fullscreen") fullscreen.setValue(True) # Render a frame to make sure the fullscreen is applied # before we do anything else self.taskMgr.step() # make sure to propagate the new aspect ratio properly so # the GUI and other things will be scaled appropriately aspectRatio = self.dispWidth / self.dispHeight self.adjustWindowAspectRatio(aspectRatio) # check if the config file hasn't been created if not os.path.exists(prcFile): setFullscreen() # automatically safe configuration at application exit #base.exitFunc = self.__writeConfig # # INITIALIZE GAME CONTENT # base.cTrav = CollisionTraverser("base collision traverser") base.pusher = CollisionHandlerPusher() self.menu = Menu() self.credits = Credits() self.charSelection = CharacterSelection() self.levelSelection = LevelSelection() self.koScreen = KoScreen() self.hud = Hud() self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg") self.menuMusic.setLoop(True) self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg") self.fightMusic.setLoop(True) base.audio3d = Audio3DManager(base.sfxManagerList[0], camera) # # EVENT HANDLING # # By default we accept the escape key self.accept("escape", self.__escape) # # ENTER GAMES INITIAL FSM STATE # self.request("Menu")
def create(self, package): self.map_package = MapPackage(package) self.world = self.map_package.current() self.hud = Hud() self.menu = Menu()
def __init__(self, master, skin: str, size: tuple): super(Application, self).__init__(master) self.snake = Snake(self, skin, size) self.hud = Hud(self)
def main(): logg.info('Starting the main function') #Instancing, etc. main_view = View().from_rect( FloatRect(0, 0, PP_WIDTH, PP_HEIGHT + BAR_HEIGHT)) window = RenderWindow( VideoMode(PP_WIDTH * SCALE, (PP_HEIGHT + BAR_HEIGHT) * SCALE), GAME_TITLE + ' v.' + GAME_VERSION) window.framerate_limit = 61 window.view = main_view # INITIALIZE TEXTURES HERE OR AFTER \o/ TEXTURE_WALL = Texture.load_from_file('main/walls.png') TEXTURE_BAR = Texture.load_from_file('main/bar.png') TEXTURE_HUDWEAPONS = Texture.load_from_file('main/hud_weapons.png') TEXTURE_FACES = Texture.load_from_file('main/faces.png') TEXTURE_NUMBERS = Texture.load_from_file('main/numbers.png') TEXTURE_WEAPONS = Texture.load_from_file('main/weapons.png') TEXTURE_ENEMIES = Texture.load_from_file('main/test.png') #Create an instance for all game variables and loop functions # and set the level to TESTLEVEL game = Gameworld(TEXTURE_ENEMIES) game.create_dict_map() game.player.gamemap = game.current_level game.init_physics() game.physics.mob_bodies(game.entities) #prepare the hud hud = Hud(player=game.player, background=TEXTURE_BAR, faces=TEXTURE_FACES, hudweapons=TEXTURE_HUDWEAPONS, weapons=TEXTURE_WEAPONS, numbers=TEXTURE_NUMBERS) #prepare the wall textures wall_sprites = game.create_wall_sprite_list(TEXTURE_WALL) rays = Raycaster(player=game.player, sprites=wall_sprites, gamemap=game.current_level) #prepare other stuff player_action = '' running = True nofocus = False ## # MAIN LOOP ## logg.info('Main loop starting...') while running: #iterate events for event in window.iter_events(): if event.type == Event.CLOSED or player_action == 'quit': running = False if event.type == Event.LOST_FOCUS: nofocus = True elif event.type == Event.GAINED_FOCUS: nofocus = False if event.type == Event.KEY_RELEASED: if game.player.bob > 0: #level the headbobbing game.player.bob -= .5 elif game.player.bob < 0: game.player.bob += .5 game.player.strafing = False #disable speed limiter for moving in 2 axii window.clear(Color(235, 235, 235, 255)) #clear the window of everything for sprite in wall_sprites: #draw walls window.draw(sprite) #draw entities here for entity in game.entities: if entity.visible == True: for sprite_slice in entity.sprite: window.draw(sprite_slice) hud.display(window) #draw the hud debug_txt = text('[' + str(draw_fps(frame)) + '] ' + str("{0:.2f}".format(game.player.ux)) + '(' + str(game.player.x) + '),' + str("{0:.2f}".format(game.player.uy)) + '(' + str(game.player.y) + '):' + str(game.player.heading), style=1) window.draw(debug_txt) wall_sprites = rays.texture_slices( rays.cast_rays(), wall_sprites, game.player.bob) #determine which walls to display #determine wich entities to display and prepare for entity in game.entities: #calculate the distance of entities to the player entity.distance_to_player(game.player) # print(str(round(entity.distance, 2)) + " " + str(entity.x) + "," + str(entity.y)) game.entities.sort(key=lambda x: x.distance, reverse=True) #sort entities based on the distance for entity in game.entities: entity.set_sprite_for_display(game.player, rays.distances) ### # TIMERS ### if game.player.attack_delay > 0 and game.player.attack == True: game.player.attack_delay -= 1 elif game.player.attack == True and game.player.attack_delay == 0: game.player.attack = False game.player.attack_delay = 2 elif game.player.attack == False and game.player.attack_delay > 0: game.player.attack_delay -= 1 if len(game.doors) != 0: # print('lol doors') for door in game.doors: # print(door.openess) state = door.open_close() # print(state) if state == 'done': # print('removing doors') game.doors.remove(door) game.physics.world.ClearForces() if not nofocus: player_action = game.handle_keys() #player input game.physics.world.Step(1.0 / 60.0, 10, 8) game.player.update_position() for entity in game.entities: entity.update_position() window.display() #blit to window window.close() logg.info('Terminating. Have a nice day.') logg.info('Average FPS: %s', round(average_fps / all_frames, 2))
def game_loop(): """The main game loop""" # This is for the in-game background music pygame.mixer.music.stop() pygame.mixer.music.load("assets/audio/electric_jazz.wav") pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play(-1) all_sprites_list = pygame.sprite.Group() missile_list = pygame.sprite.Group() projectile_list = pygame.sprite.Group() power_up_list = pygame.sprite.Group() random.seed() missiles_to_spawn = random.choices([1, 2, 3], weights=[1, 2, 3], k=(fib(G.DIFFICULTY + 5))) power_ups_to_spawn = random.choices( sprites.Power_Up.power_up_list, weights=[1, 1, 1, 1], k=random.randrange(2, 7), ) player = Player() gun = sprites.Gun((G.DISPLAY_WIDTH * 0.5, G.DISPLAY_HEIGHT * 0.875)) all_sprites_list.add(gun) hud = Hud(player.health, player.score, player.ammo) delta_t = 0 game_time = 0 while True: # Add last iteration's time to running game_time game_time += delta_t for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() # Fire a projectile if the player presses and releases space if event.type == pygame.KEYUP: if event.key == pygame.K_SPACE and player.ammo > 0: player.update_ammo(-1) if player.ammo == 0: player.reload_start_time = game_time pygame.mixer.Sound.play(G.SHOOT_FX) projectile = sprites.Projectile( gun.rect.center, gun.angle, gun.image.get_height() * 0.5, ) all_sprites_list.add(projectile) projectile_list.add(projectile) if player.fan_of_projectiles: left_projectile = sprites.Projectile( gun.rect.center, gun.angle + 15, gun.image.get_height() * 0.5, ) right_projectile = sprites.Projectile( gun.rect.center, gun.angle - 15, gun.image.get_height() * 0.5, ) all_sprites_list.add(left_projectile, right_projectile) projectile_list.add(left_projectile, right_projectile) if event.key == pygame.K_ESCAPE: G.PAUSE = True paused.paused() # Reload if player.time_to_reload(game_time): player.reload() if player.time_to_piercing_rounds_expire(game_time): player.piercing_rounds = False if player.time_to_fan_expire(game_time): player.fan_of_projectiles = False if (random.randrange(700 // (5 + G.DIFFICULTY)) == 0 and missiles_to_spawn): missile_type = missiles_to_spawn.pop(0) new_missile = sprites.Missile( ( random.randrange(0.1 * G.DISPLAY_WIDTH, 0.9 * G.DISPLAY_WIDTH), -600, ), missile_type, ) all_sprites_list.add(new_missile) missile_list.add(new_missile) if random.randrange(500) == 0 and power_ups_to_spawn: power_up = power_ups_to_spawn.pop(0) new_power_up_sprite = sprites.Power_Up( ( random.randrange(G.DISPLAY_WIDTH * 0.125, G.DISPLAY_WIDTH * 0.875), random.randrange(G.DISPLAY_WIDTH * 0.125, G.DISPLAY_HEIGHT * 0.625), ), power_up, ) all_sprites_list.add(new_power_up_sprite) power_up_list.add(new_power_up_sprite) all_sprites_list.update() for projectile in projectile_list: hit_missile_list = pygame.sprite.spritecollide( projectile, missile_list, True) for hit_missile in hit_missile_list: all_sprites_list.add( sprites.Missile_Explosion(hit_missile.rect.center, hit_missile.missile_type)) pygame.mixer.Sound.play(G.EXPLOSION_FX) if not player.piercing_rounds: projectile.kill() G.SCORE += hit_missile.stats["points"] hit_power_up_list = pygame.sprite.spritecollide( projectile, power_up_list, True) for hit_power_up in hit_power_up_list: pygame.mixer.Sound.play(random.choice(G.POWER_UP_FX_LIST)) if not hit_power_up.power_up["temporary"]: G.PERMANENT_POWER_UPS[hit_power_up.power_up["type"]] += 1 if hit_power_up.power_up["type"] == "higher_max_health": player.update_health(1) elif hit_power_up.power_up["type"] == "higher_max_ammo": if player.ammo >= 1: player.update_ammo(1) player.max_ammo += 1 elif hit_power_up.power_up["type"] == "piercing_rounds": player.piercing_rounds = True player.piercing_rounds_start_time = game_time elif hit_power_up.power_up["type"] == "fan_of_projectiles": player.fan_of_projectiles = True player.fan_of_projectiles_start_time = game_time if projectile.off_screen(): projectile.kill() for missile in missile_list: if missile.off_screen(): missile.kill() all_sprites_list.add( sprites.Missile_Explosion(missile.rect.center, missile.missile_type)) pygame.mixer.Sound.play(G.EXPLOSION_FX) player.update_health(missile.stats["damage"]) if player.health <= 0: game_over.game_over() # Paint the background G.WHITE G.SCREEN.fill(G.WHITE) G.SCREEN.blit(G.BACKGROUND_1.image, G.BACKGROUND_1.rect) hud.draw_hud(G.SCORE, player.ammo, player.health) # Draw all sprites all_sprites_list.draw(G.SCREEN) # Move all background changes to the foreground pygame.display.update() # Store time since last tick in seconds delta_t = G.CLOCK.tick(60) / 1000 if not missiles_to_spawn and not missile_list: G.DIFFICULTY += 1 new_round.new_round()
def main(): # create queues in shared memory so each process can access it mainQueue = Queue(maxsize=70) xyDoneQueue = Queue(maxsize=70) hudDoneQueue = Queue(maxsize=70) resizeDoneQueue = Queue(maxsize=70) # start VideoStream process vs = PiVideoStream(mainQueue, file1) time.sleep(1) # allow pi camera to "warm up" vsP1 = Process(target=vs.update, name='videoStreamProcess', args=(resolution, framerate, awb_mode)) # passing these parameters here because time.sleep( 0.5 ) # put some frames into mainQueue to stop other processes from throwing errors # passing to PiVideoStream instantiation causes pi camera to be accessed by two different processes which breaks it vsP1.daemon = True vsP1.start() # start ColorTracker process tracker = ColorTracker(mainQueue, xyDoneQueue, file2) # pass shared queues trackerP1 = Process(target=tracker.update, name='trackerProcess', args=()) trackerP1.daemon = True trackerP1.start() # start Hud process hud = Hud(resolution, xyDoneQueue, hudDoneQueue, file3, hud_done) hudP1 = Process(target=hud.draw, name='hudProcess', args=()) hudP1.daemon = True hudP1.start() # start ResizeFrame process 1 resize = ResizeFrame(hudDoneQueue, resizeDoneQueue, file4, hud_done, instance_name='resizer1') resizeP1 = Process(target=resize.resize, name='resizeProcess', args=()) resizeP1.daemon = True resizeP1.start() # start ResizeFrame process 2 resize2 = ResizeFrame(hudDoneQueue, resizeDoneQueue, file4B, hud_done, instance_name='resizer2') resizeP2 = Process(target=resize2.resize, name='resizeProcess2', args=()) resizeP2.daemon = True resizeP2.start() # start DisplayFrame process display = DisplayFrame(resizeDoneQueue, file5, done) displayP1 = Process(target=display.show, name='displayProcess', args=()) displayP1.daemon = True displayP1.start() while not done.is_set(): continue else: print('Terminating processes') file1.close() file2.close() file3.close() file4.close() file4B.close() vsP1.terminate() trackerP1.terminate() hudP1.terminate() resizeP1.terminate() resizeP2.terminate() displayP1.terminate()
def __init__(self, AGREE_TIME, WIN_TIME, COOLDOWN_TIME, STALE_TIME, TOTAL_TIME, FAILURE_TIME, NUM_WINS, keys, p_list_rect, scoreboard_rect, top_rect, top_rect_left, top_rect_right, game_rect, bottom_rect, shadow_dist, sys_font): # -- IMPORTS -- self.keys = keys self.top_rect_left = top_rect_left self.top_rect_right = top_rect_right self.bottom_rect = bottom_rect self.AGREE_TIME = AGREE_TIME self.NUM_WINS = NUM_WINS self.shadow_dist = shadow_dist # -- MATCH INFO -- self.match_num = 0 self.big_f_agree = self.big_j_agree = 0 self.f_wins = self.j_wins = 0 self.score_streak = 0 # -- NECESSARY CLASSES -- self.p_list = PlayerList(p_list_rect, shadow_dist, sys_font) self.game = Game(WIN_TIME, COOLDOWN_TIME, STALE_TIME, TOTAL_TIME, FAILURE_TIME, self.keys, game_rect, shadow_dist, sys_font) self.wheel = Wheel(game_rect, shadow_dist, sys_font) self.hud = Hud(top_rect, bottom_rect, shadow_dist, sys_font) self.scoreboard = Scoreboard(scoreboard_rect, shadow_dist, sys_font, self.p_list) self.menu = Menu(p_list_rect, self.keys, shadow_dist, sys_font) self.match_state = MatchState(MatchState.PLAYER_LIST, self.state_response) # -- MENU ACTIONS -- self.menu.add_item( "[2]", "PRACTICE MODE", 0.5, lambda: self.match_state.set_state(MatchState.PRACTICE_MODE)) self.menu.add_item( "[3]", "RESET MATCHUP", 0.5, lambda: self.match_state.set_state(MatchState.NEW_OPPONENT, same_match=True)) self.menu.add_item( "[4]", "NEXT OPPONENT", 0.5, lambda: self.match_state.set_state(MatchState.NEW_OPPONENT, next=True)) self.menu.add_item( "[5]", "CHANGE PLAYERS", 0.5, lambda: self.match_state.set_state(MatchState.PLAYER_LIST)) # -- RENDERING -- # bottom bar self.f_name_text = TextRenderer( sys_font, 2, (top_rect_left.centerx, bottom_rect.centery), shadow_dist) self.j_name_text = TextRenderer( sys_font, 2, (top_rect_right.centerx, bottom_rect.centery), shadow_dist) self.streak_text = TextRenderer( sys_font, 1, (bottom_rect.width * 0.08, bottom_rect.centery + bottom_rect.height * 0.25), shadow_dist) self.practice_mode_text = TextRenderer(sys_font, 2, bottom_rect.center, 0) self.practice_inst_rect = Rect( (game_rect.left + game_rect.height * 0.05, game_rect.top + game_rect.height * 0.05), (game_rect.width, game_rect.height * 0.25)) self.practice_inst_0 = ShadowedPressable.make_pressable_key( "1. Hold your key to build your bar.", sys_font, 1, GameColor.Pink)[0].convert_alpha() self.practice_inst_1 = ShadowedPressable.make_pressable_key( "2. Press [SPACE] to reset moving bars.", sys_font, 1, GameColor.Cyan)[0].convert_alpha() self.practice_inst_2 = ShadowedPressable.make_pressable_key( "3. Build the biggest bar to win!", sys_font, 1, GameColor.Yellow)[0].convert_alpha() # vs self.new_match_text = TextRenderer( sys_font, 4, (game_rect.centerx, game_rect.top + game_rect.height / 6), shadow_dist, GameColor.White) self.vs_left_bar = Rect((0, game_rect.y + game_rect.height / 3), (top_rect_left.width, game_rect.height / 5)) self.vs_right_bar = Rect( (game_rect.centerx, self.vs_left_bar.bottom), (self.vs_left_bar.width, self.vs_left_bar.height)) vs_par_width = game_rect.height / 7 self.vs_parallelogram = ((game_rect.centerx, self.vs_left_bar.top), (game_rect.centerx - vs_par_width, self.vs_right_bar.bottom), (game_rect.centerx, self.vs_right_bar.bottom), (game_rect.centerx + vs_par_width, self.vs_left_bar.top)) self.f_name_big_text = TextRenderer( sys_font, 4, (top_rect_left.centerx + shadow_dist, self.vs_left_bar.centery + shadow_dist), shadow_dist, GameColor.F.Dark) self.j_name_big_text = TextRenderer( sys_font, 4, (top_rect_right.centerx + shadow_dist, self.vs_right_bar.centery + shadow_dist), shadow_dist, GameColor.J.Dark) self.vs_text = TextRenderer(sys_font, 2, (game_rect.centerx + shadow_dist, self.vs_left_bar.bottom + shadow_dist), shadow_dist) self.vs_left_bar.move_ip((top_rect_left.width, 0)) big_f, big_f_shadow = ShadowedPressable.make_pressable_key( "[F]", sys_font, 4) self.big_f = ShadowedPressable( big_f.convert_alpha(), big_f_shadow, (top_rect_left.centerx, game_rect.top + game_rect.height * 0.85), shadow_dist) big_j, big_j_shadow = ShadowedPressable.make_pressable_key( "[J]", sys_font, 4) self.big_j = ShadowedPressable( big_j.convert_alpha(), big_j_shadow, (top_rect_right.centerx, game_rect.top + game_rect.height * 0.85), shadow_dist) # counter self.counter = TextRenderer(sys_font, 4, game_rect.center, shadow_dist) self.ready_text = TextRenderer( sys_font, 2, (game_rect.centerx, game_rect.top + game_rect.height * 0.35), shadow_dist) # win rects win_rect_size = top_rect.height * 0.15 self.win_rect = Rect(top_rect.centerx - win_rect_size / 2, win_rect_size, win_rect_size, win_rect_size) self.win_rect_shadows = [ self.win_rect.move(self.win_rect.width * 2 * idx, 0) for idx in [-3, -2, -1, 1, 2, 3] ] self.f_win_rects = [] self.j_win_rects = [] # win text self.f_win_loss_text = TextRenderer( sys_font, 4, (top_rect_left.centerx, game_rect.top + game_rect.height * 0.35), shadow_dist) self.j_win_loss_text = TextRenderer( sys_font, 4, (top_rect_right.centerx, game_rect.top + game_rect.height * 0.35), shadow_dist) self.f_plus_minus_text = TextRenderer( sys_font, 4, (top_rect_left.centerx, game_rect.top + game_rect.height * 0.65), shadow_dist) self.j_plus_minus_text = TextRenderer( sys_font, 4, (top_rect_right.centerx, game_rect.top + game_rect.height * 0.65), shadow_dist) self.f_enc_cons_text = TextRenderer( sys_font, 1, (top_rect_left.centerx, game_rect.top + game_rect.height * 0.5), shadow_dist / 8) self.j_enc_cons_text = TextRenderer( sys_font, 1, (top_rect_right.centerx, game_rect.top + game_rect.height * 0.5), shadow_dist / 8) # tweens self.vs_bar_w = Tweener( { "retracted": 0, "extended": top_rect_left.width }, "retracted") self.f_name_big_x = Tweener( { "out": 0, "in": self.f_name_big_text.center[0] }, "out") self.j_name_big_x = Tweener( { "out": game_rect.right, "in": self.j_name_big_text.center[0] }, "out") # -- SOUND -- self.vs_sound = pygame.mixer.Sound("SFX/VS.wav") self.timer_sound = pygame.mixer.Sound("SFX/beep.wav") self.begin_sound = pygame.mixer.Sound("SFX/begin_game.wav") self.climax_sound = pygame.mixer.Sound("SFX/climax.wav") self.victory_sounds = [ pygame.mixer.Sound("SFX/vic{0}.wav".format(i)) for i in range(3) ] self.win_sound = pygame.mixer.Sound("SFX/win.wav") self.reset()
pygame.init() fps_clock = pygame.time.Clock() # Game window setup window_size = DEFAULT_WINDOW_SIZE pygame.display.set_caption("Type Fight!") app_icon = pygame.image.load(os.path.join('graphics', 'app_icon_256.png')) pygame.display.set_icon(app_icon) # Set flags to FULLSCREEN | DOUBLEBUF | HWSURFACE if we add fullscreen support later flags = HWSURFACE|DOUBLEBUF|RESIZABLE screen = pygame.display.set_mode(window_size, flags) screen.set_alpha(None) game_surface = pygame.Surface((screen.get_width(), screen.get_height())) hud = Hud(screen) player = Player(screen) fight_bkg = pygame.image.load(os.path.join('graphics', 'fight_bkg.png')).convert() win_fg = pygame.image.load(os.path.join('graphics', 'win_fg.png')).convert_alpha() lose_fg = pygame.image.load(os.path.join('graphics', 'lose_fg.png')).convert_alpha() pause_fg = pygame.image.load(os.path.join('graphics', 'pause_menu.png')).convert_alpha() gamelog.log_display_info() pygame.key.set_repeat(500, 50) # Mouse setup mouse_list = [MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP] mouse_button_list = [MOUSEBUTTONDOWN, MOUSEBUTTONUP] pygame.event.set_allowed([QUIT, VIDEORESIZE, MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP]) # Pygame mixer setup for sounds