class Egg(object): 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) @property def window(self): return self.__window @property def background_color(self): return self.__background_color @background_color.setter def background_color(self, value): self.__background_color = value def register_scene(self, scene): self.__scene = scene self.__camera = Camera("main_camera", (0, 0), self.__window.height / 2.) self.__scene.root.add_child(self.__camera) self.__camera.target.x = self.__window.width / 2. self.__camera.target.y = self.__window.height / 2. self.__window.event(self.__scene.on_mouse_press) self.__window.event(self.__scene.on_mouse_release) self.__window.event(self.__scene.on_mouse_drag) self.__window.event(self.__scene.on_mouse_motion) def on_draw(self): self.__window.clear() glClearColor(*self.__background_color) if self.__scene is not None: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) # draw batches self.__camera.focus(self.__window.width, self.__window.height) self.__scene.draw() # draw specific batches for the hud self.__camera.hud_mode(self.__window.width, self.__window.height) self.__scene.draw_head_display() def update(self, dt): if self.__scene is not None: self.__scene.update(dt) self.__scene.process_keyboard(self.__key_state_handler, dt) self.__camera.update(dt)
def test_motion(self): w = Window(200, 200) try: w.push_handlers(self) while not w.has_exit: w.dispatch_events() finally: w.close() self.user_verify('Pass test?', take_screenshot=False)
def test_resize(self): w = Window(200, 200, resizable=True) 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)
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
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 test_set_visible(self): w = Window(200, 200) try: w.push_handlers(WindowEventLogger()) w.dispatch_events() self.user_verify('Is the window visible?', take_screenshot=False) w.set_visible(False) w.dispatch_events() self.user_verify('Is the window no longer visible?', take_screenshot=False) w.set_visible(True) w.dispatch_events() self.user_verify('Is the window visible again?', take_screenshot=False) finally: w.close()
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
class Game(): def __init__(self): self.batch = Batch() self.background = Rectangle(0, 0, 0, 0) self.window = Window() self.window.push_handlers(self) self.on_resize(self.window.width, self.window.height) clock.schedule_interval(self.update, 1 / 60) clock.schedule_interval(self.log, 1) self.sounds = { 'fail': media.load('resources/failure.mp3', streaming=False), 'jump': media.load('resources/jump.wav', streaming=False), 'score': media.load('resources/score.wav', streaming=False), } self.reset() def log(self, delta): logging.info('Current speed: {}'.format(self.speed)) logging.info('Current score: {}'.format(self.points)) def reset(self): self.pipes = [] self.points = 0 self.speed = 2 self.player = Player(batch=self.batch) self.create_pipe() self.create_pipe(x=(Grid.columns / 2) + (Pipe.WIDTH / 2)) def fail(self): self.sounds['fail'].play() self.reset() def create_pipe(self, *args, **kwargs): kwargs['batch'] = kwargs.get('batch', self.batch) self.pipes.append(Pipe(*args, **kwargs)) def update(self, delta): self.player.update(delta) self.speed += delta * 0.1 delta_x = delta * Grid.x() * self.speed if self.player.is_offscreen(): self.fail() return for pipe in self.pipes: pipe.scroll(delta_x) if pipe.is_offscreen(): self.pipes.remove(pipe) self.create_pipe() if pipe.collides(self.player.center): self.fail() if self.player.cleared(pipe): self.score() def score(self): self.sounds['score'].play() self.points += 1 def jump(self): logging.info('jumping') self.sounds['jump'].play() self.player.jump() def on_key_press(self, symbol, modifiers): self.jump() def on_mouse_press(self, x, y, button, modifiers): self.jump() def on_draw(self): self.window.clear() self.background.draw() self.batch.draw() def on_resize(self, width, height): Grid.update_factor(width, height) self.background.width, self.background.height = width, height if getattr(self, 'player', None): self.player.resize()
class Gameloop(object): instance = None def __init__(self): Gameloop.instance = self self.window = None self.camera = None self.world = None self.renderer = None self.paused = False self.fps_display = None Keyboard.handlers.update({ key.PAGEUP: lambda: self.camera.zoom(2.0), key.PAGEDOWN: lambda: self.camera.zoom(0.5), key.ESCAPE: self.quit_game, key.PAUSE: self.toggle_pause, key.F12: lambda: save_screenshot(self.window), }) def init(self, name, version): clock.set_fps_limit(FPS_LIMIT) self.fps_display = clock.ClockDisplay() self.camera = Camera((0, 0), 800) self.renderer = Renderer(self.camera) caption = '%s v%s' % (name, version) self.window = Window( caption=caption, fullscreen=True, visible=False) self.window.on_key_press = on_key_press self.window.push_handlers(Keyboard.keystate) graphics = load_graphics() self.world = World() builder = LevelBuilder() seed(1) builder.build(self.world, 75, graphics) self.world.player = Player() self.world.player.add_to_space(self.world.space, (0, 200), 0) self.world.chunks.update(self.world.player.chunks) def dispose(self): if self.window: self.window.close() def run(self): try: self.window.set_visible() while not self.window.has_exit: self.window.dispatch_events() clock.tick() if self.world and not self.paused: self.world.tick(1/FPS_LIMIT) if self.world and hasattr(self.world, 'player'): player_position = self.world.player.chunks[0].body.position self.camera.x, self.camera.y = player_position self.camera.angle = atan2( player_position.x, player_position.y) self.camera.update() if self.renderer: aspect = ( self.window.width / self.window.height) self.renderer.draw(self.world, aspect) self.camera.hud_projection( (self.window.width, self.window.height)) self.fps_display.draw() self.window.flip() finally: self.dispose() def toggle_pause(self): self.paused = not self.paused def quit_game(self): self.window.has_exit = True
class Client( object ): def __init__(self, app): self.app = app self.window = Window( width=self.app.size[0], height=self.app.size[1], style='dialog', resizable=False ) self.window.set_caption("ASTAR MAZE") self.window.on_close = sys.exit self.ctrl = InputHandler(self) self.window.push_handlers(self.ctrl) self.clock = Clock() self.clock.set_fps_limit(30) self.window.push_handlers(self.clock) self.grid = ClientGrid( self.app.grid ) # S q u a r e s self.entities = {} self.setup() def setup(self): glClearColor( .113, .121, .1289, 1 ) glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) glDisable( GL_LIGHTING ) glCullFace( GL_BACK ) glDisable( GL_DEPTH_TEST ) self.runner = None self.goal = None self.isSearching = False self.found = False self.solution = [] self.prev = None self.entitiesBatch = pyglet.graphics.Batch() group = ClientGroup() for k,v in self.app.squares.iteritems(): verts = self.entitiesBatch.add( 4, GL_QUADS, group, 'v2i/static', 'c4B/dynamic' ) verts.vertices = v.vertices['positions'] verts.colors = v.vertices['colors'] self.entities[k] = ClientSquare( v, verts ) def draw(self): self.grid.draw() self.entitiesBatch.draw() if self.found: curr = None if self.prev: self.setVisited( self.entities[self.prev] ) if len(self.solution): curr = self.solution.pop() self.entities[curr].update( SquareType.RUNNER ) self.prev = curr def update(self): self.clock.tick() self.window.dispatch_events() self.window.clear() self.draw() self.window.flip() def reset(self): self.app.setup() self.setup() def astar(self): startState = ASState( self.runner.pos, self.goal.pos, self ) nodesGenerated = 1 frontier = Heap() expanded = set() frontier.push( 0, ASNode( startState ) ) while len(frontier): n = frontier.pop() if n.state.isGoal(): self.solution = n.execute() print "%d node(s) generated.\n" % nodesGenerated return True successors = n.state.expand() for succ in successors: if succ['successor'] not in expanded: nodesGenerated = nodesGenerated + 1 nprime = ASNode( succ['successor'], succ['action'], n ) frontier.push( nprime.hCost, nprime ) expanded.add( succ['successor'] ) return False def search(self): if not self.runner or not self.goal: print "You must select a start and end position on the grid" print "Press 1 and then click a square for start position (in purple)." print "Press 2 and then click a square for end position (in red)." else: self.isSearching = True print "\nRUNNING A*\n" print "Goal position: \t", self.goal.pos print "Start position: \t", self.runner.pos print "Using heuristic: \t%s\n" % SETTINGS['HEURISTIC'] if self.astar(): self.found = True else: print "Failed to solve maze." self.isSearching = False def pressSquare( self, sqr ): sqr.update( SquareType.BLOCKED ) def resetSquare( self, sqr ): sqr.update( SquareType.EMPTY ) def setStart( self, sqr ): if not self.runner: sqr.update( SquareType.START ) self.runner = sqr def setEnd( self, sqr ): if not self.goal: sqr.update( SquareType.GOAL ) self.goal = sqr def setVisited( self, sqr ): sqr.update( SquareType.TRAIL )
def register_entity(window: Window, ent: entity.Entity): window.push_handlers(on_draw=ent.draw, on_resize=Resize(ent.resize)) ent.resize(entity.Plane(window.width, window.height))
class EventLoopFixture(InteractiveFixture): question = '\n\n(P)ass/(F)ail/(S)kip/(Q)uit?' key_pass = key.P key_fail = key.F key_skip = key.S key_quit = key.Q clear_color = 1, 1, 1, 1 base_options = { 'width': 300, 'height': 300, } def __init__(self, request): super().__init__(request) self._request = request self.window = None self.text_batch = None self.text_document = None self.answer = None request.addfinalizer(self.tear_down) def tear_down(self): if self.window: self.window.close() self.window = None def create_window(self, **kwargs): combined_kwargs = {} combined_kwargs.update(self.base_options) combined_kwargs.update(kwargs) self.window = Window(**combined_kwargs) self.window.push_handlers(self) return self.window def get_document(self): if self.text_document is None: self._create_text() return self.text_document def _create_text(self): assert self.window is not None self.text_batch = Batch() self.text_document = FormattedDocument() layout = TextLayout(self.text_document, self.window.width, self.window.height, multiline=True, wrap_lines=True, batch=self.text_batch) layout.content_valign = 'bottom' def add_text(self, text): self.get_document() self.text_document.insert_text(len(self.text_document.text), text) def ask_question(self, description=None, screenshot=True): """Ask a question inside the test window. By default takes a screenshot and validates that too.""" if self.window is None: self.create_window() self.add_text('\n\n') if description: self.add_text(description) self.add_text(self.question) self.answer = None caught_exception = None try: if self.interactive: self.run_event_loop() self.handle_answer() else: self.run_event_loop(0.1) except Exception as ex: import traceback traceback.print_exc() caught_exception = ex finally: if screenshot: try: screenshot_name = self._take_screenshot(self.window) if caught_exception is None and not self.interactive: self._check_screenshot(screenshot_name) except: if not caught_exception: raise if caught_exception: raise caught_exception def handle_answer(self): if self.answer is None: raise Exception('Did not receive valid input in question window') elif self.answer == self.key_fail: # TODO: Ask input pytest.fail('Tester marked test failed') elif self.answer == self.key_skip: pytest.skip('Tester marked test skipped') elif self.answer == self.key_quit: pytest.exit('Tester requested to quit') def ask_question_no_window(self, description=None): """Ask a question to verify the current test result. Uses the console or an external gui as no window is available.""" super().ask_question(description) def run_event_loop(self, duration=None): if duration: clock.schedule_once(self.interrupt_event_loop, duration) pyglet.app.run() def interrupt_event_loop(self, *args, **kwargs): pyglet.app.exit() @staticmethod def schedule_once(callback, dt=.1): clock.schedule_once(callback, dt) def on_draw(self): self.clear() self.draw_text() def clear(self): gl.glClearColor(*self.clear_color) self.window.clear() def draw_text(self): if self.text_batch is not None: self.text_batch.draw() def on_key_press(self, symbol, modifiers): if symbol in (self.key_pass, self.key_fail, self.key_skip, self.key_quit): self.answer = symbol self.interrupt_event_loop() # Prevent handling of Escape to close the window return True
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 on_key_press(symbol, modifiers): if symbol == key.BACKSPACE: interp.backspace() else:
del e.style['display'] else: e.style['display'] = 'none' layout.push_handlers(on_mouse_press) @select('#para2') def on_mouse_press(element, x, y, button, modifiers): element.add_text('One fish two fish red fish blue fish.') layout.push_handlers(on_mouse_press) window.push_handlers(layout) def print_style(style, indent=''): import textwrap print '\n'.join( textwrap.wrap(repr(style), initial_indent=indent, subsequent_indent=indent)) if style.parent: print_style(style.parent, ' ' + indent) def print_element(element, indent=''): import textwrap print '\n'.join(
# print "after",list[:10] # print len(clist) vertexlist.vertices = clist vertexlist.draw(pyglet.gl.GL_LINE_STRIP) def plot_field(): granularity = 10 width = window.width / granularity height = window.height / granularity print EfieldC((1.0, 1.0)) data = bytearray(EfieldC) fieldtexture = pyglet.image.ImageData(width, height, "RGB", data) buttonevents = ButtonEventHandler() window.push_handlers(buttonevents) window.push_handlers(buttonevents.keys) pyglet.clock.schedule_interval(buttonevents.compute, 1.0 / 20.0) held_objects = set() selected_objects = set() hovered = None Buttons = [Button(mouseX, mouseY, 20, charge=10), Button(mouseX, mouseY + 100, 20, charge=10)] Links = set() # set([Link(Buttons[0] , Buttons[1], 10.0, 100.0)]) # window.push_handlers(pyglet.window.event.WindowEventLogger()) pyglet.app.run()
@window.event def on_text(text): sprite.text += text.replace('\r', '\n') @window.event def on_key_press(symbol, modifiers): if symbol == key.BACKSPACE: sprite.text = sprite.text[:-1] sprite = TextSprite(arial, text, color=(0, 0, 0, 1)) fps = clock.ClockDisplay() window.push_handlers(fps) glClearColor(1, 1, 1, 1) window.set_visible() while not window.has_exit: window.dispatch_events() clock.tick() glClear(GL_COLOR_BUFFER_BIT) sprite.y = sprite.height # TODO align on bottom sprite.draw() fps.draw() window.flip()
class Game(object): INITIAL_UPDATE_INTERVAL = UPDATE_INTERVAL def __init__(self): impl.funcs.load_resources() self.gameInfo = GameInfo() self.win = Window(FIELD_WIDTH, FIELD_HEIGHT) self.win.set_caption("snake") impl.funcs.setup_background_color() impl.funcs.setup_opengl_blend_func() self.gameField = GameField(self.gameInfo, self.win) self.menu = Menu(FIELD_WIDTH//2, FIELD_HEIGHT//2, self.game_start_callback, self.game_exit_callback, self.win) self._overlay = None self._update_interval = Game.INITIAL_UPDATE_INTERVAL @self.gameField.event def on_restart_snake(): unschedule(func=self.update) self._setup_overlay("restart") schedule_once(func=self.run_snake, delay=DELAY_FOR_NEW_RUN) @self.gameField.event def on_rerun_menu(): unschedule(func=self.update) #reset current handler self.win.pop_handlers() #and setup update handler self.win.push_handlers(self.menu) self.menu.start_bgrn_animation() @self.gameField.event def on_game_over(): unschedule(func=self.update) self._setup_overlay('game over...') schedule_once(func=self.game_exit_callback, delay=DELAY_FOR_EXIT) @self.gameField.event def on_score_up(): if self._update_interval > MAX_UPDATE_SPEED_INTERVAL: self._update_interval -= UPDATE_INTERVAL_SPEED_DX unschedule(func=self.update) schedule_interval(func=self.update,interval=self._update_interval) def _setup_overlay(self, text): self._overlay = BouncingLabel(FIELD_WIDTH//2,FIELD_HEIGHT//2,text,DEFAULT_OVERLAY_COLOR) self.win.pop_handlers() def on_draw(): self.win.clear() self._overlay.draw() self.win.push_handlers(on_draw) schedule_interval(func=self._overlay.update, interval=OVERLAY_UPDATE_INTERVAL) def game_start_callback(self): self._setup_overlay("start") schedule_once(func=self.run_snake, delay=DELAY_FOR_NEW_RUN) def game_exit_callback(self, *args): if self._overlay: unschedule(self._overlay.update) self._overlay = None self.win.pop_handlers() self.win.close() def start(self): self.win.push_handlers(self.menu) pyglet.app.run() def update(self, dt): if not self.gameInfo.pause: self.gameField.update(dt) def run_snake(self, *args): if self._overlay: unschedule(self._overlay.update) self._overlay = None #reset current handlers self.win.pop_handlers() self.gameInfo.pause = False self.gameField.reset() #setup new handlers self.win.push_handlers(self.gameField) #and setup update handler self._update_interval = Game.INITIAL_UPDATE_INTERVAL schedule_interval(func=self.update,interval=self._update_interval)
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 on_key_press(symbol, modifiers): if symbol == key.BACKSPACE: interp.backspace() else: return True window.push_handlers(on_key_press) def blink_cursor(dt):
class World(object): 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 def addPlayer(self, player, main=False): """ add a player to the player list """ if main: self.p1 = player self.p1.keys = key.KeyStateHandler() self.window.push_handlers(self.p1.keys) player.world = self self.players[player.name] = player self.mini_objects.append(player.mini) player.send(0, 'new') def addPlayerFromMini(self, mini): """ what the title says """ p = Player(mini.name, 'tanktop', 'tankbot') self.addPlayer(p) def gameUpdate(self, dt): """ To be called every Tick """ self.recvServer() rabbyt.add_time(dt) default_system.update(dt) for name, po in self.players.items(): delete_keys=[] for k, k_pressed in po.keys.iteritems(): if k_pressed and k in po.input: action = po.input[k][0] arg = po.input[k][1] po.action(action, arg, dt) def displayScore(self): """ Render the score for the players """ x_start = 1200 y_start = 750 labels = [] for p in self.mini_objects: y_start -= 25 score = '%s : %s' % (p.name, p.score) label = text.Label(score, font_name='Times New Roman', font_size=12, x=x_start, y=y_start, ) labels.append(label) for l in labels: l.draw() def selectLevel(self, name): """ Maybe add more levels? """ self.bgimage = resource.image('images/'+name+'.jpg') map = self.buildMap(name) for building in map: b = rabbyt.Sprite(None, building[0]) b.xy = building[1] self.map_objects.append(b) def buildMap(self, name): """ Need to DOC this """ city1 = [ ((-75, 24, 75, -24),(490, 373)), ((-24, 24, 24, -24),(590, 373)), ((-24, 24, 24, -24),(590, 325)), ((-24, 24, 24, -24),(838, 373)), ((-24, 24, 24, -24),(738, 275)), ((-24, 24, 24, -24),(488, 525)), ((-24, 24, 24, -24),(938, 525)), ((-24, 24, 24, -24),(988, 525)), ((-49, 49, 49, -49),(563, 549)), ((-49, 49, 49, -49),(763, 549)), ((-49, 49, 49, -49),(863, 549)), ((-49, 49, 49, -49),(763, 349)) ] levels = {'city1':city1} return levels[name] def connectServer(self): context = zmq.Context() # Socket to receive broadcasts from server self.sub_socket = context.socket(zmq.SUB) self.sub_socket.connect("tcp://localhost:5556") self.sub_socket.setsockopt(zmq.SUBSCRIBE, "all") print "Connecting to server ...", sys.stdout.flush() self.sub_socket.recv() # Will hang forever if no server. print "Connected" self.push_socket = context.socket(zmq.PUSH) self.push_socket.connect("tcp://localhost:5555") def recvServer(self): try: msg = self.sub_socket.recv(flags=zmq.core.NOBLOCK) except zmq.core.error.ZMQError: pass else: sep = msg.find(':') to = msg[0:sep] foreign = util.unpickle(msg[sep+1:]) for n, obj in foreign.items(): if n == self.p1.mini.name: del foreign[n] self.updatePlayers(foreign) def updatePlayers(self, foreign): for name, mini in foreign.items(): p = self.getPlayer(mini) p.updateFromMini(mini) def getPlayer(self, mini): try: return self.players[mini.name] except: self.addPlayerFromMini(mini) return self.players[mini.name]
import pyglet import serial import struct from jaraco.input import Joystick from pyglet.window import key, Window arial = pyglet.font.load('Arial', 14, bold=True, italic=False) window = Window() keyboard = key.KeyStateHandler() window.push_handlers(keyboard) fps_display = pyglet.clock.ClockDisplay() string_display = pyglet.text.Label('NULL', y=128) joysticks = Joystick.enumerate_devices() xbox = joysticks[0] print xbox xbox_axes = {} @xbox.event def on_axis(axis, value): xbox_axes[axis] = value print(axis, value) xbee = serial.Serial('COM6', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)
window.clear() with nested(Projection(0, 0, window.width, window.height, far=1000.0), Matrix, Lighting): glTranslatef(0, 0, -500) glRotatef(tilt*0.3, 1.0, 0, 0) glRotatef(rotate*0.3, 0.0, 1.0, 0) for body in bodies: with Matrix: glMultMatrixf(body.matrix) cube(size=body.size, color=(0.5, 0.5, 0.5, 1.0)) fps.draw() description.draw() keys = pyglet.window.key.KeyStateHandler() window.push_handlers(keys) constant = 300.0 def simulate(delta): for i, body1 in enumerate(bodies): for body2 in bodies[i+1:]: vec = body1.position - body2.position gravity = (body1.mass*body2.mass/vec.magnitude) * constant * delta normal = vec.normalized body1.add_force(linear=normal.inversed*gravity, relative=False) body2.add_force(linear=normal*gravity, relative=False) world.step(delta, iterations=10) schedule_interval(simulate, 0.005) run()
import pyglet from pyglet.window import Window from pyglet.window import key from pyglet.window.key import KeyStateHandler from pyglet.text import Label from pyglet import image win = Window() keyboard = KeyStateHandler() win.push_handlers(keyboard) winWidth, winHeight = win.get_size() mouseX = 0 mouseY = 0 label = Label('Hello') cnvs = win.canvas print(dir(cnvs)) print(cnvs.__class__) disp = win.canvas.display print(dir(disp)) print(disp.__class__) # screens = display.get_screens() # print(win.context) # print("screen count {}".format(len(screens))) # print(screens[0]) # print(display)
class Client: """ While we aren't networking this game it's better to learn this structure now rather than later. Even if you never plan on learning how to network your games this is still a very good architecture to use. This Client class should be considered completely separate from the Game. It is just a way of interacting with the game. The game should not depend on anything in this class. Working like this will help you keep your code much cleaner and, as stated before, networkable. You could also make multiple clients using different technologies. In our case we are using pyglet and rabbyt libraries, but it wouldn't be difficult to make a client using pygame or even just the consol (for a text mode). """ 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 setup(self): """ Just like the setup in the Game class this one fills out the block data. But wait, why do we have to do this again? Remeber how in the GameBlock we only had stuff related to the game engine; no display stuff? Well, we need display stuff for the client - that's why we have ClientBlock! As you'll see soon the ClientBlock sorta wraps the GameBlock to provide the graphical stuff we need. """ self.blocks = {} for key,b in self.game.blocks.items(): self.blocks[key] = ClientBlock(self, b) def _add_time(self, dt): """ This is kept track of so we can pass it onto rabbyt (so animation works) """ self.time += dt def loop(self): """ And here is our main game loop! In case you are new to game programming this is what is called every frame. This is where we will handle the display and stuff. """ # clock.tick is used for keeping track of time and limiting the frame # rate. self.clock.tick() self.window.dispatch_events() # And this is where that mysterious "time" comes in. This way rabbyt # knows how much time has passed and can do the awesome animations. rabbyt.set_time(self.time) # If you are new to this sort of thing rabbyt.clear clears the screen # (erases what was drawn last loop). We pass white as the color that we # want to clear it with. rabbyt.clear((1,1,1,1)) # And now we draw our blocks and smile face. for b in self.blocks.values(): b.draw() if self.game.gameover == True: if self.game.won == False: self.dead_face.render() else: self.won_face.render() else: self.smile_face.render() # This draws the buffer onto the screen. Without this we would be # staring at a blank screen. self.window.flip() def press_block(self, block): """ This is called by the Control as we will see later. Pretty simple and even unneeded. But this is where you could add cool effects for when you click on a block if you wannted to. (That's the reasion I have it) """ self.game.press_block(block.gameblock) def retry(self): """ Re-sets up the game. """ self.game.setup() self.setup()
from pyglet.window import key from pyglet import shapes import math from Generation import Generation from track import tracklines window = Window(960, 700) pyglet.gl.glClearColor(1, 1, 1, 1) gen = Generation() for car in gen.players: window.push_handlers(car.key_handler) @window.event def on_draw(): window.clear() gen.draw() for line in tracklines: line.draw() # for car in gen.players: # car.draw() # for car in gen.players: # for line in car.rays: # line.draw()
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.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
@select('#shone') def on_mouse_press(element, x, y, button, modifiers): e = layout.document.get_element('wishing') if e.style['display'] == 'none': del e.style['display'] else: e.style['display'] = 'none' layout.push_handlers(on_mouse_press) @select('#para2') def on_mouse_press(element, x, y, button, modifiers): element.add_text('One fish two fish red fish blue fish.') layout.push_handlers(on_mouse_press) window.push_handlers(layout) def print_style(style, indent=''): import textwrap print '\n'.join(textwrap.wrap(repr(style), initial_indent=indent, subsequent_indent=indent)) if style.parent: print_style(style.parent, ' ' + indent) def print_element(element, indent=''): import textwrap print '\n'.join(textwrap.wrap(repr(element), initial_indent=indent, subsequent_indent=indent)) if element.style_context: print_style(element.style_context, indent + ' ')