def main(): global win clock.schedule(rabbyt.add_time) win = Window(width=800, height=600) rabbyt.set_default_attribs() lawn = Lawn() wind = Wind() magicEventRegister(win, events, list(lawn)) while not win.has_exit: tick = clock.tick() win.dispatch_events() lawn.update(tick) wind.update(tick) events.ConsumeEventQueue() rabbyt.clear((1, 1, 1)) lawn.draw() win.flip()
def main(): global fps_display win = Window(width=800, height=600) clock.schedule(rabbyt.add_time) rabbyt.set_default_attribs() bg = Background() fps_display = clock.ClockDisplay() while not win.has_exit: tick = clock.tick() win.dispatch_events() bg.update(tick) rabbyt.clear((bg.color)) bg.draw() fps_display.draw() win.flip()
def main(): # Create the main window window = Window(800, 600, visible=False, caption="FF:Tactics.py", style='dialog') # Create the default camera and have it always updating camera = Camera((-600, -300, 1400, 600), (400, 300), 300, speed=PEPPY) clock.schedule(camera.update) # Load the first scene world = World(window, camera) world.transition(MainMenuScene) # centre the window on whichever screen it is currently on window.set_location(window.screen.width/2 - window.width/2, window.screen.height/2 - window.height/2) # clear and flip the window # otherwise we see junk in the buffer before the first frame window.clear() window.flip() # make the window visible at last window.set_visible(True) # finally, run the application pyglet.app.run()
class Gameloop(object): def __init__(self): self.window = None def init(self): self.world = World() self.world.init() populate(self.world) bitmaps = Bitmaps() bitmaps.load() self.render = Render(bitmaps) self.camera = Camera(zoom=10.0) self.window = Window(fullscreen=False, visible=False) self.window.set_exclusive_mouse(True) self.window.on_draw = self.draw self.window.on_resize = self.render.resize self.controls = Controls(self.world.bat) self.window.set_handlers(self.controls) self.render.init() clock.schedule(self.update) self.hud_fps = clock.ClockDisplay() self.window.set_visible() def update(self, dt): # scale dt such that the 'standard' framerate of 60fps gives dt=1.0 dt *= 60.0 # don't attempt to compensate for framerate of less than 30fps. This # guards against huge explosion when game is paused for any reason # and then restarted dt = min(dt, 2) self.controls.update() self.world.update() self.window.invalid = True def draw(self): self.window.clear() self.camera.world_projection(self.window.width, self.window.height) self.camera.look_at() self.render.draw(self.world) self.hud_fps.draw() return EVENT_HANDLED def stop(self): if self.window: self.window.close()
class Gameloop(object): def __init__(self): self.camera = None self.projection = None self.render = None self.window = None self.world = None self.fpss = [] def prepare(self, options): self.window = Window(fullscreen=options.fullscreen, vsync=False, visible=False, resizable=True) self.window.on_draw = self.draw self.projection = Projection(self.window.width, self.window.height) self.window.on_resize = self.projection.resize self.world = World() self.camera = Camera() self.world.add(GameItem(camera=self.camera, position=Origin, move=WobblyOrbit(32, 1, speed=-0.5))) self.render = Render(self.world) self.render.init() pyglet.clock.schedule(self.update) self.clock_display = pyglet.clock.ClockDisplay() vs = VertexShader(join("flyinghigh", "shaders", "lighting.vert")) fs = FragmentShader(join("flyinghigh", "shaders", "lighting.frag")) shader = ShaderProgram(vs, fs) shader.use() def update(self, dt): # self.fpss.append(1/max(1e-3, dt)) dt = min(dt, 1 / 30) self.world.update(dt) self.window.invalid = True def draw(self): self.window.clear() self.projection.set_perspective(45) self.camera.look_at(Origin) self.render.draw() self.projection.set_screen() self.camera.reset() self.render.draw_hud(self.clock_display) return EVENT_HANDLED def stop(self): if self.window: self.window.close()
def __init__(self, view_size=(10,10),scale=(10),*args, **kwargs): Window.__init__(self, *args, **kwargs) self.set_mouse_visible(True) self.view_scale = scale#min(self.width/view_size[0],self.height/view_size[1]) self.view_size = view_size self.undo = UndoManager(self) self.width = self.view_scale*self.view_size[0] self.height = self.view_scale*self.view_size[1] self.setup()
def main(): win = Window(fullscreen=True) win.on_resize = on_resize try: try: install_shaders('allGreen.frag', 'zoomRotate.vert') except ShaderError, e: print str(e) return 2 win.on_draw = lambda: on_draw(win) app.run()
def _create_shadow_window(): global _shadow_window import pyglet if not pyglet.options['shadow_window'] or _is_epydoc: return from pyglet.window import Window _shadow_window = Window(width=1, height=1, visible=False) _shadow_window.switch_to() from pyglet import app app.windows.remove(_shadow_window)
def main(): win = Window(fullscreen=True, visible=False) camera = Camera(win.width, win.height, (0, 0), 100) renderer = Renderer() maze = Maze() maze.create(50, 30, 300) keyboard = Keyboard() keyboard.key_handlers[key.ESCAPE] = win.close keyboard.key_handlers.update(camera.key_handlers) clock.schedule(maze.update) win.on_draw = lambda: renderer.on_draw(maze, camera, win.width, win.height) win.on_key_press = keyboard.on_key_press keyboard.print_handlers() win.set_visible() app.run()
class PygletApp(object): def __init__(self): self.window = Window(visible=False, fullscreen=False) self.window.on_resize = self.on_resize self.window.on_draw = self.on_draw self.window.on_key_press = self.on_key_press self.files = SvgFiles() glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt( 0.0, -0.0, 1.0, # eye 0.0, -0.0, -1.0, # lookAt 0.0, 1.0, 0.0) # up def on_draw(self): glClear(GL_COLOR_BUFFER_BIT) self.files.draw() return EVENT_HANDLED def on_resize(self, width, height): # scale is distance from screen centre to top or bottom, in world coords scale = 110 glMatrixMode(GL_PROJECTION) glLoadIdentity() aspect = width / height gluOrtho2D( -scale * aspect, +scale * aspect, -scale, +scale) return EVENT_HANDLED def on_key_press(self, symbol, modifiers): if symbol == key.ESCAPE: self.window.close() return self.files.next() def run(self): self.window.set_visible() app.run()
def __init__(self): self.win = Window(fullscreen=True, visible=False) self.clockDisplay = clock.ClockDisplay() glClearColor(0.2, 0.2, 0.2, 1) self.camera = Camera((0, 0), 250) self.space = pymunk.Space() #2 self.space.gravity = (0, -500.0) self.space.damping = 0.999 self.map = alone.Map(self.space) self.player = alone.Player(*self.map.to_world(1,2)) self.space.add(self.player.box, self.player.body) self.space.add_collision_handler(0, 0, None, None, self.print_collision, None) self.balls = [] self.lamps = [alone.Lamp(*self.map.to_world(4, 3))] #self.powerups = [alone.Powerup(*self.map.to_world(1, 4))] darkImage = pyglet.resource.image('dark.png') winSize = self.win.get_size() self.darkness = pyglet.sprite.Sprite(darkImage, x=0, y=0) self.darkness.scale = winSize[0]/darkImage.width backgroundImage = pyglet.resource.image('background.png') self.background = pyglet.sprite.Sprite(backgroundImage, x=0, y=0) self.background.scale = winSize[0]/backgroundImage.width self.camera.setTarget(0, 0)
def run(self, name, texture): #Sets up name and texture self.texture = texture self.name = name #Sets up images self.block_textures = pyglet.image.load(os.getcwd()+"/Resources"+self.texture+"Blocks/Textures.png") self.blocks_textures = pyglet.image.ImageGrid(self.block_textures, 5, 1) #Reads data self.extract_data() #Generates tiles and stuff self.generate_map() #Sets up window self.window = Window(800,600) self.window.set_icon(self.blocks_textures[1]) #Generates sprites to show at start self.screen_render_start(0,0) #Runs it pyglet.app.run()
def __init__(self, size=(DEFAULT_WIDTH, DEFAULT_HEIGHT), title='MegaMinerAI Bland Title Text', fullscreen=False): self.window = Window(width=size[0], height=size[1], caption=title, visible=True, fullscreen=fullscreen, resizable=True, style=Window.WINDOW_STYLE_DEFAULT, vsync=False, display=None, context=None, config=None) self.updates = []
def __init__(self): vs = True # limit FPS or something try: # Try and create a window with multisampling (antialiasing) config = Config(sample_buffers=1, samples=4, depth_size=16, double_buffer=True,) GLWindow.__init__(self, self.sizeX, self.sizeY, vsync=vs, resizable=False, config=config) except pyglet.window.NoSuchConfigException: # Fall back to no multisampling for old hardware super(Melee, self).__init__(self.sizeX, self.sizeY, vsync=vs, resizable=False) # Initialize OpenGL squirtle.setup_gl()
def prepare(self, options): self.window = Window( fullscreen=options.fullscreen, vsync=options.vsync, visible=False, resizable=True) self.window.on_draw = self.draw_window self.world = World() self.player = Player(self.world) self.camera = GameItem( position=origin, update=CameraMan(self.player, (3, 2, 0)), ) self.level_loader = Level(self) success = self.start_level(1) if not success: logging.error("ERROR, can't load level 1") sys.exit(1) self.update(1/60) self.window.push_handlers(KeyHandler(self.player)) self.render = Render(self.world, self.window, self.camera) self.render.init() self.music = Music() self.music.load() self.music.play()
def prepare(self, options): self.window = Window( fullscreen=options.fullscreen, vsync=False, visible=False, resizable=True) self.window.on_draw = self.draw self.projection = Projection(self.window.width, self.window.height) self.window.on_resize = self.projection.resize self.world = World() self.camera = Camera() self.world.add( GameItem( camera=self.camera, position=Origin, move=WobblyOrbit(32, 1, speed=-0.5), ) ) self.render = Render(self.world) self.render.init() pyglet.clock.schedule(self.update) self.clock_display = pyglet.clock.ClockDisplay() vs = VertexShader(join('flyinghigh', 'shaders', 'lighting.vert')) fs = FragmentShader(join('flyinghigh', 'shaders', 'lighting.frag')) shader = ShaderProgram(vs, fs) shader.use()
def __init__(self, pmap): self.world = World(pmap) self.win = Window(width=pmap['bounds'][2], height=pmap['bounds'][3]) # pyglet.clock.set_fps_limit(10) # pyglet.clock.set_fps_limit(60) self.win.push_handlers(self.on_key_press) self.fullscreen = False
def launch(self): self.win = Window( width=1024, height=768, vsync=self.vsync, visible=False) self.win.set_mouse_visible(False) GameItem.win = self.win load_sounds() self.music = Music() self.music.load() self.music.play() keystate = key.KeyStateHandler() self.win.push_handlers(keystate) game = Game(keystate, self.win.width, self.win.height) handlers = { key.M: self.toggle_music, key.F4: self.toggle_vsync, key.ESCAPE: self.exit, } game.add(KeyHandler(handlers)) render = Render(game) render.init(self.win) game.startup(self.win) self.win.set_visible() pyglet.app.run()
def setUp(self): self.w = Window(width=1, height=1, visible=False) self.s = Sprite(10, 10, 10, 10, Image2d.from_image(SolidColorImagePattern((0, 0, 0, 0)).create_image( 1, 1))) assert (self.s.x, self.s.y) == (10, 10)
def setUp(self): self.window = Window( width=200, height=100, visible=False, caption="Camera_test setup") self.window.dispatch_events() glClearColor(0, 0, 0, 1) self.window.clear() self.world = World() self.camera = Camera((0, 0), 1)
def __init__(self): self.map_objects = [] self.player_objects = [] self.players = {} self.mini_objects = [] self.window = Window(width=1300, height=768) self.stop_update = False
class Application(object): def __init__(self): self.win = None self.music = None self.vsync = ( not settings.has_option('all', 'vsync') or settings.getboolean('all', 'vsync') ) def launch(self): self.win = Window( width=1024, height=768, vsync=self.vsync, visible=False) self.win.set_mouse_visible(False) GameItem.win = self.win load_sounds() self.music = Music() self.music.load() self.music.play() keystate = key.KeyStateHandler() self.win.push_handlers(keystate) game = Game(keystate, self.win.width, self.win.height) handlers = { key.M: self.toggle_music, key.F4: self.toggle_vsync, key.ESCAPE: self.exit, } game.add(KeyHandler(handlers)) render = Render(game) render.init(self.win) game.startup(self.win) self.win.set_visible() pyglet.app.run() def toggle_vsync(self): self.vsync = not self.vsync self.win.set_vsync(self.vsync) def toggle_music(self): self.music.toggle() def exit(self): self.win.has_exit = True
def main(): clock.schedule(rabbyt.add_time) win = Window(width=800, height=600) rabbyt.set_default_attribs() lawn = NewLawn() while not win.has_exit: tick = clock.tick() win.dispatch_events() lawn.update(tick) rabbyt.clear((1, 1, 1)) lawn.draw() win.flip()
def __init__(self): self.icons = Icons() #self.sounds = Sounds() Window.__init__(self) glEnable(GL_DEPTH_TEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.set_caption(AppTitle) self.set_icon(self.icons.Icon16) # self.btnStart = pyglet.input.Button('Jugar') # self.btnConfig = pyglet.input.Button('Config') # self.btnAbout = pyglet.input.Button('Acerca') self.titlelabel = pyglet.text.Label(Title, font_name='Tahoma', font_size=32, x = self.width // 2, y = self.height // 2, anchor_x='center', anchor_y='center' )
def test_world_projection_strange_aspect(self): # create a new window, since # resizing the existing window doesn't work for some reason # even if we dispatch events. Default handlers? self.window.close() self.window = Window( width=100, height=200, visible=False, caption="world.test_projection_strange_aspect") self.window.dispatch_events() rect = (-0.2, -0.4, +0.6, +0.8) expectedRect = (40, 60, 79, 119) self.assert_world_projection(rect, expectedRect)
def test_set_visible(self): self.width, self.height = 200, 200 self.w = w = Window(self.width, self.height) try: w.push_handlers(self) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.flip() w.dispatch_events() finally: w.close() self.user_verify('Pass test?', take_screenshot=False)
def __init__(self, width, height): # display initializations self.__window = Window(width, height, vsync=True) self.__background_color = (0, 0, 0, 1.0) # self._fps_display = pyglet.clock.ClockDisplay() self.__key_state_handler = key.KeyStateHandler() self.__scene = None self.__window.event(self.on_draw) self.__window.push_handlers(self.__key_state_handler) self.__camera = None #schedule regular updates pyglet.clock.schedule_interval(self.update, 1 / 100.0)
def test_set_size(self): self.width, self.height = 200, 200 self.w = w = Window(self.width, self.height) try: w.push_handlers(self) while not w.has_exit: window_util.draw_client_border(w) w.flip() w.dispatch_events() finally: w.close() self.user_verify('Pass test?', take_screenshot=False)
def __init__(self, config, filename=None, caption='Pyno', style=Window.WINDOW_STYLE_DEFAULT): Window.__init__(self, resizable=True, caption=caption, config=config, style=style) Process.__init__(self) self.set_minimum_size(320, 200) self.set_size(800, 600) # set window position to center screen = self.display.get_default_screen() self.set_location(screen.width // 2 - 400, screen.height // 2 - 300) pyglet.clock.schedule_interval(self.update, 0.016) # ~60fps pyglet.clock.schedule_interval(lambda x: self.info(), 1) # drop time arg pyglet.clock.schedule_interval(lambda x: self.autosave(), 30) self.active_nodes = [] self.selected_nodes = [] self.code_editor = None self.field = None self.node_drag = False self.select = False self.connection = False self.connecting_node = None self.nodes_check = 0 self.w, self.c = (0, 0), (0, 0) self.mouse = (0, 0) self.pointer = (0, 0) self.line = () self.pan_scale = [[0.0, 0.0], 1] self.batch = None self.info_label, self.pyno_logo, self.menu = None, None, None self.new_batch() if filename: # open auto-save or welcome-file welcome = pkg_resources.resource_filename('pyno', 'examples/welcome.pn') (self.load_pyno(filename) or self.load_pyno(welcome))
def __init__(self, background_color=dark_gray, clock=mono_clock.get_time): # TODO: if committing to moderngl, make & store the context here? # lazy load, partially to avoid auto-formatter that wants to # do imports, *then* dict setting from pyglet import gl from pyglet.window import Window self._background_color = Vector4f(background_color) self.clock = clock self.current_time = 0 self.prev_time = 0 # can bump down `samples` if performance is hurting config = gl.Config(depth_size=0, double_buffer=True, alpha_size=8, sample_buffers=1, samples=4, vsync=False, major_version=3, minor_version=3) display = pyglet.canvas.get_display() screen = display.get_screens()[0] self._win = Window(resizable=False, fullscreen=True, screen=screen, config=config, style='borderless', vsync=True) self._win.event(self.on_key_press) atexit.register(self._on_close) self.context = mgl.create_context( require=int('%i%i0' % (config.major_version, config.minor_version))) self.context.viewport = (0, 0, self.width, self.height) self.context.enable(mgl.BLEND) self.frame_period # do this before we've drawn anything # in principle, should be disconnected from the window # but we're saving time & mental energy self.cam = Camera(projection=height_ortho(self.width, self.height))
class App(object): def __init__(self, pmap): self.world = World(pmap) self.win = Window(width=pmap['bounds'][2], height=pmap['bounds'][3]) # pyglet.clock.set_fps_limit(10) # pyglet.clock.set_fps_limit(60) self.win.push_handlers(self.on_key_press) self.fullscreen = False def main_loop(self): self.world.annealing.kickoff() while not (self.win.has_exit or self.world.finished): self.win.dispatch_events() if (not self.world.finished) and (not self.world.pause): self.world.update() if (self.world.showvisuals): self.world.draw() pyglet.clock.tick() self.win.flip() self.win.close() def on_key_press(self, symbol, modifiers): # IDEA more key toggles, make it a dictionary if symbol == key.D: self.world.showdebug = not self.world.showdebug elif symbol == key.F: self.fullscreen = not self.fullscreen self.win.set_fullscreen(fullscreen=self.fullscreen) self.world.draw() elif symbol == key.G: self.world.showgrid = not self.world.showgrid elif symbol == key.S: self.world.pause = not self.world.pause elif symbol == key.U: self.world.showUI = not self.world.showUI elif symbol == key.V: self.world.showvisuals = not self.world.showvisuals
def __init__(self): display = pyglet.canvas.get_display() config = display.get_default_screen().get_best_config(Config()) config.major_version = 3 config.minor_version = 3 context = config.create_context(None) Window.__init__(self, 800, 600, visible=False, resizable=True, caption='Tinyblend example', context=context) self.vao = (GLuint * 1)() glGenVertexArrays(1, self.vao) glBindVertexArray(self.vao[0]) # Load shaders shader = shaders.from_files_names('shaders/main.glsl.vert', 'shaders/main.glsl.frag') shader.owned = False shader.use() shader.enable_all_attributes() self.shader = shader # Uniforms matrices setup self.rotation = [-90, 0, 0] self.position = [0, 0, -4.5] shaders.transpose_matrices(False) self.upload_uniforms() # Scene creation self.setup_scene() # Show the window self.set_visible()
def __init__(self): self.window = Window(visible=False, fullscreen=False) self.window.on_resize = self.on_resize self.window.on_draw = self.on_draw self.window.on_key_press = self.on_key_press self.files = SvgFiles() glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt( 0.0, -0.0, 1.0, # eye 0.0, -0.0, -1.0, # lookAt 0.0, 1.0, 0.0) # up
def _test_main(self): assert self.question self.window = w = Window(**self._get_window_options()) try: w.push_handlers(self) self.render() w.set_visible() w.dispatch_events() self.user_verify(cleandoc(self.question), self.take_screenshot) finally: w.close()
def __init__(self, game): # While the game needs to work independently of the client the client # can't work independently of the game. The client will be sending # input to the game as well as looking up different elements (such as # all the blocks so we can draw them and tell the game when we click on # one). self.game = game # Setup our pyglet window. self.window = Window(width=self.game.size_xy[0]*20, height=self.game.size_xy[1]*20+50) self.window.set_caption("Mines") self.window.on_close = sys.exit # The default pyglet OpenGL display is setup a bit different than how # rabbyt would like, thus rabbyt.set_default_attribs rabbyt.set_default_attribs() # Using pyglet for input is really easy. When you get further down # you'll see GameContorl inherits from EventDispatcher. That's how # window.push_handlers does the magic as we'll see further down. self.ctrl = GameContorl(self) self.window.push_handlers(self.ctrl) # Here we have some sprites we are going to use for the client. For # bigger games I think it's better to separate stuff like this out; # but this is quite small and not an issue. self.smile_face = rabbyt.Sprite("data/smile.png") self.smile_face.x = self.window.width/2 self.smile_face.y = self.window.height-25 self.dead_face = rabbyt.Sprite("data/smile_dead.png") self.dead_face.xy = self.smile_face.xy self.won_face = rabbyt.Sprite("data/smile_won.png") self.won_face.xy = self.smile_face.xy # That sprite stuff was pretty self explanatory. It is also very basic. # I'm not going to be going into much depth with rabbyt in these # tutorials so you may want to check out the rabbyt documentation from # http://matthewmarshall.org/projects/rabbyt/ # Very cool and elegant stuff there. Check it out! self.clock = Clock() self.clock.set_fps_limit(20) self.window.push_handlers(self.clock) self.time = 0 self.clock.schedule(self._add_time) self.setup()
def test_set_mouse_cursor(self): self.width, self.height = 200, 200 self.w = w = Window(self.width, self.height) try: img = image.load(self.get_test_data_file('images', 'cursor.png')) w.set_mouse_cursor(ImageMouseCursor(img, 4, 28)) w.push_handlers(self) glClearColor(1, 1, 1, 1) while not w.has_exit: glClear(GL_COLOR_BUFFER_BIT) w.flip() w.dispatch_events() finally: w.close() self.user_verify('Pass test?', take_screenshot=False)
def main(): """ app container? """ win_width = 800 win_height = 600 random.seed(1) world = World(random, 128, 128) window = Window(width=win_width, height=win_height, vsync=True) # window = Window(fullscreen=True, vsync=True) camera = Camera(0, 0, 0) game = Game(world=world, window=window, camera=camera) game.start()
def __init__(self,a_world): # super(MainWnd,self).__init__() Window.__init__(self) # init GL options glEnable(GL_CULL_FACE) glFrontFace(GL_CCW) glCullFace(GL_BACK) glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_LINE) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) # create the world self.the_world=a_world # create the camera self.the_camera=camera.Camera() self.the_camera.x=400 self.the_camera.y=-350 self.the_camera.z=80
def __init__(self, a_world): # super(MainWnd,self).__init__() Window.__init__(self) # init GL options glEnable(GL_CULL_FACE) glFrontFace(GL_CCW) glCullFace(GL_BACK) glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_LINE) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) # create the world self.the_world = a_world # create the camera self.the_camera = camera.Camera() self.the_camera.x = 400 self.the_camera.y = -350 self.the_camera.z = 80
class Game(): def __init__(self): gl.glEnable(gl.GL_TEXTURE_2D) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.window = Window(width=640, height=360, resizable=True) self.window.config.alpha_size = 8 gl.glEnable(gl.GL_BLEND) self.window.set_caption('KeysManiac (development build)') Grid.set_factor_from_resolution(*self.window.get_size()) self.window.push_handlers(self) self.scene = None def load_scene(self, scene_class): context = None if self.scene: context = self.scene.context self.scene.unload() new_scene = scene_class(game=self, context=context) new_scene.load() self.scene = new_scene def on_draw(self): if not self.scene: logging.warning('No scene has been loaded') return self.window.clear() self.scene.draw() def on_resize(self, width, height): Grid.set_factor_from_resolution(width, height) if not self.scene: return self.scene.resize() def on_activate(self): self.on_draw() def on_key_press(self, symbol, modifiers): if not self.scene: return self.scene.on_key_press(symbol, modifiers) def on_key_release(self, symbol, modifiers): if not self.scene: return self.scene.on_key_release(symbol, modifiers)
def create(title, size, full_screen, resizable): _window = _Window(width=size[0], height=size[1], caption=title, fullscreen=full_screen, resizable=resizable) window = Window(_window) _WindowsMap[_window] = window _Windows.add(window) window._last_frame_time = None window._current_start_time = None window._current_frame_time = None window._draw_time = datetime.timedelta() window._frame_delta = None window._target_fps = None on_draw_finished_event = window.event['on_draw_finished'] @on_draw_finished_event.add_listener def update_frame_metrics(): window._last_frame_time, window._current_frame_time = window._current_frame_time, time.perf_counter( ) window._draw_time = datetime.timedelta( seconds=window._current_frame_time - window._current_start_time) if window._last_frame_time: window._frame_delta = datetime.timedelta( seconds=window._current_frame_time - window._last_frame_time) runner.current_renderer = window._renderer if runner.running: runner.tasks_set.add(asyncio.create_task(window.draw_schedule())) return window
def main(): font.add_directory(FONT_DIR) FPS = 60 WINDOW_SIZE = Vector(920, 760) window = Window(WINDOW_SIZE.x, WINDOW_SIZE.y, caption = "Kort!!!") sjuan = Sjuan(game, RectangleShape( bottom_left = Vector(0, 0), size = WINDOW_SIZE )) @window.event def on_draw(): window.clear() sjuan._world.draw() @window.event def on_mouse_motion(*args): sjuan._world.mouse_at(*args) @window.event def on_mouse_drag(*args): sjuan._world.mouse_at(*args) @window.event def on_mouse_press(*args): sjuan._world.mouse_down(*args) @window.event def on_mouse_release(*args): sjuan._world.mouse_up(*args) @window.event def on_mouse_scroll(*args): sjuan._world.mouse_scroll(*args) def update(dt): pass pyglet.clock.schedule_interval(update, 1 / FPS) pyglet.app.run()
def _test_main(self): assert self.question width, height = self.window_size self.window = w = Window(width, height, visible=False, resizable=False) try: w.push_handlers(self) self._render_question() w.set_visible() while not self.finished and not w.has_exit: self._draw() w.dispatch_events() finally: w.close() # TODO: Allow entering reason of failure if user aborts self.assertTrue(self.finished, msg="Test aborted") self.assertIsNone(self.failure, msg=self.failure)
def test_set_icon_sizes(self): self.width, self.height = 200, 200 self.w = w = Window(self.width, self.height) try: w.set_icon( image.load(self.get_test_data_file('images', 'icon_size1.png')), image.load(self.get_test_data_file('images', 'icon_size2.png')), image.load(self.get_test_data_file('images', 'icon_size3.png')), image.load(self.get_test_data_file('images', 'icon_size4.png')), image.load(self.get_test_data_file('images', 'icon_size5.png'))) w.dispatch_events() self.user_verify( 'Does the window have the icon corresponding to the correct size?', take_screenshot=False) finally: w.close()
import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from pyglet import app, clock, graphics, gl from pyglet.window import Window, mouse from pyglet.window.key import symbol_string from squiglet import Vector win = Window() class Ship(object): def __init__(self,colour): self.vector = Vector(colour,"ship.sgl") self.pos = (0,0) def draw(self): self.vector.draw(7,self.pos) ships = [Ship((255,0,0)),Ship((0,255,0)),Ship((0,0,255))] @win.event def on_draw(): win.clear() for ship in ships: ship.draw() @win.event def on_mouse_motion(x,y,dx,dy): offset = -60
print "\tdown is pushed" if not state: print "\tdown is released" # SPACJA print state = subject.get_key_state("space") if state: print "\tspace is pushed" if not state: print "\tspace is released" # Utworzenie InputManagera i włączenie go do pygleta manager = InputManager() window = Window() window.on_key_press = manager.key_pressed window.on_key_release = manager.key_released # Tworzymy 3 obiekty obserwujące ops1 = ConcreteInputObserver('ops1') ops2 = ConcreteInputObserver('ops2') ops3 = ConcreteInputObserver('ops3') # dodajemy obserwatorów manager.register_observer(ops1) manager.register_observer(ops2) manager.register_observer(ops3) # usuwamy obserwatorów manager.unregister_observer(ops1)
drawn in a single batch.draw() call. """ from math import pi from random import randint, uniform from sys import stdout from pyglet import app, clock from pyglet.window import key, Window from pyglet.window.key import symbol_string from army import Army, rand_point from camera import Camera from data import all_ghosts, pacman from creature import Creature from keyboard import on_key_press, key_handlers from renderer import Renderer win = Window(fullscreen=True, visible=False) camera = Camera((0, 0), 10) renderer = Renderer() army_shape = Army.MakeShape(400, 1500, all_ghosts) armies = [] for i in range(20, 0, -1): army = Creature(army_shape, rand_point(500), uniform(-pi, pi)) army.dx = uniform(-0.4, +0.4) army.dy = uniform(-0.4, +0.4) armies.append(army) def update(dt): for army in armies: army.update(dt)
class Renderer(object): def __init__(self, client, map_size, minimap_size) -> None: self._client = client self._window = None self._map_size = map_size self._map_image = None self._minimap_size = minimap_size self._minimap_image = None self._mouse_x, self._mouse_y = None, None self._text_supply = None self._text_vespene = None self._text_minerals = None self._text_score = None self._text_time = None async def render(self, observation): render_data = observation.observation.render_data map_size = render_data.map.size map_data = render_data.map.data minimap_size = render_data.minimap.size minimap_data = render_data.minimap.data map_width, map_height = map_size.x, map_size.y map_pitch = -map_width * 3 minimap_width, minimap_height = minimap_size.x, minimap_size.y minimap_pitch = -minimap_width * 3 if not self._window: from pyglet.window import Window from pyglet.image import ImageData from pyglet.text import Label self._window = Window(width=map_width, height=map_height) self._window.on_mouse_press = self._on_mouse_press self._window.on_mouse_release = self._on_mouse_release self._window.on_mouse_drag = self._on_mouse_drag self._map_image = ImageData(map_width, map_height, 'RGB', map_data, map_pitch) self._minimap_image = ImageData(minimap_width, minimap_height, 'RGB', minimap_data, minimap_pitch) self._text_supply = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='top', x=self._map_size[0] - 10, y=self._map_size[1] - 10, color=(200, 200, 200, 255)) self._text_vespene = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='top', x=self._map_size[0] - 130, y=self._map_size[1] - 10, color=(28, 160, 16, 255)) self._text_minerals = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='top', x=self._map_size[0] - 200, y=self._map_size[1] - 10, color=(68, 140, 255, 255)) self._text_score = Label('', font_name='Arial', font_size=16, anchor_x='left', anchor_y='top', x=10, y=self._map_size[1] - 10, color=(219, 30, 30, 255)) self._text_time = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='bottom', x=self._minimap_size[0] - 10, y=self._minimap_size[1] + 10, color=(255, 255, 255, 255)) else: self._map_image.set_data('RGB', map_pitch, map_data) self._minimap_image.set_data('RGB', minimap_pitch, minimap_data) self._text_time.text = str( datetime.timedelta( seconds=(observation.observation.game_loop * 0.725) // 16)) if observation.observation.HasField('player_common'): self._text_supply.text = "{} / {}".format( observation.observation.player_common.food_used, observation.observation.player_common.food_cap) self._text_vespene.text = str( observation.observation.player_common.vespene) self._text_minerals.text = str( observation.observation.player_common.minerals) if observation.observation.HasField('score'): self._text_score.text = "{} score: {}".format( score_pb._SCORE_SCORETYPE.values_by_number[ observation.observation.score.score_type].name, observation.observation.score.score) await self._update_window() if self._client.in_game and (not observation.player_result ) and self._mouse_x and self._mouse_y: await self._client.move_camera_spatial( Point2((self._mouse_x, self._minimap_size[0] - self._mouse_y))) self._mouse_x, self._mouse_y = None, None async def _update_window(self): self._window.switch_to() self._window.dispatch_events() self._window.clear() self._map_image.blit(0, 0) self._minimap_image.blit(0, 0) self._text_time.draw() self._text_score.draw() self._text_minerals.draw() self._text_vespene.draw() self._text_supply.draw() self._window.flip() def _on_mouse_press(self, x, y, button, modifiers): if button != 1: # 1: mouse.LEFT return if x > self._minimap_size[0] or y > self._minimap_size[1]: return self._mouse_x, self._mouse_y = x, y def _on_mouse_release(self, x, y, button, modifiers): if button != 1: # 1: mouse.LEFT return if x > self._minimap_size[0] or y > self._minimap_size[1]: return self._mouse_x, self._mouse_y = x, y def _on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if not buttons & 1: # 1: mouse.LEFT return if x > self._minimap_size[0] or y > self._minimap_size[1]: return self._mouse_x, self._mouse_y = x, y
async def render(self, observation): render_data = observation.observation.render_data map_size = render_data.map.size map_data = render_data.map.data minimap_size = render_data.minimap.size minimap_data = render_data.minimap.data map_width, map_height = map_size.x, map_size.y map_pitch = -map_width * 3 minimap_width, minimap_height = minimap_size.x, minimap_size.y minimap_pitch = -minimap_width * 3 if not self._window: from pyglet.window import Window from pyglet.image import ImageData from pyglet.text import Label self._window = Window(width=map_width, height=map_height) self._window.on_mouse_press = self._on_mouse_press self._window.on_mouse_release = self._on_mouse_release self._window.on_mouse_drag = self._on_mouse_drag self._map_image = ImageData(map_width, map_height, 'RGB', map_data, map_pitch) self._minimap_image = ImageData(minimap_width, minimap_height, 'RGB', minimap_data, minimap_pitch) self._text_supply = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='top', x=self._map_size[0] - 10, y=self._map_size[1] - 10, color=(200, 200, 200, 255)) self._text_vespene = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='top', x=self._map_size[0] - 130, y=self._map_size[1] - 10, color=(28, 160, 16, 255)) self._text_minerals = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='top', x=self._map_size[0] - 200, y=self._map_size[1] - 10, color=(68, 140, 255, 255)) self._text_score = Label('', font_name='Arial', font_size=16, anchor_x='left', anchor_y='top', x=10, y=self._map_size[1] - 10, color=(219, 30, 30, 255)) self._text_time = Label('', font_name='Arial', font_size=16, anchor_x='right', anchor_y='bottom', x=self._minimap_size[0] - 10, y=self._minimap_size[1] + 10, color=(255, 255, 255, 255)) else: self._map_image.set_data('RGB', map_pitch, map_data) self._minimap_image.set_data('RGB', minimap_pitch, minimap_data) self._text_time.text = str( datetime.timedelta( seconds=(observation.observation.game_loop * 0.725) // 16)) if observation.observation.HasField('player_common'): self._text_supply.text = "{} / {}".format( observation.observation.player_common.food_used, observation.observation.player_common.food_cap) self._text_vespene.text = str( observation.observation.player_common.vespene) self._text_minerals.text = str( observation.observation.player_common.minerals) if observation.observation.HasField('score'): self._text_score.text = "{} score: {}".format( score_pb._SCORE_SCORETYPE.values_by_number[ observation.observation.score.score_type].name, observation.observation.score.score) await self._update_window() if self._client.in_game and (not observation.player_result ) and self._mouse_x and self._mouse_y: await self._client.move_camera_spatial( Point2((self._mouse_x, self._minimap_size[0] - self._mouse_y))) self._mouse_x, self._mouse_y = None, None
from pyglet.window import Window from pyglet_helper.objects import * from pyglet_helper.util.color import * window = Window() scene = View() _ball = Sphere(pos=(0, 0, 0), radius=0.5, color=red) _light = Light() _light.render(scene) _ball.render(scene) pyglet.app.run()
from pyglet.window import Window import pyglet from game import FBGame window = Window(600, 800, caption='Flappy Bird') game_dict = { 'bird_x': 80, 'bird_y': window.height/2, 'bird_radius': 30, 'pipe_x': 400, 'pipe_size': 80, 'window_width': window.width + 300, 'window_height': window.height } game = FBGame(**game_dict) @window.event def on_key_press(symbol, modifiers): if symbol is pyglet.window.key.W: game.jump_bird() if symbol is pyglet.window.key.R: game.reset(**game_dict) @window.event def on_draw(): window.clear() game.show() pyglet.clock.schedule(game.update) pyglet.app.run()
if prompt: self.write('... ') else: self.source = [] self.write('>>> ') sys.stdout = _stdout def backspace(self): self.buffer = self.buffer[:-1] # There is no easy way to change element text yet... self.element.text = self.element.text[:-1] self.element.document.element_modified(self.element) window = Window(visible=False, vsync=False) layout = Layout() layout.set_xhtml(data) window.push_handlers(layout) interp = DOMInterpreter(layout.document.get_element('interpreter')) def on_text(text): interp.input(text.replace('\r', '\n')) window.push_handlers(on_text)
def __init__(self, height, width): Window.__init__(self, height, width) self.clock_setted = False self.complete = 0 self.center = Point(height / 2, width / 2)
from pathlib import Path from pyglet import sprite from pyglet import app from pyglet import image from pyglet.window import Window from pyglet.window import mouse from pyglet.window import key from pyglet import graphics from pyglet import gl from pyglet import text import random #these values can be changed to modify the game window = Window(1100, 600) #transform player's options o_rock_pos = (950, 350) o_paper_pos = (950, 250) o_scissors_pos = (950, 150) #transform big choice players_choice_pos = (650, 200) comps_choice_pos = (150, 200) questionmark_pos = (50, 250) its_a_tie = 0 # if the game is evaluated as "its a tie", the value turns 1 #image properties play_image_size = (265, 215) choice_image_size = (94, 76) #players options options_all = graphics.Batch() image_dir = Path(__file__).parent / "images"
class Gameloop(object): def __init__(self, options): self.options = options self.window = None self.fpss = [] self.time = 0.0 self.level = None def prepare(self, options): self.window = Window( fullscreen=options.fullscreen, vsync=options.vsync, visible=False, resizable=True) self.window.on_draw = self.draw_window self.world = World() self.player = Player(self.world) self.camera = GameItem( position=origin, update=CameraMan(self.player, (3, 2, 0)), ) self.level_loader = Level(self) success = self.start_level(1) if not success: logging.error("ERROR, can't load level 1") sys.exit(1) self.update(1/60) self.window.push_handlers(KeyHandler(self.player)) self.render = Render(self.world, self.window, self.camera) self.render.init() self.music = Music() self.music.load() self.music.play() def run(self): pyglet.clock.schedule(self.update) self.window.set_visible() self.window.invalid = False pyglet.app.run() def update(self, dt): if self.options.print_fps: self.fpss.append(1/max(1e-6, dt)) dt = min(dt, 1 / 30) self.time += dt for item in self.world: if hasattr(item, 'update'): item.update(item, dt, self.time) if self.player_at_exit(): self.world.remove(self.player) pyglet.clock.schedule_once( lambda *_: self.start_level(self.level + 1), 1.0 ) self.window.invalid = True def start_level(self, n): success = self.level_loader.load(self.world, n) if not success: logging.info('No level %d' % (n,)) self.stop() return False self.level = n pyglet.clock.schedule_once( lambda *_: self.world.add(self.player), 2.0, ) return True def player_at_exit(self): items = self.world.collision.get_items(self.player.position) if any(hasattr(item, 'exit') for item in items): dist2_to_exit = dist2_from_int_ords(self.player.position) if dist2_to_exit < EPSILON2: return True return False def draw_window(self): self.window.clear() self.render.draw_world() if self.options.display_fps: self.render.draw_hud() self.window.invalid = False return EVENT_HANDLED def stop(self): if self.window: self.window.close() if self.options.print_fps: print ' '.join("%6.1f" % (dt, ) for dt in self.fpss)
from pyglet.media import Player as MediaPlayer from pyglet.clock import ClockDisplay from pyglet.clock import set_fps_limit from pyglet.clock import schedule_interval from pyglet.window import Window from client.gui import Background from client.gui import Button from client.gui import QuitButton from client.gui import TextWidget from client.gui import UILabel from client.gui import MyRectangle from client.manager import GameManager from client.view_objects import Player from game.resources import Resources game_window = Window(Resources.window_width, Resources.window_height) game_window.set_caption("Push") game_window.set_location(Resources.center_x,Resources.center_y) fps = ClockDisplay() manager = GameManager() manager.set_window(game_window) # Object Batches per state # title_batch = Resources.batches['title'] setup_batch = Resources.batches['setup'] host_batch = Resources.batches['host'] join_batch = Resources.batches['join'] game_batch = Resources.batches['game'] end_batch = Resources.batches['end'] # End of Batches
from pyglet import * from pyglet import app from pyglet import resource from pyglet import sprite from pyglet import clock from pyglet.window import key from pyglet.window import Window window = Window(1000, 1000) @window.event def on_draw(): window.clear() player_sprite.draw() def update(dt): player_sprite.x += plyr_dx * dt player_sprite.y += plyr_dy * dt @window.event def on_key_press(symbol, modifiers): global plyr_dx, plyr_dy if symbol == key.LEFT: plyr_dx = -plyr_speed plyr_dy = 0 elif symbol == key.RIGHT: plyr_dx = +plyr_speed
from pyglet.window import key, mouse, Window from pyglet.gl import * from include.rect import Rectangle as Rect from include.line import Line from include.generic_classes.position import Position from node import Node from network import Network import pyglet window = Window(1000, 800) keys = key.KeyStateHandler() window.push_handlers(keys) nodes = [Node(window, address=i) for i in range(1, 11)] def main(): window.clear() def update(dt): window.clear() for node in nodes: node.get_neighbor_lens() node.draw() # print(node.neighbors) @window.event
#!/usr/bin/env python '''Early demonstration of XML/XHTML/CSS layout and rendering. Use the scroll-wheel to move up and down the document and resize the window to reflow the layout. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from pyglet.gl import * from pyglet.window import Window from pyglet import clock from layout import * window = Window(visible=False, vsync=False, resizable=True) data = '''<?xml version="1.0"?> <html> <head> <style> h1 {border-bottom: 1px solid; background-image: url(examples/stripe.png)} body {background-image: url(examples/paper.jpg); background-repeat: repeat;} p {padding: 2px} p:hover {color:red; padding: 0px; border: 2px dashed blue;} </style> </head> <body> <h1>The Frog King</h1>