def main(): numpass, numfail = pg.init() print(f'pass:{numpass}, fail:{numfail}') inited = pg.get_init() print(f'Inited: {inited}') try: raise pg.error('Custom Error') except RuntimeError as re: print(f'Exception: {re}') pg.set_error('Set Error') err = pg.get_error() print(f'Error: {err}') major, minor, path = pg.get_sdl_version() print(f'SDL: {major}.{minor}.{path}') pg.register_quit(quit) unencoded = '你好' encoded = pg.encode_string(unencoded, encoding='utf-8') print(f'Encoded: {encoded}, Original: {unencoded}') encoded_path = pg.encode_file_path(os.path.join(__file__)) print(f'Encoded Path: {encoded_path}') print(f'{pg.version.PygameVersion(1, 2, 3)}, {pg.vernum}')
def main(): # init is a convenient way to initialize all subsystems # instead we could also initialize the submodules directly - for example by calling pygame.display.init(), pygame.display.quit() no_pass, no_fail = pygame.init() if no_fail > 0: print("Not all pygame modules initialized correctly") print(pygame.get_error()) else: print("All pygame modules initializes") if not pygame.font: print("Pygame - fonts not loaded") if not pygame.mixer: print("Pygame - audio not loaded") if not pygame.display: print("Pygame - display not loaded") if not pygame.mouse: print("Pygame - mouse not loaded") print("Did we initialize: {}".format(pygame.get_init())) print("Pygame Version: {}".format(pygame.ver)) print("Pygame runs on SDL Version: {}".format(pygame.get_sdl_version())) print("Pygame Display Driver: {}".format(pygame.display.get_driver())) pygame.register_quit(on_quit) w, h, t = 640, 480, "Elisa - 19.1 Collision Detection - QuadTree" c_white = (255, 255, 255) c_black = (0, 0, 0) screen_buffer = pygame.display.set_mode(size=(w, h), flags=0) pygame.display.set_caption(t) pygame.mouse.set_visible(True) back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size()) back_buffer = back_buffer.convert() back_buffer.fill(c_white) # here we setup a pygamer clock - we will discuss this in a later example fps_watcher = pygame.time.Clock() is_done = False # we compose a scene of ... while not is_done: _ = fps_watcher.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: is_done = True break back_buffer.fill(c_black) if not is_done: screen_buffer.blit(back_buffer, (0, 0)) pygame.display.flip() pygame.quit()
def __PYGAMEinit__(): # called automatically by pygame.init() global init_called init_called = init_called + 1 pygame.register_quit(pygame_quit) # Returning False indicates that the initialization has failed. It is # purposely done here to test that failing modules are reported. return False
def test_register_quit(self): """Ensure that a registered function is called on quit()""" self.assertFalse(quit_hook_ran) pygame.init() pygame.register_quit(quit_hook) pygame.quit() self.assertTrue(quit_hook_ran)
def start_pygame(resolution, flags, depth, caption="PyGame"): """Initializes pygame to run the game. Returns the screen surface. caption is the caption for the pygame window, other variables are the same as pygame.display.set_mode method.""" pygame.init() pygame.register_quit(quit_func) # Will be changed by Game class. surface = pygame.display.set_mode(resolution, flags, depth) pygame.display.set_caption(caption) return surface
def test_register_quit(self): """Ensure that a registered function is called on quit()""" self.assertEqual(quit_count, 0) pygame.init() pygame.register_quit(quit_hook) pygame.quit() self.assertEqual(quit_count, 1)
def init(): """init() -> None initialize pygame.fastevent """ global _ft_init if not pygame.display.get_init(): raise error("video system not initialized") register_quit(_quit_hook) _ft_init = True
def test_register_quit(self): # __doc__ (as of 2008-06-25) for pygame.base.register_quit: # register_quit(callable): return None # register a function to be called when pygame quits self.assert_(not quit_hook_ran) pygame.init() pygame.register_quit(quit_hook) pygame.quit() self.assert_(quit_hook_ran)
def run(self): self.running = True pygame.register_quit(self.quit) while self.running: event = pygame.event.wait() if event.type == pygame.QUIT: pygame.quit() self.running = False event.dict["type"]=event.type self.channel.basic_publish(exchange="events", routing_key=str(event.type), body="{}".format(event.dict)) print "S out",event.dict
def __init__(self, screen, game_map, hero, allies, enemies, server_socket=None): """Create a new game object. screen is the surface which is used to display the game on screen. __game_map is the map of the game (obviously) and is an image file. After the game starts, might have blitted images on it. hero is the Character object the player will play as. allies and enemies are pygame.sprite.OrderedUpdates objects. Each sprite's location is its location on game_map. containing all the allies and enemies of the hero respectively. self.fps is an automatically calculated refresh rate of the screen (might not work for multi-screen setups). You can change it as you like or not use it at all by passing vsync=False to update_screen. server_socket is the Sock of the server for online games. If provided, game_map might change according to the server.""" self.screen = screen self.__game_map = pygame.image.load(game_map).convert() self.hero = hero self.allies = allies self.enemies = enemies self.__minimap = pygame.image.load(game_map).convert() self._uppery = (self.__game_map.get_height()) - ( self.screen.get_height() / 2) self._upperx = (self.__game_map.get_width()) - ( self.screen.get_width() / 2) self._lowerx = self.screen.get_width() / 2 self._lowery = self.screen.get_height() / 2 self.fps = get_refresh_rate(win32api.EnumDisplayDevices()) self.server_socket = server_socket self.timeout = 0.1 self.__recv = False # Turns to False when the client stops communicating with the server. self.__send = False # Turns to False when the client stops communicating with the server. pygame.register_quit(self.quit_func) # self.__inactive_timeout = None self.__exit = False
def runGame(): # Initialize game and create a window pg.init() # create a new object using the settings class setting = Settings() # creaete a new object from pygame display screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight)) # intro intro.introimages() # set window caption using settings obj pg.display.set_caption(setting.windowCaption) bMenu = ButtonMenu(screen) bMenu.addButton("play", "PLAY") bMenu.addButton("menu", "MENU") bMenu.addButton("twoPlay", "2PVS") bMenu.addButton("settings", "SETTINGS") bMenu.addButton("invert", "INVERT") bMenu.addButton("about", "ABOUT") bMenu.addButton("quit", "QUIT") bMenu.addButton("grey", "GREY") bMenu.addButton("red", "RED") bMenu.addButton("blue", "BLUE") bMenu.addButton("retry", "RETRY") bMenu.addButton("hard", "HARD") bMenu.addButton("normal", "NORMAL") mainMenuButtons = ["play", "about", "settings", "quit"] # delete "twoPlay" playMenuButtons = ["grey", "red", "blue", "menu", "quit"] levelMenuButtons = ["hard", "normal", "quit"] mainGameButtons = ["play", "menu", "quit"] aboutButtons = ["menu", "quit"] settingsMenuButtons = ["menu", "invert", "quit"] bgManager = BackgroundManager(screen) bgManager.setFillColor((0, 0, 0)) bgManager.addBackground( "universe_1", "gfx/backgrounds/stars_back.png", 0, 1) bgManager.addBackground( "universe_1", "gfx/backgrounds/stars_front.png", 0, 1.5) bgManager.selectBackground("universe_1") # Create an instance to stor game stats stats = GameStats(setting) sb = Scoreboard(setting, screen, stats) # Make a ship ship = Ship(setting, screen) # Ships for two player ship1 = Ship(setting, screen) ship2 = Ship(setting, screen) # make a group of items to store items = Group() # make a group of bullets to store bullets = Group() charged_bullets = Group() eBullets = Group() setting.explosions = Explosions() # Make an alien aliens = Group() gf.createFleet(setting, stats, screen, ship, aliens) pg.display.set_icon(pg.transform.scale(ship.image, (32, 32))) bgImage = pg.image.load('gfx/title_c.png') bgImage = pg.transform.scale( bgImage, (setting.screenWidth, setting.screenHeight)) bgImageRect = bgImage.get_rect() aboutImage = pg.image.load('gfx/About_modify2.png') aboutImage = pg.transform.scale( aboutImage, (setting.screenWidth, setting.screenHeight)) aboutImageRect = aboutImage.get_rect() # plays bgm pg.mixer.music.load('sound_bgms/galtron.mp3') pg.mixer.music.set_volume(0.25) pg.mixer.music.play(-1) rungame = True sounds.stage_clear.play() # Set the two while loops to start mainMenu first while rungame: # Set to true to run main game loop bMenu.setMenuButtons(mainMenuButtons) while stats.mainMenu: if not stats.gameActive and stats.paused: setting.initDynamicSettings() stats.resetStats() ##stats.gameActive = True # Reset the alien and the bullets aliens.empty() bullets.empty() eBullets.empty() # Create a new fleet and center the ship gf.createFleet(setting, stats, screen, ship, aliens) ship.centerShip() mm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) mm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect) bMenu.setMenuButtons(levelMenuButtons) while stats.levelMenu: lm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) lm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect) bMenu.setMenuButtons(playMenuButtons) while stats.playMenu: pm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) pm.drawMenu(setting, screen, sb, bMenu) bMenu.setMenuButtons(mainGameButtons) while stats.mainGame: # Game functions gf.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets, charged_bullets) # Check for events # Reset Game if gf.reset == 1: gf.reset = 0 pg.register_quit(runGame()) if stats.gameActive: gf.updateAliens(setting, stats, sb, screen, ship, aliens, bullets, eBullets) # Update aliens gf.updateBullets(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, items) # Update collisions gf.updateItems(setting, screen, stats, sb, ship, aliens, bullets, eBullets, items) ship.update(bullets, aliens) # update the ship # Update the screen gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, bMenu, bgManager, items) bMenu.setMenuButtons(aboutButtons) bMenu.setPos(None, 500) while stats.mainAbout: About.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) About.drawMenu(setting, screen, sb, bMenu, aboutImage, aboutImageRect) while stats.twoPlayer: tp.checkEvents(setting, screen, stats, sb, bMenu, bullets, aliens, eBullets, ship1, ship2) if stats.gameActive: ship1.update(bullets, aliens) ship2.update(bullets, aliens) tp.updateBullets(setting, screen, stats, sb, ship1, ship2, aliens, bullets, eBullets, items) tp.updateScreen(setting, screen, stats, sb, ship1, ship2, aliens, bullets, eBullets, bMenu, items) bMenu.setMenuButtons(settingsMenuButtons) while stats.settingsMenu: sm.checkEvents1(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) sm.drawMenu(setting, screen, sb, bMenu) while stats.mainGame: if rungame == True: print("test")
def __PYGAMEinit__(): #called automatically by pygame.init() global init_called init_called = init_called + 1 pygame.register_quit(pygame_quit)
def main(): global screen, game_state, game_surface, gui_surface, resource_manager, clock, \ game_scene, current_width, current_state, pause_state, pause_scene, game_map, overworld_sheet, hud # pygame.mixer.pre_init(frequency=44100, size=-8) pygame.init() pygame.register_quit(has_quit) # Set up the window screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) game_state = engine.State() pause_state = engine.State() game_surface = engine.CoordinateSurface( (SCREEN_WIDTH, (SCREEN_HEIGHT / COORDINATE_HEIGHT) * COORDINATE_HEIGHT), (COORDINATE_WIDTH, COORDINATE_HEIGHT)) pause_surface = engine.CoordinateSurface( pygame.Rect((0, 0), (SCREEN_WIDTH, SCREEN_HEIGHT)), (COORDINATE_WIDTH, COORDINATE_HEIGHT)) hud = game.gui.HUD((SCREEN_WIDTH, SCREEN_HEIGHT)) game_scene = engine.Scene((2560, 2048)) pause_scene = engine.Scene((COORDINATE_WIDTH, COORDINATE_HEIGHT)) game_state.add_scene('game', game_scene) pause_state.add_scene('pause', pause_scene) current_state = game_state game_scene.insert_view(game_surface, 'game_view', (0, 0)) pause_scene.insert_view(pause_surface, 'pause_view', (0, 0), (0, 0), (0, 0, 0, 0)) current_width = 480 # Set up the clock clock = engine.GameClock(*CLOCK_SETTINGS) # Load the resources overworld_sheet = engine.Spritesheet(SPRITE_DIR + "OverworldSheet.png") enemy_sheet = engine.Spritesheet(SPRITE_DIR + "Enemies.png") resource_manager = engine.ResourceManager() resource_manager.add_spritesheet_strip_offsets('overworld_tiles', overworld_sheet, (1, 1), 600, 24, (16, 16), 1, 1) # Load enemy sprites resource_manager.add_spritesheet_strip_offsets('octorok', enemy_sheet, (0, 0), 9, 9, (16, 16), 0, 0, (64, 64, 192)) resource_manager.add_font('gui_font_small', FONT_DIR + "ReturnofGanon.ttf", 20) resource_manager.add_font('gui_font_large', FONT_DIR + "ReturnofGanon.ttf", 46) # Music resource_manager.add_music('overworld', MUSIC_DIR + '10. Overworld' + EXTENSION) resource_manager.add_music('mabe_village', MUSIC_DIR + '11. Mabe Village' + EXTENSION) resource_manager.add_music('mysterious_forest', MUSIC_DIR + '16. Mysterious Forest' + EXTENSION) # resource_manager.play_music('mabe_village') # Sounds game_map = engine.Map(RESOURCE_DIR + 'worlds/grassworldtmx', SPRITE_DIR + 'OverworldSheet.png') while True: if not run_game(): # print("Back in main, breaking and quiting pygame") break
def __init__(self): '''Makes a BetterTimers object. Call pygame.quit to end all timers.''' self.__timers = list() pygame_init() register_quit(self.end_all_timers) fastevent_init()
def main(): # init is a convenient way to initialize all subsystems # instead we could also initialize the submodules directly - for example by calling pygame.display.init(), pygame.display.quit() no_pass, no_fail = pygame.init() if no_fail > 0: print("Not all pygame modules initialized correctly") print(pygame.get_error()) else: print("All pygame modules initializes") # in order to actually do something with text, we need to ensure that the font module is initialized. Furthermore, since we want to # draw some text to the screen it makes sense to also check the display initialization. if not pygame.font: print("Pygame - fonts not loaded") if not pygame.display: print("Pygame - display not loaded") print("Did we initialize: {}".format(pygame.get_init())) print("Pygame Version: {}".format(pygame.ver)) print("Pygame runs on SDL Version: {}".format(pygame.get_sdl_version())) print("Pygame Display Driver: {}".format(pygame.display.get_driver())) # for pontential cleanup of other resources, we register a quit handler. This handler will be invoked whenever # pygame enters the quit state. pygame.register_quit(on_quit) w, h, t = 640, 480, "Elisa - 0.2 Fonts and Text" c_white = (255, 255, 255) screen_buffer = pygame.display.set_mode(size=(w, h), flags=0) pygame.display.set_caption(t, "Elisa 0.2") pygame.mouse.set_visible(True) back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size()) back_buffer = back_buffer.convert() back_buffer.fill(c_white) # here we setup a pygamer clock - we will discuss this in a later example fps_watcher = pygame.time.Clock() is_done = False # let's see which fonts we do have fonts = pygame.font.get_fonts() no_fonts = len(fonts) print("Found {} fonts ...".format(no_fonts)) for i, f in enumerate(fonts): print("Found font: ", f) while not is_done: _ = fps_watcher.tick(16) for event in pygame.event.get(): if event.type == pygame.QUIT: is_done = True break # clear the screen and write something in a randomly coloured, random font back_buffer.fill(C_BLACK) c = (randint(0, 255), randint(0, 255), randint(0, 255)) x, y = randint(100, 500), randint(50, 450) i_font = randint(0, no_fonts - 1) size = randint(20, 50) # while get_fonts returned a list of all fonts on the system, sometimes they may not be system fonts and # directly referencable by pygame, that is why we call match font here, which # if the font is installed on the system gives us the path to the font - still then it seems in certain cases # is not really present on the system, so we include another check font = pygame.font.match_font(fonts[i_font]) if not os.path.exists(font): print("Font does not exist: ", font) continue f = pygame.font.Font(font, size) # now, let's flip some coins in order to add text effects like bold, italic or underlining if random() >= 0.5: f.set_bold(True) if random() >= 0.5: f.set_italic(True) if random() >= 0.5: f.set_underline(True) # Note that the text can only be a single line, font render returns a surface that we can blit into our # main surface. Here, we set antialiasing to false text = f.render("Hello", False, c) back_buffer.blit(text, (x, y)) if not is_done: screen_buffer.blit(back_buffer, (0, 0)) pygame.display.flip() sleep(0.5) pygame.quit()
lm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect) bMenu.setMenuButtons(playMenuButtons) while stats.playMenu: pm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) pm.drawMenu(setting, screen, sb, bMenu) bMenu.setMenuButtons(mainGameButtons) while stats.mainGame: # Game functions gf.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets, charged_bullets) # Check for events # Reset Game if gf.reset == 1: gf.reset = 0 pg.register_quit(runGame()) if stats.gameActive: gf.updateAliens(setting, stats, sb, screen, ship, aliens, bullets, eBullets) # Update aliens gf.updateBullets(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, items) # Update collisions gf.updateItems(setting, screen, stats, sb, ship, aliens, bullets, eBullets, items) ship.update(bullets, aliens) # update the ship # Update the screen gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets, eBullets, charged_bullets, bMenu, bgManager, items) bMenu.setMenuButtons(aboutButtons) bMenu.setPos(None, 500) while stats.mainAbout: About.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens, bullets, eBullets) About.drawMenu(setting, screen, sb, bMenu, aboutImage, aboutImageRect)
source=self, scene=scene, surface=surface)) py_format = (surface.get_bitsize(), surface.get_masks()) if py_format != self.last_channels[0]: self.last_channels = (py_format, channels_from_surface(surface)) super(PygameRenderer, self).begin_render( # for some reason, get_view returns a read-only buffer under Python # 2.7 on Windows with Pygame 1.9.2a0 surface.get_view() if IS_PYTHON3 and hasattr(surface, 'get_view') else surface.get_buffer(), ntracer.render.ImageFormat( surface.get_width(), surface.get_height(), self.last_channels[1], surface.get_pitch(), pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN), scene, on_complete) # When PyGame shuts down, it destroys all surface objects regardless of # reference counts, so any threads working with surfaces need to be stopped # first. def _quit_func(): for inst in PygameRenderer.instances: inst.abort_render() pygame.register_quit(_quit_func)
def main(): # init is a convenient way to initialize all subsystems # instead we could also initialize the submodules directly - for example by calling pygame.display.init(), pygame.display.quit() no_pass, no_fail = pygame.init() if no_fail > 0: print("Not all pygame modules initialized correctly") print(pygame.get_error()) else: print("All pygame modules initializes") if not pygame.font: print("Pygame - fonts not loaded") if not pygame.mixer: print("Pygame - audio not loaded") if not pygame.display: print("Pygame - display not loaded") if not pygame.mouse: print("Pygame - mouse not loaded") print("Did we initialize: {}".format(pygame.get_init())) print("Pygame Version: {}".format(pygame.ver)) print("Pygame runs on SDL Version: {}".format(pygame.get_sdl_version())) print("Pygame Display Driver: {}".format(pygame.display.get_driver())) pygame.register_quit(on_quit) w, h, t = 640, 480, "Elisa - 19.1 Collision Detection - QuadTree" c_white = (255, 255, 255) c_black = (0, 0, 0) c_blue = (0, 0, 255) c_light_blue = (64, 64, 255) c_red = (255, 0, 0) screen_buffer = pygame.display.set_mode(size=(w, h), flags=0) pygame.display.set_caption(t) pygame.mouse.set_visible(True) back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size()) back_buffer = back_buffer.convert() back_buffer.fill(c_white) # here we setup a pygamer clock - we will discuss this in a later example fps_watcher = pygame.time.Clock() is_done = False # we compose a scene of ... poly1 = Poly2(points=[(50, 150), (150, 125), (200, 100), (150, 200), (100, 175)]) poly2 = Poly2(points=[(350, 100), (500, 150), (400, 200), (250, 150)]) poly3 = Poly2(points=[(400, 300), (500, 300), (450, 325)]) poly4 = Poly2(points=[(600, 400), (630, 400), (600, 420)]) poly5 = Poly2(points=[(350, 250), (400, 250), (370, 300)]) poly6 = Poly2(points=[(350, 20), (400, 50), (370, 100)]) poly7 = Poly2(points=[(10, 10), (50, 10), (30, 30)]) entities = [poly1, poly2, poly3, poly4, poly5, poly6] # in this we assume that the oob is already computed, i.e. we define it here: poly1_oob = [(50, 150), (100, 50), (200, 100), (150, 200)] poly2_oob = [(350, 100), (500, 150), (400, 200), (250, 150)] world_bounds = Rect2.from_points(0, 0, w, h) q_tree = QuadTree(area=world_bounds, max_depth=2) for p in entities: q_tree.insert(p) entities.append(poly7) q_tree.insert(poly7) # for introspection print(q_tree) print("Removing poly: {}".format(q_tree.remove(poly7))) print(q_tree) # now we define a query region ... something that we might be interested in # when doing our collision detection proposal_region = Rect2.from_points(300, 220, 500, 320) # we are going to update one poly along the x-axis. # this will be based on copying/ creating new objects, which is somewhat wasteful # for the purposes of the tutorial and the current code base, this is what we do _move_x_min, _move_x_max = 100, 600 update_poly = poly5 dir_x = 1.0 while not is_done: _ = fps_watcher.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: is_done = True break back_buffer.fill(c_black) # update the two polys - this is wasteful ... _pminx, _pminy, _pmaxx, _pmaxy = update_poly.AABB if _pminx + (_pmaxx - _pminx) >= _move_x_max or _pminx <= _move_x_min: dir_x *= -1.0 dx = dir_x * 1.0 new_poly: Poly2 = Poly2.translate(update_poly, dx, 0.0) # update entities entities.remove(update_poly) entities.append(new_poly) # update the quad tree q_tree.replace(update_poly, new_poly) # replace the object identity update_poly = new_poly for r in q_tree: _r: Rect2 = r.points pygame.draw.polygon(back_buffer, c_white, _r, 1) pygame.draw.polygon(back_buffer, c_red, poly1_oob, 0) pygame.draw.polygon(back_buffer, c_red, poly2_oob, 0) for r in entities: pygame.draw.polygon(back_buffer, c_white, r.points, 1) pygame.draw.rect(back_buffer, c_blue, proposal_region.as_p_wh(), 1) proposals = q_tree.query(proposal_region) for p in proposals: pygame.draw.polygon(back_buffer, c_light_blue, p.points, 0) pygame.draw.polygon(back_buffer, c_blue, p.points, 1) if not is_done: screen_buffer.blit(back_buffer, (0, 0)) pygame.display.flip() pygame.quit()
source=self, scene=scene, surface=surface)) py_format = (surface.get_bitsize(),surface.get_masks()) if py_format != self.last_channels[0]: self.last_channels = (py_format,channels_from_surface(surface)) super(PygameRenderer,self).begin_render( # for some reason, get_view returns a read-only buffer under Python # 2.7 on Windows with Pygame 1.9.2a0 surface.get_view() if IS_PYTHON3 and hasattr(surface,'get_view') else surface.get_buffer(), ntracer.render.ImageFormat( surface.get_width(), surface.get_height(), self.last_channels[1], surface.get_pitch(), pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN), scene, on_complete) # When PyGame shuts down, it destroys all surface objects regardless of # reference counts, so any threads working with surfaces need to be stopped # first. def _quit_func(): for inst in PygameRenderer.instances: inst.abort_render() pygame.register_quit(_quit_func)
# coalition between ball and side wall if circle_y <= 10.: speed_y = -(speed_y * alpha) elif circle_y >= 457.5: speed_y = -(speed_y * alpha) # coalition between bars and side wall if bar1_y <= 7: bar1_y = 7 elif bar1_y >= 394: bar1_y = 394 if bar2_y <= 7: bar2_y = 7 elif bar2_y >= 394: bar2_y = 394 # score and results if bar2_score >= 11 and bar2_score > bar1_score + 2: print("Blue Player Wins") P1vsAL = False if bar1_score >= 11 and bar1_score > bar2_score + 2: print("Red Player Wins") P1vsAL = False # update pygame.display.update() pygame.register_quit(P1vsAL)
if circle_y <= 10.: speed_y = -(speed_y * alpha) circle_y = 10. elif circle_y >= 457.5: speed_y = -(speed_y * alpha) circle_y = 457.5 # coalition between bars and side wall if bar1_y <= 7: bar1_y = 7 elif bar1_y >= 394: bar1_y = 394 if bar2_y <= 7: bar2_y = 7 elif bar2_y >= 394: bar2_y = 394 # score and results if bar2_score >= 11 and bar2_score > bar1_score + 2: print("Blue Player Wins") P1vsP2 = False if bar1_score >= 11 and bar1_score > bar2_score + 2: print("Red Player Wins") P1vsP2 = False # update pygame.display.update() pygame.register_quit(P1vsP2)
def runGame(): # Initialize game and create a window pg.init() # create a new object using the settings class setting = Settings() # creaete a new object from pygame display screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight)) # set window caption using settings obj pg.display.set_caption(setting.windowCaption) playBtn = Button(setting, screen, "PLAY", 200) menuBtn = Button(setting, screen, "MENU", 250) twoPlayBtn = Button(setting, screen, "2PVS", 250) setBtnbtn = Button(setting, screen, "SETTING", 400) bgcrbtn = Button(setting, screen, "CL REV", 500) aboutBtn = Button(setting, screen, "ABOUT", 300) quitBtn = Button(setting, screen, "QUIT", 400) greyBtn = Button(setting, screen, "GREY", 200) redBtn = Button(setting, screen, "RED", 250) blueBtn = Button(setting, screen, "BLUE", 300) boonBtn = Button(setting, screen, "OFFSET", 550) # make slector for buttons sel = Selector(setting, screen) sel.rect.x = playBtn.rect.x + playBtn.width + 10 sel.rect.centery = playBtn.rect.centery # Create an instance to stor game stats stats = GameStats(setting) sb = Scoreboard(setting, screen, stats) # Make a ship ship = Ship(setting, screen) # Ships for two player ship1 = Ship(setting, screen) ship2 = Ship(setting, screen) # make a group of bullets to store bullets = Group() eBullets = Group() setting.explosions = Explosions() # Make an alien aliens = Group() gf.createFleet(setting, screen, ship, aliens) pg.display.set_icon(pg.transform.scale(ship.image, (32, 32))) # plays bgm pg.mixer.music.load("sound_bgms/galtron.mp3") pg.mixer.music.set_volume(0.25) pg.mixer.music.play(-1) rungame = True # Set the two while loops to start mainMenu first while rungame: # Set to true to run main game loop while stats.mainMenu: mm.checkEvents(setting, screen, stats, sb, playBtn, twoPlayBtn, aboutBtn, quitBtn, menuBtn, setBtnbtn, sel, ship, aliens, bullets, eBullets) mm.drawMenu(setting, screen, sb, playBtn, menuBtn, twoPlayBtn, aboutBtn, quitBtn, setBtnbtn, sel) while stats.playMenu: pm.checkEvents(setting, screen, stats, sb, playBtn, greyBtn, redBtn, blueBtn, quitBtn, menuBtn, sel, ship, aliens, bullets, eBullets) pm.drawMenu(setting, screen, sb, greyBtn, redBtn, blueBtn, menuBtn, quitBtn, sel) while stats.mainGame: # Game functions gf.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, menuBtn, sel, ship, aliens, bullets, eBullets) # Check for events # Reset Game if gf.reset == 1: gf.reset = 0 pg.register_quit(runGame()) if stats.gameActive: gf.updateAliens(setting, stats, sb, screen, ship, aliens, bullets, eBullets) # Update aliens gf.updateBullets(setting, screen, stats, sb, ship, aliens, bullets, eBullets) # Update collisions ship.update(bullets, aliens) # update the ship # Update the screen gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets, eBullets, playBtn, menuBtn, quitBtn, setBtnbtn, sel) while stats.mainAbout: About.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, menuBtn, sel, ship, aliens, bullets, eBullets) About.drawMenu(setting, screen, sb, menuBtn, quitBtn, sel) while stats.twoPlayer: tp.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, sel, bullets, aliens, eBullets, ship1, ship2) if stats.gameActive: ship1.update(bullets, aliens) ship2.update(bullets, aliens) tp.updateBullets(setting, screen, stats, sb, ship1, ship2, aliens, bullets, eBullets) tp.updateScreen(setting, screen, stats, sb, ship1, ship2, aliens, bullets, eBullets, playBtn, menuBtn, quitBtn, sel) # ship1.update(bullets) # ship2.update(bullets) # tp.updateBullets(setting, screen, stats, ship1, ship2, bullets, eBullets) # tp.updateScreen(setting, screen, stats, bullets, eBullets, playBtn, menuBtn, quitBtn, sel, ship1, ship2) while stats.settingsMenu: sm.checkEvents1(setting, screen, stats, sb, playBtn, quitBtn, menuBtn, sel, ship, aliens, bullets, eBullets) sm.drawMenu(setting, screen, sb, menuBtn, quitBtn, bgcrbtn, boonBtn, sel) while stats.mainGame: if rungame == True: print("test")
pygame.register_quit(self.quit) while self.running: event = pygame.event.wait() if event.type == pygame.QUIT: pygame.quit() self.running = False event.dict["type"]=event.type self.channel.basic_publish(exchange="events", routing_key=str(event.type), body="{}".format(event.dict)) print "S out",event.dict disp = Display() EventPublisher(disp) pygame.register_quit(connection.close) def callback(ch, method, properties, body): global disp print "S in",body try: eval("disp.{}".format(body)) #... i shouldn't even test with this in... except: print "Exception." pass # ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_consume(callback, queue='graphics', no_ack=True) for i in [channel.start_consuming,pygame.quit]:
def main(): # init is a convenient way to initialize all subsystems # instead we could also initialize the submodules directly - for example by calling pygame.display.init(), pygame.display.quit() no_pass, no_fail = pygame.init() if no_fail > 0: print("Not all pygame modules initialized correctly") print(pygame.get_error()) else: print("All pygame modules initializes") if not pygame.font: print("Pygame - fonts not loaded") if not pygame.mixer: print("Pygame - audio not loaded") if not pygame.display: print("Pygame - display not loaded") if not pygame.mouse: print("Pygame - mouse not loaded") print("Did we initialize: {}".format(pygame.get_init())) print("Pygame Version: {}".format(pygame.ver)) print("Pygame runs on SDL Version: {}".format(pygame.get_sdl_version())) print("Pygame Display Driver: {}".format(pygame.display.get_driver())) # for pontential cleanup of other resources, we register a quit handler. This handler will be invoked whenever # pygame enters the quit state. pygame.register_quit(on_quit) w, h, t = 640, 480, "Elisa - 0 Pygame Initialization" c_white = (255, 255, 255) # here we create a display surface of width and height: https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode # we have different options to create a display surface, such as enabling double buffering, preparing it for opengl # removing borders or going full screen. However, we will not do any of this, by using the flags=0 # this will create a default software rasterizer supported window of size, no full screen and default layout. # Setting the display mode will also return a buffer object/ pixel surface, that we can draw to. # then we set the window's caption and icon title (for shorter displays) # Then we make the mouse cursor visible screen_buffer = pygame.display.set_mode(size=(w, h), flags=0) pygame.display.set_caption(t, "Elisa 0") pygame.mouse.set_visible(True) # the next lines are concerned with supporting a double-buffered drawing approach. # in double-buffered drawing one does not draw to the display surface directly, in order to avoid drawing/ refresh issues. # instead one draws to a back buffer and when time comes then the image fully drawn to the back buffer will be copied to the displayed # front buffer. # # So we setup a back buffer, that matches our visible screen buffer in size, and for the time being clear it with white color. # Later on, we constantly copy (blit) our back buffer to the front buffer associated with the display and then flip, such # what is drawn to the back buffer becomes visible to our eyes - for the time being only a white canvas. back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size()) back_buffer = back_buffer.convert() back_buffer.fill(c_white) # here we setup a pygamer clock - we will discuss this in a later example fps_watcher = pygame.time.Clock() is_done = False verbose = False # Now, we are ready to setup our game loop, where we loop until our application/ game is done - then we break from the loop. # As you can see, there is only condition that exits from the loop - and that is when the application receives a QUIT event message. # One way to receive this message is by clicking the closing button of the window. # Another way is to send ctrl+c in the console window. while not is_done: elapsed_millis = fps_watcher.tick(60) if verbose: print("Milli Seconds Elapsed: ", elapsed_millis) for event in pygame.event.get(): if event.type == pygame.QUIT: is_done = True break if not is_done: screen_buffer.blit(back_buffer, (0, 0)) pygame.display.flip() # after exiting the loop we call it Quit - this will invoke our Quit handler and we are free to perform any heavy clean up lifting # such as freeing memory or releasing any other resources pygame.quit()
def __init__(self, game): """ Set up pygame and handle events. Your game should subclass this class. Args: ---- game - None, since it *is* the game. options - the configuration options passed via the command line. """ parser = argparse.ArgumentParser(f"{game.NAME} version {game.VERSION}") parser = GameEngine.args(parser) # args is a class method, which allows us to call it before initializing a game # object, which allows us to query all of the game engine objects for their # command line parameters. try: game.args( parser.add_argument_group( f'{game.NAME} v{game.VERSION} Options')) except AttributeError: self.log.info('Game does not implement arguments. ' 'Add a def args(parser) class method.') args = parser.parse_args() GameEngine.OPTIONS = vars(args) options = GameEngine.OPTIONS # TODO: Decouple game from event manager # so we can have clean separation for unhandled events super().__init__() self._active_scene = None # Pygame stuff. pygame.register_quit(self.quit) self.fps = options.get('fps', 0) self.update_type = options.get('update_type') self.use_gfxdraw = options.get('use_gfxdraw') self.windowed = options.get('windowed') self.desired_resolution = options.get('resolution') self.fps_refresh_rate = options.get('fps_refresh_rate') # Initialize all of the Pygame modules. self.init_pass, self.init_fail = pygame.init() self.print_game_info() # Enable fast events for multithreaded applications pygame.fastevent.init() # We are fully initialized now, so we can set up the scene. # # The scene will start once .start() is called on the GameEngine # object GameEngine.game = game self.scene_manager = SceneManager() # Resolution initialization. # Convert our resolution to a tuple (desired_width, desired_height) = self.desired_resolution.split('x') if self.windowed: self.mode_flags = 0 else: self.mode_flags = pygame.FULLSCREEN self.desired_resolution = self.suggested_resolution( desired_width, desired_height) # window icon and system tray/dock icon self.initialize_system_icons() # Let's try to set a resolution to the most compatible for # the system. If we don't provide any parameters, we'll get # a reasonble default, but you should consider whether that's # a good idea for your particular application. # # There are various caveats for hardware accelerated blitting # that make it undesirable in a lot of cases, so we'll just use # software. self.display_info = pygame.display.Info() self.initial_resolution = (self.display_info.current_w, self.display_info.current_h) self.cursor = self.set_cursor(cursor=None) # Set the screen update type. if self.scene_manager.update_type == 'update': self.display_update = pygame.display.update elif self.scene_manager.update_type == 'flip': self.display_update = pygame.display.flip else: self.log.error( 'Screen update type was neither "update" nor "flip".') # The Pygame documentation recommends against using hardware accelerated blitting. # # Note that you can also get the screen with pygame.display.get_surface() self.screen = pygame.display.set_mode(self.desired_resolution, self.mode_flags) self.print_system_info()
def init(): pg.init() pg.register_quit(quit)