Exemplo n.º 1
0
 def __init__(self, *args, **kwargs):
   super(MainWindow, self).__init__(*args, **kwargs)
   self.keys = window.key.KeyStateHandler()
   self.push_handlers(self.keys)
   # self.set_exclusive_mouse()
   self.width, self.height, self.rat3d, self.ratex = 640, 480, 1.05, 0.5
   self.zoom, self.expand, self.mapping, self.blend = 0, 0, 0, 1
   self.fgc, self.bgc = (1.0, 1.0, 1.0, 0.9), (0.1, 0.1, 0.1, 0.1)
   self.loadfgc, self.loadbgc = (0.4, 0.2, 0.4, 0.3), (0.6, 0.3, 0.6, 0.9)
   self.instfgc, self.instbgc = (0.1, 0.1, 0.5, 0.9), (0.5, 0.9, 0.9, 0.8)
   self.instbkwidth, self.instbkheight = 480, 400
   bmplen = (self.instbkwidth / 8) * self.instbkheight
   self.instbkbmp = (ctypes.c_ubyte * bmplen)(*([255] * bmplen))
   self.ticktimer, self.tick, self.insttimer, self.inst = 0.5, 0.0, 30, 1
   self.printing, self.solver = 1, deque()
   self.stat = [None, 0, Queue.Queue(512)] # (key(1-9), direc), count, queue
   self.cmax, self.tanim = 18, [6, 3, 1, 3] # frames in rotate moving, speeds
   self.tcos, self.tsin = [1.0] * (self.cmax + 1), [0.0] * (self.cmax + 1)
   for i in xrange(1, self.cmax):
     t = i * math.pi / (2.0 * self.cmax) # 0 < t < pi/2
     self.tcos[i], self.tsin[i] = math.cos(t), math.sin(t)
   self.tcos[self.cmax], self.tsin[self.cmax] = 0.0, 1.0 # pi/2 regulation
   self.InitRot()
   self.InitAxis()
   self.InitGL(self.width, self.height)
   self.textures = [None] * (len(self.ary_norm) * 2 + 1 + len(TEXIMG_CHAR))
   self.loading, self.dat = 0, [('', 0, 0)] * len(self.textures)
   resource.add_font(FONT_FILE)
   self.font = font.load(FONT_FACE, 20)
   self.fontcolor = (0.5, 0.8, 0.5, 0.9)
   self.fps_display = clock.ClockDisplay(font=self.font, color=self.fontcolor)
   self.fps_pos = (-60.0, 30.0, -60.0)
   clock.set_fps_limit(60)
   clock.schedule_interval(self.update, 1.0 / 60.0)
Exemplo n.º 2
0
    def __init__(self):
        self.fps_display = clock.ClockDisplay()
        self.init_frame()
        self.frame = graphics.Batch()

        # -*- WARNING -*-
        # -*- Python magic -*-
        # Luckily this only has to be called once per renderer
        # and per program there is on average 1.0 renderer
        # (Actually it might be useful to have two of these...)
        # Finds all classes in Renderer that inherit Primitive
        # at some point, and for each, creates a copy for this
        # instance and sets the renderer attribute for each
        # to this instance.

        # This is just so we can do stuff like renderer.Rectangle()
        # without having to pass in the renderer because that doesn't
        # make any sense.
        # -*- Python magic -*-
        # -*- WARNING -*-

        for name in dir(self):
            cls = getattr(self, name)
            if hasattr(cls, '__mro__') and Primitive in cls.__mro__:
                setattr(self, name, type(name, (cls, ), dict(renderer=self)))
Exemplo n.º 3
0
    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 __init__(self, window, view):
     self.window = window
     self.view = view
     self.font = font.load('Helvetica', 10)
     self.fps = clock.ClockDisplay(font=self.font,
                                   interval=0.2,
                                   color=(0, 0, 0, 1))
Exemplo n.º 5
0
 def set_show_FPS(self, value):
     if value and self.fps_display is None:
         self.fps_display = clock.ClockDisplay()
     elif not value and self.fps_display is not None:
         self.fps_display.unschedule()
         self.fps_display.label.delete()
         self.fps_display = None
Exemplo n.º 6
0
 def __init__(self):
     super().__init__()
     self.set_size(WINDOW_SIZE['width'], WINDOW_SIZE['height'])
     clock.schedule_interval(self.update, 1 / 60)
     self.fps_display = clock.ClockDisplay()
     self.scene = SceneMainMenu(self)
     self.set_vsync(True)
Exemplo n.º 7
0
    def __init__(self):
        super(_GameClient, self).__init__(fullscreen=True)
        synthesize(self, 'gameFolder', None)
        synthesize(self, 'gameWorld', None)
        synthesize(self, 'showStats', False)
        synthesize(self, 'isAlive', True)

        synthesize(self, 'fps', clock.ClockDisplay(), True)
Exemplo n.º 8
0
    def init(self, *args, **kwargs):
        """Initializes the Director creating the main window.
        Keyword arguments are passed to pyglet.window.Window().

        All the valid arguments can be found here:

            - http://www.pyglet.org/doc/1.1/api/pyglet.window.Window-class.html
        
        :rtype: pyglet.window.Window                    
        :returns: The main window, an instance of pyglet.window.Window class.
        """

        # pop out the Cocos-specific flag
        do_not_scale_window = kwargs.pop('do_not_scale', False)

        #: pyglet's window object
        self.window = window.Window(*args, **kwargs)

        #: whether or not the FPS are displayed
        self.show_FPS = False

        #: stack of scenes
        self.scene_stack = []

        #: scene that is being run
        self.scene = None

        #: this is the next scene that will be shown
        self.next_scene = None

        # save resolution and aspect for resize / fullscreen
        if do_not_scale_window:
            self.window.push_handlers(on_resize=self.unscaled_resize_window)
        else:
            self.window.push_handlers(on_resize=self.scaled_resize_window)
        self.window.push_handlers(self.on_draw)
        self._window_original_width = self.window.width
        self._window_original_height = self.window.height
        self._window_aspect = self.window.width / float(self.window.height)
        self._offset_x = 0
        self._offset_y = 0

        # opengl settings
        self.set_alpha_blending()

        # init fps
        self.fps_display = clock.ClockDisplay()

        # python interpreter
        self.python_interpreter = None

        #: whether or not to show the python interpreter
        self.show_interpreter = False

        # default handler
        self.window.push_handlers(DefaultHandler())

        return self.window
Exemplo n.º 9
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # batch for efficient drawing
        self.batch = graphics.Batch()
        background = graphics.OrderedGroup(0)
        foreground = graphics.OrderedGroup(1)

        self.gamelayer = graphics.OrderedGroup(2)

        toplayer = graphics.OrderedGroup(3)

        # window size
        self.size = self.get_size()

        # start with empty asteroid set
        self.asteroids = set()

        # empty explosions set
        self.explosions = set()

        # background and moving foreground sprites
        self.background = physicalobject.ScaledMovingSprite(img=resources.background_image,
                screensize=self.size, batch=self.batch, group=background)
        self.debris = load.debris(screensize=self.size, batch=self.batch, group=foreground)
        self.splashscreen = load.ClickableSprite(hook_function=self.start,
                img=resources.splashscreen,
                x = self.size[0] / 2.0, y=self.size[1] / 2.0,
                batch=self.batch, group=toplayer)


        # player ship
        self.player = load.ship(screensize=self.size, batch=self.batch, group=self.gamelayer)

        self.score = 0
        self.lives = LIVES
        self.started = False

        self.fps_display = clock.ClockDisplay()

        # Lives and score labels
        self.lives_label = text.Label(font_size=20, text="Lives: %d" % self.lives, x=40, y=self.size[1]-40,
                    batch=self.batch, group=toplayer)
        self.score_label = text.Label(font_size=20, anchor_x='right', text="Score: %d" % self.score, x=self.size[0]-40,
                    y=self.size[1]-40, batch=self.batch, group=toplayer)

        # update frequency
        clock.schedule_interval(self.update, 1 / 120)

        # spawn a new asteroid each second
        clock.schedule_interval(self.spawn_asteroid, 1)

        # add event handlers to the ship and splashscreen
        self.push_handlers(self.player)
        self.push_handlers(self.splashscreen)
Exemplo n.º 10
0
 def __init__(self, win):
     helv = font.load('Helvetica', win.width / 15.0)
     #        self.text = font.Text(
     #            helv,
     #            'Hello, World!',
     #            x=win.width / 2,
     #            y=win.height / 2,
     #            halign=font.Text.CENTER,
     #            valign=font.Text.CENTER,
     #            color=(1, 1, 1, 0.5),
     #        )
     self.fps = clock.ClockDisplay()
Exemplo n.º 11
0
 def __init__(self, win):
     helv = font.load('Helvetica', win.width / 15.0)
     self.text = font.Text(
         helv,
         'Hello, World!',
         x=win.width / 2,
         y=win.height / 2,
         halign=font.Text.CENTER,
         valign=font.Text.CENTER,
         color=(1, 1, 1, 0.5),
     )
     self.fps = clock.ClockDisplay()
Exemplo n.º 12
0
    def __init__(self, model):
        self.model = model
        self.model.push_handlers(self)

        self.window = window.Window(512, 512)
        self.keys = key.KeyStateHandler()
        self.window.push_handlers(self.keys)

        self.fps = clock.ClockDisplay(color=(1, 0, 0, 1))
        self.font = font.load(None, 24, bold=True)
        self.bigfont = font.load(None, 48, bold=True)
        self.score_view = font.Text(self.font,
                                    "Score: 0",
                                    x=16,
                                    y=496,
                                    halign='left',
                                    valign='top',
                                    color=(1, 0, 0, .8))
        self.game_over = font.Text(self.bigfont,
                                   "GAME OVER",
                                   x=256,
                                   y=256,
                                   halign='center',
                                   valign='center',
                                   color=(1, 0, 0, .8))
        # View objects
        self.ship_view = ShipView(self.model.ship)
        self.bullet_views = gfx.ViewObjectBag(self.model.bullets, BulletView)
        self.asteroid_views = gfx.ViewObjectBag(self.model.asteroids,
                                                AsteroidView)
        self.dust = gfx.ParticleSystem(DustParticle)
        self.exhaust = gfx.ParticleSystem(ExhaustParticle)
        self.stars = gfx.SlowParticleSystem(Star)

        # Generate stars
        for i in range(20):
            dist = random.uniform(5, 20)
            x = random.uniform(0, 512)
            y = random.uniform(0, 512)
            angle = random.uniform(0, 72)
            self.stars.new_particle(x=x,
                                    y=y,
                                    vx=-dist * 0.05,
                                    vy=0,
                                    radius=dist,
                                    angle=angle)

        # Setup GL
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_POINT_SMOOTH)
        glClearColor(0, 0, 0, 0)
Exemplo n.º 13
0
 def __init__(self, win, world):
     helv = font.load('Helvetica', 30)
     message = '%d entities' % (world.numEnts)
     self.text = font.Text(
         helv,
         message,
         x=win.width,
         y=0,
         halign=font.Text.RIGHT,
         valign=font.Text.BOTTOM,
         color=(1, 1, 1, 0.5),
     )
     self.fps = clock.ClockDisplay(format="%(fps).1ffps", font=helv)
Exemplo n.º 14
0
    def __init__(self):
        clock.set_fps_limit(fps)
        self.fps_display = clock.ClockDisplay()

        config = pyglet.gl.Config(double_buffer=True)

        pyglet.window.Window.__init__(self, width=window_width, height=window_height, config=config)
        self.batch_draw = pyglet.graphics.Batch()
        x = image_spacing
        y = window_height - 5*(image_size+image_spacing)
        self.square = SquareImage(self.batch_draw, x, y, image_size)
        self.run = False
        self.schedule = pyglet.clock.schedule_interval(func=self.update, interval=1/float(fps*2))
Exemplo n.º 15
0
    def __init__(self, **kwargs):
        # rip out the game settings we want
        players = kwargs.pop('players')
        gamestate = kwargs.pop('gamestate')
        self.game = PlanetWars(gamestate)
        for p in players:
            self.game.add_player(p)
        self.max_tick = kwargs.pop('max_game_length')
        self.max_tick += self.max_tick / 2

        # set and use pyglet window settings
        kwargs.update({
            'width': 500,
            'height': 500,
            'vsync': True,
            'resizable': False,
        })
        super(PlanetWarsWindow, self).__init__(**kwargs)
        # create a pyglet window and set glOptions
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glClearColor(0., 0., 0., 1.0)  # Grey

        # current "pen" colour of lines
        self.pen_color = (1, 0, 0, 1.)
        self.stroke = 1.0  # - thickness default
        self.qobj = gluNewQuadric()
        # gluQuadricDrawStyle(self.qobj, GLU_FILL) #GLU_SILHOUETTE)

        # prep the fps display and some labels
        self.fps_display = clock.ClockDisplay()
        clWhite = (255, 255, 255, 255)
        self.step_label = Label('STEP', x=5, y=self.height - 20, color=clWhite)
        self.fps = 0
        self.set_fps(20)
        self.paused = True
        self.view_id = 0
        self.label_type = 'num_ships'

        # create adaptor to help with drawing
        self.adaptor = PlanetWarsScreenAdapter(self.game, self.circle)

        # prep the game (space!)
        self.reset_space()
        # add extra event handlers we need
        self.add_handlers()
Exemplo n.º 16
0
 def __init__(self):
     pyglet.window.Window.__init__(self, resources.window_dimensions[0],
                                   resources.window_dimensions[1])
     self.to_delete = []
     self.scoring = 0
     self.attack_label = False
     self.fps_display = clock.ClockDisplay()
     self.level = Levels.Level_Handler(group=background_level)
     self.player = Player.Player(batch=entry, group=player_level)
     self.game_objects = []
     self.game_objects.append(self.player)
     #self.camera = Camera(complex_camera, total_level_width, total_level_height)
     self.level.level_keeper()
     self.schedule = pyglet.clock.schedule_interval(func=self.update,
                                                    interval=1 / 60.)
     self.push_handlers(self.player.keyboard)
     self.reappender()
Exemplo n.º 17
0
def draw_sprites(domain, texture):
    glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT)

    glEnable(GL_BLEND)
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
    glColor4f(.2, .2, .2, .2)
    glEnable(GL_TEXTURE_2D)
    glBindTexture(GL_TEXTURE_2D, texture.id)
    domain.draw(GL_QUADS)

    glPopAttrib()

    domain = vertexdomain.create_domain('v2f/static', 't2f/static')

    sprites = [Sprite(domain) for i in range(SPRITES)]
    fps = clock.ClockDisplay(color=(1, 1, 1, 1))

    texture = image.load(SPRITE_IMAGE).texture

    if SPRITE_UPDATE_N:
        update_n = 0

    while not win.has_exit:
        dt = clock.tick()
        if dt == 0:
            dt = 0.01

        win.dispatch_events()

        if SPRITE_UPDATE_N > 1:
            # Update small number of sprites
            for sprite in sprites[update_n:update_n + SPRITE_UPDATE_N]:
                sprite.update(dt)
            update_n = (update_n + SPRITE_UPDATE_N) % len(sprites)
        elif SPRITE_UPDATE_N:
            # Update all sprites
            for sprite in sprites:
                sprite.update(dt)
        # Otherwise, update no sprites (static)

        win.clear()
        draw_sprites(domain, texture)
        fps.draw()
        win.flip()
Exemplo n.º 18
0
    def on_select(self, label):
        if label.text == 'Resume Game':
            pass
        elif label.text == 'Advance Stage':
            self.fps.level.advance_stage()
        elif label.text == 'Unlimited Weapon Charge':
            self.fps.level.weapon_charge = 10000000.
            self.fps.level.update_weapon_materials()
        elif label.text == 'Unlimited Health':
            self.fps.level.set_health(1000000.)
        elif label.text == 'FPS Counter':
            self.fps.clock_display = clock.ClockDisplay()
        elif label.text == 'Print XL Objects':
            utl.log.clear_stdout()
            xl.Object.print_all()
        elif label.text == 'Print GL Objects':
            utl.log.clear_stdout()
            gl.Object.print_all()

        self.has_exit = True
Exemplo n.º 19
0
    def __init__(self, filename, **kwargs):
        kwargs.update({
            'width': 500,
            'height': 500,
            'vsync': True,
            'resizable': True,
        })
        super(BoxWorldWindow, self).__init__(**kwargs)

        self.searching = False

        # create a pyglet window and set glOptions
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        # needed so that graphs.egi knows where to draw
        egi.InitWithPyglet(self)
        egi.text_color(name='BLACK')

        glClearColor(0.9, 0.9, 0.9, 1.0)  # Grey

        #create a world for graph searching
        #filename = kwargs['filename'] #"boxworld2.txt"
        #filename = 'map2.txt'
        self.world = BoxWorld.FromFile(filename, self.get_size())
        self.world.reset_navgraph()

        # prep the fps display and some labels
        self.fps_display = clock.ClockDisplay()
        clBlack = (0, 0, 0, 255)
        self.labels = {
            'mouse': Label('', x=5, y=self.height - 20, color=clBlack),
            'search': Label('', x=120, y=self.height - 20, color=clBlack),
            'status': Label('', x=300, y=self.height - 20, color=clBlack),
        }
        self._update_label()

        # add the extra event handlers we need
        self.add_handers()

        # search limit
        self.limit = 0  # unlimited.
Exemplo n.º 20
0
Arquivo: gui.py Projeto: msarch/py
    def __init__(self):
        pyglet.window.Window.__init__(self, vsync=True)
        self.background_color = (0.95, 0.95, 0.95, 0)  # background
        self.chrono = 0.0  # keeps track of total time elapsed
        self.frame_number = 0  # frame counter
        self.paused = False
        self.set_mouse_visible(False)
        self.show_fps = True
        self.pcd = clock.ClockDisplay()
        self.key_setup()
        self.gl_setup()

        #---window size depends on choosen mode--------------------------------
        if MODE == 'FULLSCREEN':
            self.set_fullscreen(True)

        elif MODE in ('EXPORT', 'PREVIEW'):  # export or preview  mode
            self.set_size(self.PREVIEW_SIZE[0], PREVIEW_SIZE[1])
        else:
            print 'error : undefined mode'
            exit()
Exemplo n.º 21
0
 def __init__(self):
     clock.set_fps_limit(fps)
     self.fps_display = clock.ClockDisplay()
     monitor = Monitor(1080, 1920, 13.12, 23.43)
     image_size = monitor.mm_to_px(42)
     image_spacing = monitor.mm_to_px(3.175)
     rows = 4
     cols = 5
     window_width = (cols+1)*image_spacing+cols*image_size
     # extra row for fps display and sync sensor
     window_height = (rows+2)*image_spacing+(rows+1)*image_size
     pyglet.window.Window.__init__(self, width=window_width, height=window_height)
     self.batch_draw = pyglet.graphics.Batch()
     squares = []
     for i in range(rows + 1):
         for j in range(cols):
             x = image_spacing + (j) * (image_size + image_spacing)
             y = window_height - (i + 1) * (image_size + image_spacing)
             squares.append(SquareImage(self.batch_draw, x, y, image_size))
     self.squares = squares[0:20]
     self.squares.append(squares[-1])
     self.run = False
     self.schedule = pyglet.clock.schedule_interval(func=self.update, interval=1/float(fps*2))
Exemplo n.º 22
0
	def createWindow(self):
		
		self.win = None
		if(self.antialiased):
			config = pyglet.gl.Config(sample_buffers=1, samples=4, double_buffer=True)
			self.win = window.Window(width=self.width, height=self.height, vsync=True, resizable=True, config=config)
		else:
			self.win = window.Window(width=self.width, height=self.height, vsync=True, resizable=True)
		
		glEnable(GL_BLEND)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

		# needed so that egi knows where to draw
		egi.InitWithPyglet(self.win)

		# prep the fps display
		self.fps_display = clock.ClockDisplay()
		self.fps_display.label.color = rgba('fff', 0.05)

		# register key and mouse event handlers
		self.win.push_handlers(self.on_key_press)
		self.win.push_handlers(self.on_mouse_press)
		self.win.push_handlers(self.on_resize)
Exemplo n.º 23
0
    def __init__(self, scene, duration=0):
        pyglet.window.Window.__init__(self, vsync=True)
        self.duration = duration
        self.scene = scene
        #---engine setup-------------------------------------------------------
        # schedule pyglet  loop at max framerate
        # and the tick function at more than fps
        # frame / time driven loop
        _DEBUG = 1
        _PREVIEW_SIZE = (600, 600)
        self.background_color = (0.95, 0.95, 0.95, 0)  # background
        self.framerate = 1.0 / 60  # max display framerate
        self.movie_framerate = 1.0 / 25  # framerate for movie export
        self.mode = 'PREVIEW'  # options are: 'FULL'; 'PREVIEW'; 'EXPORT'
        self.chrono = 0.0  # keeps track of total time elapsed
        self.frame_number = 0  # frame counter
        self.paused = False
        self.show_fps = True
        self.pcd = clock.ClockDisplay()
        self.key_setup()
        self.print_keys()
        self.gl_setup()
        self.mouse_setup()

        #---window size depends on choosen mode--------------------------------
        if self.mode == 'FULL':
            self.set_fullscreen(True)
            self.get_display_size()

        elif self.mode in ('EXPORT', 'PREVIEW'):  # export or preview  mode
            self.xmax = _PREVIEW_SIZE[0]
            self.ymax = _PREVIEW_SIZE[1]
            self.set_size(self.xmax, self.ymax)
        else:
            print 'error : undefined mode'
            exit()
Exemplo n.º 24
0
    def __init__(self, w=800, h=600):
        # leave initially invisible, load fonts, etc. then make visible.

        window.Window.__init__(self, visible=False)

        self.fps = clock.ClockDisplay()

        self.big_font = font_resource(FONT_NAME, size=24)
        self.small_font = font_resource(FONT_NAME, size=12)

        self.set_size(w, h)
        self.set_visible(True)
        clock.set_fps_limit(30)

        self.status_text = font.Text(self.small_font, '')
        self.status_text.y = self.height - self.status_text.height
        self.status_text.width = self.width

        # enable alpha-blending since some of our images are semi-transparent.
        # this must be done after creating the window (and really only once but
        # it doesn't matter if we have >1 window/view).

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
Exemplo n.º 25
0
import sys
import random
import math

from pyglet import window
from pyglet import clock
from pyglet import resource

import spryte

NUM_CARS = 100
if len(sys.argv) > 1:
    NUM_CARS = int(sys.argv[1])

win = window.Window(vsync=False)
fps = clock.ClockDisplay(color=(1, 1, 1, 1))

cars = spryte.SpriteBatch()
car = resource.image('car.png')
car.anchor_x = 16
car.anchor_y = 20
for i in range(NUM_CARS):
    s = spryte.Sprite(car,
                      win.width * random.random(),
                      win.height * random.random(),
                      batch=cars,
                      dr=-45 + random.random() * 90)

while not win.has_exit:
    win.dispatch_events()
    clock.tick()
Exemplo n.º 26
0
def on_resize(cx, cy):
    world.cx = cx
    world.cy = cy


if __name__ == '__main__':

    # create a pyglet window and set glOptions
    win = window.Window(width=1000, height=1000, vsync=True, resizable=True)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    # needed so that egi knows where to draw
    egi.InitWithPyglet(win)
    # prep the fps display
    fps_display = clock.ClockDisplay()
    # register key and mouse event handlers
    win.push_handlers(on_key_press)
    win.push_handlers(on_mouse_press)
    win.push_handlers(on_resize)

    # create a world for agents
    world = World(500, 500)
    # add one agent
    world.agents.append(Agent(world))
    world.prey.append(Target(world))
    # unpause the world ready for movement
    world.paused = False
    i = 0
    while not win.has_exit:
        win.dispatch_events()
Exemplo n.º 27
0
    glClear,
    glClearColor,
    glEnable,
    glPopMatrix,
    glPushMatrix,
    glRotatef,
    glTranslatef,
    GL_BLEND,
    GL_COLOR_BUFFER_BIT,
    GL_LINE_SMOOTH,
    GL_ONE_MINUS_SRC_ALPHA,
    GL_SRC_ALPHA,
)

rad2deg = 180 / pi
clockDisplay = clock.ClockDisplay()


class Renderer(object):
    def __init__(self):
        glClearColor(0.1, 0.2, 0.5, 0.0)
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    def on_draw(self, maze, camera, win_width, win_height):
        glClear(GL_COLOR_BUFFER_BIT)
        camera.update_position()
        camera.focus()

        maze.shape.get_batch().draw()
Exemplo n.º 28
0
    def __init__(self, movieFile=None):
        if (movieFile == None):
            print("Usage: python thp.py filename.thp")
            exit(-1)
        fp = file(movieFile, 'rb')
        HEADER = self.THPHeader()
        HEADER.unpack(fp.read(len(HEADER)))
        print(HEADER)
        fp.seek(HEADER.compInfoDataOffsets)
        CompInfo = self.THPFrameCompInfo()
        CompInfo.unpack(fp.read(len(CompInfo)))
        print(CompInfo)
        for i in range(0, CompInfo.numComponents):
            if (CompInfo.frameComp[i] == 0):
                VideoInfo = self.THPCompVideoInfo()
                VideoInfo.unpack(fp.read(len(VideoInfo)))
                print(VideoInfo)
            if (CompInfo.frameComp[i] == 1):
                AudioInfo = self.THPCompAudioInfo()
                AudioInfo.unpack(fp.read(len(AudioInfo)))
                print(AudioInfo)

        clock.set_fps_limit(HEADER.frameRate)
        currOff = HEADER.movieDataOffsets
        currSize = HEADER.firstFrameSize
        fp.seek(currOff)

        win = window.Window(VideoInfo.width, VideoInfo.height)
        fps_display = clock.ClockDisplay()
        i = 1
        j = 1
        image_index = 0
        image_period = 1.0 / HEADER.frameRate  # Reciprocal of the frame rate
        remained = 0

        while not win.has_exit:

            win.dispatch_events()
            win.clear()

            dt = clock.tick()

            skip = math.floor((dt + remained) / image_period)
            j += skip
            print(skip, ":break:", i, j, skip)
            remained = dt - skip * image_period

            tempFrame = self.THPFrameHeader()
            tempFrame.unpack(fp.read(len(tempFrame)))

            for xx in range(1, skip):
                currOff = currOff + currSize
                currSize = tempFrame.frameSizeNext
                fp.seek(currOff)
                tempFrame = self.THPFrameHeader()
                tempFrame.unpack(fp.read(len(tempFrame)))

            imagedat = tempFrame.readData(fp, i)

            pic = image.load("image.jpg", imagedat)
            pic.blit(0, 0)

            currOff = currOff + currSize
            currSize = tempFrame.frameSizeNext
            fp.seek(currOff)

            fps_display.draw()
            win.flip()
            i += 1
Exemplo n.º 29
0
frames = [r['flame%d' % i] for i in range(1, 7)]
flame = AnimatedSprite.from_image(0,
                                  0,
                                  frames[0],
                                  properties=dict(frame=0, t=0, frames=frames))
clock.schedule(flame.update)

frames = [r['boom%d' % i] for i in range(1, 4)]
boom = AnimatedSprite.from_image(0,
                                 0,
                                 frames[0],
                                 properties=dict(frame=0, t=0, frames=frames))
clock.schedule(boom.update)

fps = clock.ClockDisplay(color=(1., .5, .5, .5))

effectlayer = SpriteLayer(5)
rocketlayer = SpriteLayer(1, [rocket])


def play(level):
    view = FlatView.from_window(w, layers=[level, effectlayer, rocketlayer])

    # set rocket start
    for col in level.cells:
        for cell in col:
            if 'player-start' in cell.properties:
                rocket.midtop = cell.midtop

    clock.schedule(rocket.update)
Exemplo n.º 30
0

@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()