Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
class Engine:

  def __init__(self):
    self.updateRate = 1/300. # real-time between physics ticks in seconds. the lower this is the more accurete the physics is
    self.initialSpeed = 0.3
    #self.timestep = self.updateRate * self.initialSpeed # how much game time each simulation represents

    # groups of entities
    self.groups = {
      'all'       : set(),
      'updating'  : set(), # all that have a update function
    }

    self.entityAddQueue = []
    self.entityDelQueue = []

    # layers specify the order in which they are drawn. (ordered back to front)
    self.drawLayerNames = [
      'background',
      'game',
      'foreground',
      # UI ones from here on
      # UI Entities will be drawn in camera space
      'UI_pauseMenu',
      'UI_debug',
    ]

    # A dict from drawLayerNames to a Batch of entities. they are mutually exclusive
    self.drawLayers = { name : Batch()  for name in self.drawLayerNames }
    self.drawCalls =  { name : []       for name in self.drawLayerNames }

    self.levelStartTime = time.time()
    self.levelTime = 0. # TODO proper pausing (maybe move to gameState or some level class)

    self.accumulatedFrameTime = 0.


    # Window
    config = gl.Config(
      sample_buffers=1, samples=4   # antialiasing
    )
    self.window = Window(
      config = config,
      #fullscreen = True,
      vsync = False,
      style = Window.WINDOW_STYLE_BORDERLESS,
    )

    # opengl flags
    gl.glEnable(gl.GL_BLEND) #enables transparency
    # gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)


    # mouse position
    self.windowCenter = Vec2d(self.window.get_size()) / 2
    self.mousePos = Vec2d(self.windowCenter)
    @self.window.event
    def on_mouse_motion(x, y, dx, dy):
      self.mousePos.x = x
      self.mousePos.y = y
    @self.window.event
    def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
      self.mousePos.x = x
      self.mousePos.y = y

    # DEBUG: drop us into a debug shell when
    @self.window.event
    def on_key_press(symbol, modifiers):
      if symbol==key.QUOTELEFT and modifiers & key.MOD_CTRL:
        liveInspect(self)
      elif symbol==key.UP:   self.initialSpeed *= 2.
      elif symbol==key.DOWN: self.initialSpeed *= 0.5

    self.fps_display = clock.ClockDisplay()

    # camera
    self.camera = Camera()


    # shedule our main loop so we don't need to manually deal with time
    clock.schedule(self.run)


  # our main game loop
  def run(self, dt):
    self.timestep = self.updateRate * (self.initialSpeed*2**(self.levelTime*0.2))

    ## UPDATE ##
    # timestep ala http://gafferongames.com/game-physics/fix-your-timestep/
    if dt > .25: # avoid spiral of death (updating taking longer than framerate)
      dt = .25
    self.accumulatedFrameTime += dt
    while self.accumulatedFrameTime >= self.updateRate:
      self.accumulatedFrameTime -= self.updateRate
      self.levelTime = time.time() - self.levelStartTime
      shots = []
      for entity in self.groups['updating']:
        # update all entities, this should not change the state
        shot = entity.update(self.timestep)
        if shot:
          # self.entityAddQueue += response.get("add Entities", [])
          # self.entityDelQueue += response.get("del Entities", [])
          shots.append((entity, shot))

      # this will apply the actions generated by update
      for entity, shot in shots:
        self.entityAddQueue.append(physics.shoot(entity, shot))
      self._processRemoving()
      self._processAdding()

      self.space.step(self.timestep) # this will do the physics and apply all actions
      self._processRemoving()
      self._processAdding()

      if enablePhysicsTesting:
        # DEBUG: test for physics consistency. Disabled as bouncing off Walls changes momentum
        # momentum =                        sum([ e.body.mass * e.body.velocity for e in self.blobs.itervalues() ])
        assertClose(self.physCheck_mass,  sum([ e.body.mass                   for e in self.blobs.itervalues() ]))
        assertClose(self.physCheck_area,  sum([ math.pi * e.radius**2         for e in self.blobs.itervalues() ]))
        # assertClose(self.physCheck_mometum.x, momentum.x)
        # assertClose(self.physCheck_mometum.y, momentum.y)


    ## DRAW ##
    gl.glClearColor(0,0,0, 0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glLoadIdentity()

    self.camera.track() # does camera work (such as what it focuses on)
    for name in self.drawLayerNames:
      for func in self.drawCalls[name]:
        func()
      shift = Vec2d() if name.startswith('UI') else None
      with self.camera.shiftView(shift):
        self.drawLayers[name].draw()


    self.fps_display.draw()
    #self.window.flip()

  def loadLevel(self, levelName):
    # Initialize physics
    self.blobs = {}         # a dict from blob.id to blob
    self.highestBlobId = 0
    self.space = physics.createSpace(self)
    self.spaceView = SpaceView(self.space)

    # self.levelCreator = resources.loadEntities
    self.levelCreator = levelCreator.createLevel

    # load the entities
    for e in self.levelCreator(levelName):
      self.addEntity(e)

    self._processAdding()
    self._processRemoving()

    self.physCheck_mass     = sum([ e.body.mass                   for e in self.blobs.itervalues() ])
    self.physCheck_area     = sum([ math.pi * e.radius**2         for e in self.blobs.itervalues() ])
    self.physCheck_mometum  = sum([ e.body.mass * e.body.velocity for e in self.blobs.itervalues() ])

  def addEntity(   self, e):  self.entityAddQueue.append(e)
  def removeEntity(self, e):  self.entityDelQueue.append(e)


  def _processAdding(self):
    while len(self.entityAddQueue):
      e = self.entityAddQueue.pop(0)
      self.groups["all"].add(e)
      if Entities.isEntityKind_updating(e):   self.groups['updating'].add(e)
      if Entities.isEntityKind_physics(e):
        self.space.add(e.shapes)
        for shape in e.shapes:
          self.spaceView.shapeToEntity[shape] = e
        if e.body is not self.space.static_body:
          self.space.add(e.body)
      if Entities.isEntityKind_visible(e):
        if hasattr(e, 'initGraphics'):
          e.initGraphics(self.drawLayers[e.drawLayer])
        if hasattr(e, 'draw'):
          self.drawCalls[e.drawLayer].append(e.draw)
      if isinstance(e, Blob):
        self.highestBlobId += 1
        e.controller = e.controller(e, self.blobs, self.spaceView)  # initialize the controller
        e.id = self.highestBlobId
        self.blobs[e.id] = e

  def _processRemoving(self):
    while len(self.entityDelQueue):
      e = self.entityDelQueue.pop(0)
      if e in self.groups['all']:
        self.groups['all'].remove(e)
      else:
        # print "was told to delete entity but it was not in the 'all' group: " + repr(e) # DEBUG
        continue
      if Entities.isEntityKind_updating(e):   self.groups['updating'].remove(e)
      if Entities.isEntityKind_physics(e):
        self.space.remove(e.shapes)
        for shape in e.shapes:
          del self.spaceView.shapeToEntity[shape]
        if e.body is not self.space.static_body:
          self.space.remove(e.body)
      if Entities.isEntityKind_visible(e):
        # self.drawLayers[e.drawLayer].remove(e)
        if hasattr(e, 'draw'):
          self.drawCalls[e.drawLayer].remove(e.draw)
        if hasattr(e, 'sprite'):
          e.sprite.delete()
        # for vertexList in e.vertexLists:
        #   vertexList.delete()
      if isinstance(e, Blob):
        del self.blobs[e.id]
Ejemplo n.º 3
0
class Engine:

  updateRate = 1/120. # how often our physics will kick in (in seconds)

  def __init__(self):

    # dictionary from group to list of Entities. they are NOT mutually exclusive
    # don't manually add to this directly! use addEntity/removeEntity.
    self.groups = {
      'all':      set(), # all entities should be in here
      'updating': set(), # everything that wants to be updated goes in here
      'level':    set(),
      'player':   set(),
      'physics':  set(),
      'rockets':  set(),
      'game':     set(), # will draw dependent   on camera movement
      'UI':       set(), # will draw independent of camera movement
      'UI_editor': set(), # entites that are part of the editor UI
    }

    self.entityAddQueue = set()
    self.entityDelQueue = set()

    # layers specify the order in which they are drawn. (ordered back to front)
    self.drawLayerNames = [
      'background',
      'game',
      'player',
      # UI ones from here on
      'UI_editor',
      'UI_pauseMenu',
      'UI_debug',
    ]

    # A dict from drawLayerNames to a list of entities. they are mutually exclusive
    self.drawLayers = {}
    self.drawLayersBatch = {} #a dict from drawLayerNames to a list of batches
    for name in self.drawLayerNames:
      self.drawLayers[name] = set()
      self.drawLayersBatch[name] = Batch()

    self.levelStartTime = time.time()
    self.levelTime = 0. # TODO proper pausing (maybe move to gameState or some level class)

    self.accumulatedFrameTime = 0.

    self.shapeToEntity = {} # a dict that gives the entity that contains the keyed shape

    # Window
    config = gl.Config(
      sample_buffers=1, samples=4   # antialiasing
    )
    self.window = Window(
      config = config,
      #fullscreen = True,
      vsync = False,
      style = Window.WINDOW_STYLE_BORDERLESS,
    )
    self.windowCenter = Vec2d(self.window.get_size()) / 2
    self.mousePos = Vec2d(self.windowCenter)

    # opengl flags
    gl.glEnable(gl.GL_BLEND) #enables transparency


    # camera
    self.camera = Camera()

    @self.window.event
    def on_mouse_motion(x, y, dx, dy):
      self.mousePos.x = x
      self.mousePos.y = y
    @self.window.event
    def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
      self.mousePos.x = x
      self.mousePos.y = y

    self.fps_display = clock.ClockDisplay()

    # shedule our main loop so we don't need to manually deal with time
    clock.schedule(self.run)

    def makeConsole():
      ic = InteractiveConsole(globals())
      try:
        ic.interact("Welcome to the scripting console! press ctrl+D to resume the game")
      except SystemExit, e:
        exit()
    @self.window.event
    def on_key_press(symbol, modifiers):
      if symbol==key.QUOTELEFT and modifiers & key.MOD_CTRL:
        makeConsole()
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
class Game(object):
    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 print_collision(self, arb, surface):
        if self.player.box in surface.shapes:
            #check to see if the player is touching an object
            self.player.touchingObject = True

    def move_camera(self):
        self.camera.setTarget(*self.player.center)

    def set_camera_dx(self, dx):
        self.dx_camera = dx

    def set_camera_dy(self, dy):
        self.dy_camera = dy

    def add_ball(self, x=0, y=0):
        mass = 1
        radius = 4
        inertia = pymunk.moment_for_circle(mass, 0, radius)
        body = pymunk.Body(mass, inertia)
        if not x:
            x = random.randint(120, 380) / 10.0
        if not y:
            y = 100
        body.position = x, y
        #shape = pymunk.Circle(body, radius) # 4
        shape = pymunk.Poly(body, ((-4, -4), (+0, +4), (+4, -4)))
        shape.friction = 0.5
        self.space.add(body, shape)
        return shape

    def draw_ball(self, ball):
        p = int(ball.body.position.x), int(ball.body.position.y)
        glBegin(GL_POLYGON)
        glColor3ub(255, 255, 000)

        points = ((-4 + p[0], -4 + p[1]), (+0 + p[0], +4 + p[1]), (+4 + p[0],
                                                                   -4 + p[1]))
        glVertex2f(*points[0])
        glVertex2f(*points[1])
        glVertex2f(*points[2])
        glEnd()

    def update_objects(self):
        self.move_camera()

        self.player.update_position()

        self.space.step(1 / 30.0)

    def draw(self):
        glClear(GL_COLOR_BUFFER_BIT)
        self.camera.update()
        self.background.draw()
        self.camera.focus(self.win.width, self.win.height)

        self.map.draw()

        for ball in self.balls:
            self.draw_ball(ball)

        for lamp in self.lamps:
            lamp.draw()

        #for powerup in self.powerups:
        #    powerup.draw()

        self.player.draw()

        for lamp in self.lamps:
            lamp.draw_flare()

        #draw a small cube at the origin

        glBegin(GL_POLYGON)
        glColor3ub(255, 255, 255)
        glVertex2f(-1, -1)
        glVertex2f(-1, 1)
        glVertex2f(1, 1)
        glVertex2f(1, -1)
        glEnd()

        self.camera.hud_mode(self.win.width, self.win.height)

        self.darkness.draw()

        #glColor3ub(50, 50, 50)
        self.clockDisplay.draw()
Ejemplo n.º 6
0
class Game(object):
    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 print_collision(self, arb, surface):
        if self.player.box in surface.shapes:
            #check to see if the player is touching an object
            self.player.touchingObject = True

    def move_camera(self):
        self.camera.setTarget(*self.player.center)

    def set_camera_dx(self, dx):
        self.dx_camera = dx

    def set_camera_dy(self, dy):
        self.dy_camera = dy

    def add_ball(self, x=0, y=0):
        mass = 1
        radius = 4
        inertia = pymunk.moment_for_circle(mass, 0, radius)
        body = pymunk.Body(mass, inertia)
        if not x:
            x = random.randint(120,380) / 10.0
        if not y:
            y = 100
        body.position = x, y
        #shape = pymunk.Circle(body, radius) # 4
        shape = pymunk.Poly(body, (
            (-4, -4),
            (+0, +4),
            (+4, -4)))
        shape.friction = 0.5
        self.space.add(body, shape)
        return shape

    def draw_ball(self, ball):
        p = int(ball.body.position.x), int(ball.body.position.y)
        glBegin(GL_POLYGON)
        glColor3ub(255, 255, 000)

        points = ((-4 + p[0], -4 + p[1]),
                  (+0 + p[0], +4 + p[1]),
                  (+4 + p[0], -4 + p[1]))
        glVertex2f(*points[0])
        glVertex2f(*points[1])
        glVertex2f(*points[2])
        glEnd()

    def update_objects(self):
        self.move_camera()

        self.player.update_position()

        self.space.step(1/30.0)

    def draw(self):
        glClear(GL_COLOR_BUFFER_BIT)
        self.camera.update()
        self.background.draw()
        self.camera.focus(self.win.width, self.win.height)

        self.map.draw()

        for ball in self.balls:
            self.draw_ball(ball)

        for lamp in self.lamps:
            lamp.draw()

        #for powerup in self.powerups:
        #    powerup.draw()

        self.player.draw()

        for lamp in self.lamps:
            lamp.draw_flare()

        #draw a small cube at the origin

        glBegin(GL_POLYGON)
        glColor3ub(255, 255, 255)
        glVertex2f(-1, -1)
        glVertex2f(-1, 1)
        glVertex2f(1, 1)
        glVertex2f(1, -1)
        glEnd()

        self.camera.hud_mode(self.win.width, self.win.height)

        self.darkness.draw()

        #glColor3ub(50, 50, 50)
        self.clockDisplay.draw()
Ejemplo n.º 7
0
        self._set_yticks(yticks, ylabels)

    def set_xticklabels(self, xlabels):
        self._set_xticks(self._xticks, xlabels)

    def set_yticklabels(self, ylabels):
        self._set_yticks(self._yticks, ylabels)

if __name__ == "__main__":

    import pyglet
    from pyglet.window import Window
    import numpy

    window = Window()
    width, height = window.get_size()

    figure = GLFigure()
    figure.set_rect([0, 0, width, height])

    x = numpy.linspace(0, 2*numpy.pi, 1024)
    y = numpy.sin(x) + 0.1 * numpy.random.random(x.shape)
    ax = figure.add_axes([0.1, 0.1, 0.8, 0.8])
    ax.plot(x, y, 'g')

    @window.event
    def on_draw():
        figure._draw()

    pyglet.app.run()