Ejemplo n.º 1
0
 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)
Ejemplo n.º 2
0
 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)
Ejemplo n.º 3
0
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()
Ejemplo n.º 5
0
Archivo: demo.py Proyecto: msarch/py
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()
Ejemplo n.º 6
0
Archivo: demo.py Proyecto: msarch/py
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()
Ejemplo n.º 7
0
 def test_caption(self):
     try:
         w1 = Window(400, 200, resizable=True)
         w2 = Window(400, 200, resizable=True)
         count = 1
         w1.set_caption('Window caption %d' % count)
         w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
         last_time = time.time()
         while not (w1.has_exit or w2.has_exit):
             if time.time() - last_time > 1:
                 count += 1
                 w1.set_caption('Window caption %d' % count)
                 last_time = time.time()
             w1.dispatch_events()
             w2.dispatch_events()
     finally:
         w1.close()
         w2.close()
     self.user_verify('Pass test?', take_screenshot=False)
Ejemplo n.º 8
0
    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()
Ejemplo n.º 9
0
class ImageViewer:
    def __init__(self, display=None, maxwidth=500):
        self.window = None
        self.isopen = False
        self.display = display

    def __del__(self):
        self.close()

    def imshow(self, arr, caption):
        if self.window is None:
            height, width, _ = arr.shape
            self.window = Window(width=width,
                                 height=height,
                                 display=self.display,
                                 vsync=False,
                                 resizable=True)
            self.width = width
            self.height = height
            self.isopen = True
        assert len(arr.shape) == 3
        height, width, _ = arr.shape
        image = pyglet.image.ImageData(width,
                                       height,
                                       'RGB',
                                       arr.tobytes(),
                                       pitch=-3 * width)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)
        texture = image.get_texture()
        texture.width = self.width
        texture.height = self.height
        self.window.clear()
        self.window.switch_to()
        self.window.dispatch_events()
        texture.blit(0, 0)
        self.window.flip()
        self.window.set_caption(caption)

    def close(self):
        if self.isopen:
            self.window.close()
            self.isopen = False
Ejemplo n.º 10
0
class NumpyTube:
    def __init__(self):
        self.window = None
        self.isopen = False

    def __del__(self):
        self.close()

    def imshow(self, img, caption=None):
        height, width, _ = img.shape
        pitch = -3 * width

        if self.window is None:
            self.window = Window(width=width, height=height, vsync=False)
            self.width = width
            self.height = height
            self.isopen = True

        data = img.tobytes()
        image = pyglet.image.ImageData(width, height, "RGB", data, pitch=pitch)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)

        texture = image.get_texture()
        texture.width = self.width
        texture.height = self.height

        self.window.clear()
        self.window.switch_to()
        self.window.dispatch_events()
        texture.blit(0, 0)
        self.window.flip()

        if caption is not None:
            self.window.set_caption(caption)

    def close(self):
        if self.isopen:
            self.window.close()
            self.window = None
            self.isopen = False
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
Archivo: run.py Proyecto: msarch/py
        glPopMatrix()

    camera.hud_mode(win.width, win.height)
    clockDisplay.draw()

def update(dt):
    for idx, entity in enumerate(entities):
        entity.angle += ((entity.x) + abs(entity.y)) / 10000
        entity.x += sin(entity.angle) / (1+idx) * 10
        entity.y -= cos(entity.angle) / (1+idx) * 10
    camera.zoom(1.008)

clock.schedule(update) # triggers on_draw event when done

key_handlers = {
    key.ESCAPE: lambda: win.close(),
    key.PAGEUP: lambda: camera.zoom(2),
    key.PAGEDOWN: lambda: camera.zoom(0.5),
    key.LEFT: lambda: camera.pan(camera.scale, -pi/2),
    key.RIGHT: lambda: camera.pan(camera.scale, +pi/2),
    key.DOWN: lambda: camera.pan(camera.scale, pi),
    key.UP: lambda: camera.pan(camera.scale, 0),
    key.COMMA: lambda: camera.tilt(-1),
    key.PERIOD: lambda: camera.tilt(+1),
}

@win.event
def on_key_press(symbol, modifiers):
    handler = key_handlers.get(symbol, lambda: None)
    handler()
Ejemplo n.º 13
0
class MapModelTest(unittest.TestCase):
    def setUp(self):
        self.w = Window(width=1, height=1, visible=False)

    def tearDown(self):
        self.w.close()

    def test_rect_neighbor(self):
        # test rectangular tile map
        # +---+---+---+
        #    | d | e | f |
        #    +---+---+---+
        #    | a | b | c |
        #    +---+---+---+
        m = gen_rect_map(rmd, 10, 16)
        t = m.get_cell(0, 0)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'd'
        assert m.get_neighbor(t, m.LEFT) is None
        assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'b'
        t = m.get_neighbor(t, m.UP)
        assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'd'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'a'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.LEFT) is None
        assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'e'
        t = m.get_neighbor(t, m.RIGHT)
        assert (t.x, t.y) == (1, 1) and t.properties['meta'] == 'e'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'b'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'd'
        t = m.get_neighbor(t, m.RIGHT)
        assert (t.x, t.y) == (2, 1) and t.properties['meta'] == 'f'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'c'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.RIGHT) is None
        assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'e'
        t = m.get_neighbor(t, m.DOWN)
        assert (t.x, t.y) == (2, 0) and t.properties['meta'] == 'c'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.RIGHT) is None
        assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'b'

    def test_rect_coords(self):
        # test rectangular tile map
        # +---+---+---+
        #    | d | e | f |
        #    +---+---+---+
        #    | a | b | c |
        #    +---+---+---+
        m = gen_rect_map(rmd, 10, 16)

        # test tile sides / corners
        t = m.get_cell(0, 0)
        assert t.top == 16
        assert t.bottom == 0
        assert t.left == 0
        assert t.right == 10
        assert t.topleft == (0, 16)
        assert t.topright == (10, 16)
        assert t.bottomleft == (0, 0)
        assert t.bottomright == (10, 0)
        assert t.midtop == (5, 16)
        assert t.midleft == (0, 8)
        assert t.midright == (10, 8)
        assert t.midbottom == (5, 0)

    def test_rect_pixel(self):
        # test rectangular tile map
        # +---+---+---+
        #    | d | e | f |
        #    +---+---+---+
        #    | a | b | c |
        #    +---+---+---+
        m = gen_rect_map(rmd, 10, 16)
        t = m.get(0, 0)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(9, 15)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(10, 15)
        assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'b'
        t = m.get(9, 16)
        assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'd'
        t = m.get(10, 16)
        assert (t.x, t.y) == (1, 1) and t.properties['meta'] == 'e'

    def test_hex_neighbor(self):
        # test hexagonal tile map
        # tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
        # /d\ /h\
        # /b\_/f\_/
        # \_/c\_/g\
        # /a\_/e\_/
        # \_/ \_/
        m = gen_hex_map(hmd, 32)
        t = m.get_cell(0, 0)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'b'
        assert m.get_neighbor(t, m.DOWN_LEFT) is None
        assert m.get_neighbor(t, m.DOWN_RIGHT) is None
        assert m.get_neighbor(t, m.UP_LEFT) is None
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'c'
        t = m.get_neighbor(t, m.UP)
        assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'b'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'a'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.DOWN_LEFT) is None
        assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'c'
        assert m.get_neighbor(t, m.UP_LEFT) is None
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'd'
        t = m.get_neighbor(t, m.DOWN_RIGHT)
        assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'c'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'd'
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'a'
        assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'e'
        assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'b'
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'f'
        t = m.get_neighbor(t, m.UP_RIGHT)
        assert (t.x, t.y) == (2, 1) and t.properties['meta'] == 'f'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'e'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'c'
        assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'g'
        assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'd'
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'h'
        t = m.get_neighbor(t, m.DOWN_RIGHT)
        assert (t.x, t.y) == (3, 0) and t.properties['meta'] == 'g'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'h'
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'e'
        assert m.get_neighbor(t, m.DOWN_RIGHT) is None
        assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.UP_RIGHT) is None
        t = m.get_neighbor(t, m.UP)
        assert (t.x, t.y) == (3, 1) and t.properties['meta'] == 'h'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'g'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.DOWN_RIGHT) is None
        assert m.get_neighbor(t, m.UP_LEFT) is None
        assert m.get_neighbor(t, m.UP_RIGHT) is None

    def test_hex_coords(self):
        # test hexagonal tile map
        # tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
        # /d\ /h\
        # /b\_/f\_/
        # \_/c\_/g\
        # /a\_/e\_/
        # \_/ \_/
        m = gen_hex_map(hmd, 32)

        # test tile sides / corners
        t00 = m.get_cell(0, 0)
        assert t00.top == 32
        assert t00.bottom == 0
        assert t00.left == (0, 16)
        assert t00.right == (36, 16)
        assert t00.center == (18, 16)
        assert t00.topleft == (9, 32)
        assert t00.topright == (27, 32)
        assert t00.bottomleft == (9, 0)
        assert t00.bottomright == (27, 0)
        assert t00.midtop == (18, 32)
        assert t00.midbottom == (18, 0)
        assert t00.midtopleft == (4, 24)
        assert t00.midtopright == (31, 24)
        assert t00.midbottomleft == (4, 8)
        assert t00.midbottomright == (31, 8)

        t10 = m.get_cell(1, 0)
        assert t10.top == 48
        assert t10.bottom == 16
        assert t10.left == t00.topright
        assert t10.right == (63, 32)
        assert t10.center == (45, 32)
        assert t10.topleft == (36, 48)
        assert t10.topright == (54, 48)
        assert t10.bottomleft == t00.right
        assert t10.bottomright == (54, 16)
        assert t10.midtop == (45, 48)
        assert t10.midbottom == (45, 16)
        assert t10.midtopleft == (31, 40)
        assert t10.midtopright == (58, 40)
        assert t10.midbottomleft == t00.midtopright
        assert t10.midbottomright == (58, 24)

        t = m.get_cell(2, 0)
        assert t.top == 32
        assert t.bottom == 0
        assert t.left == t10.bottomright
        assert t.right == (90, 16)
        assert t.center == (72, 16)
        assert t.topleft == t10.right
        assert t.midtopleft == t10.midbottomright

    def test_hex_pixel(self):
        # test hexagonal tile map
        # tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
        # /d\ /h\
        # /b\_/f\_/
        # \_/c\_/g\
        # /a\_/e\_/
        # \_/ \_/
        m = gen_hex_map(hmd, 32)
        t = m.get(0, 0)
        assert t is None
        t = m.get(0, 16)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(16, 16)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(35, 16)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(36, 16)
        assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'c'

    def test_hex_dimensions(self):
        m = gen_hex_map([[{'a': 'a'}]], 32)
        assert m.pxw, m.pxh == (36, 32)
        m = gen_hex_map([[{'a': 'a'}] * 2], 32)
        assert m.pxw, m.pxh == (36, 64)
        m = gen_hex_map([[{'a': 'a'}]] * 2, 32)
        assert m.pxw, m.pxh == (63, 48)

    unittest.main()
Ejemplo n.º 14
0
class Camera_test(MyTestCase):

    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 tearDown(self):
        self.window.close()


    def test_constructor(self):
        camera = Camera((1, 2), 3, 4)
        self.assertEquals(camera.x, 1, "should init x")
        self.assertEquals(camera.y, 2, "should init y")
        self.assertEquals(camera.scale, 3, "should init scale")
        self.assertEquals(camera.angle, 4, "should init angle")


    def test_constructor_defaults_angle(self):
        camera = Camera((10, 20), 30)
        self.assertEquals(camera.angle, 0.0, "should init angle")


    def _draw_rect(self, backColor, polyColor, left, bottom, right, top):
        glClearColor(
            backColor[0]/255,
            backColor[1]/255,
            backColor[2]/255,
            1.0)
        self.window.clear()

        verts = [
            (left, bottom),
            (right, bottom),
            (right, top),
            (left, top),
        ]
        glColor3ub(*polyColor)
        glBegin(GL_TRIANGLE_FAN)
        for vert in verts:
            glVertex2f(*vert)
        glEnd()


    def test_world_projection_default(self):
        rect = (-0.2, -0.4, +0.6, +0.8)
        expectedRect = (90, 10, 129, 69)
        self.assert_world_projection(rect, expectedRect)


    def test_defect_pyglet_get_color_buffer_for_resized_windows(self):
        self.window.set_size(111, 222)
        self.window.dispatch_events()
        mgr = get_buffer_manager()
        col_buf = mgr.get_color_buffer()
        col_buf_size = col_buf.width, col_buf.height
        self.assertEquals(col_buf_size, (111, 222), "pyglet bug regression")


    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_world_projection_offset(self):
        self.camera.x, self.camera.y = (+0.5, +0.3)
        rect = (-0.2, -0.4, +0.6, +0.8)
        expectedRect = (65, 25, 104, 84)
        self.assert_world_projection(rect, expectedRect)


    def test_world_projection_scale(self):
        self.camera.scale = 10
        rect = (-1, -2, +3, +4)
        expectedRect = (95, 30, 114, 59)
        self.assert_world_projection(rect, expectedRect)


    def test_world_projection_angle(self):
        self.camera.angle = pi/2
        rect = (-0.2, -0.4, +0.6, +0.8)
        expectedRect = (60, 20, 119, 59)
        self.assert_world_projection(rect, expectedRect)


    def test_world_projection_complicated(self):
        self.camera.angle = -pi/2
        self.camera.scale = 10
        self.camera.x, self.camera.y = (5, 6)
        rect = (-1, -2, +3, +4)
        expectedRect = (60, 20, 89, 39)
        self.assert_world_projection(rect, expectedRect)
Ejemplo n.º 15
0
class ImageViewer(object):
    def __init__(self, width, height, display=None):
        from pyglet.window import Window
        self.sheet = SpriteSheet()
        self.display = display
        self.window = Window(width=width * self.sheet.BLOCK_WIDTH,
                             height=height * self.sheet.BLOCK_WIDTH,
                             display=self.display)
        self.isopen = True
        self.init_blend()

    def init_blend(self):
        from pyglet.gl import (GL_BLEND, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA,
                               glBlendFunc, glEnable)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    def render_state(self, state, x_offset=0, flip=True):
        import pyglet
        darken = pyglet.image.SolidColorImagePattern(color=(0, 0, 0, 128))
        if flip:
            self.begin_flip()
        for i, entity in enumerate(state.entities):
            if entity is None:
                continue
            y, x = divmod(i, state.width)
            neighbours = [None] * 4
            neighbours[1] = state[x, y - 1]
            neighbours[0] = state[x, y + 1]
            neighbours[3] = state[x - 1, y]
            neighbours[2] = state[x + 1, y]
            if state.tsu_rules:
                if y == 0:
                    neighbours = [None] * 4
                elif y == 1:
                    neighbours[1] = None
            sprite = self.sheet.get_sprite(entity, neighbours)
            sprite.blit(
                (x + x_offset) * self.sheet.BLOCK_WIDTH,
                (state.height - 1 - y) * self.sheet.BLOCK_WIDTH,
            )
            if state.tsu_rules and y == 0:
                mask = darken.create_image(self.sheet.BLOCK_WIDTH + 1,
                                           self.sheet.BLOCK_WIDTH)
                mask.blit(
                    (x + x_offset) * self.sheet.BLOCK_WIDTH,
                    (state.height - 1 - y) * self.sheet.BLOCK_WIDTH,
                )
        for i, deal in enumerate(state.deals):
            for j, entity in enumerate(deal):
                neighbours = [None] * 4
                # Deals are usually not rendered "sticky"
                # neighbours[2 + j] = deal[1 - j]
                sprite = self.sheet.get_sprite(entity, neighbours)
                sprite.blit(
                    (state.width + 2 + j + x_offset) * self.sheet.BLOCK_WIDTH,
                    (state.height - 1 - 2 * i) * self.sheet.BLOCK_WIDTH,
                )

        if flip:
            self.end_flip()

    def begin_flip(self):
        self.window.clear()
        self.window.switch_to()
        self.window.dispatch_events()

    def end_flip(self):
        self.window.flip()

    def save_screenshot(self, filename):
        from pyglet.image import get_buffer_manager
        get_buffer_manager().get_color_buffer().save(filename)

    def close(self):
        if self.isopen:
            self.window.close()
            self.isopen = False

    def __del__(self):
        self.close()
Ejemplo n.º 16
0
class ExpWindow(object):
    def __init__(self, background_color=dark_gray, clock=mono_clock.get_time):
        # 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))

    def on_key_press(self, symbol, modifiers):
        if symbol == pyglet.window.key.ESCAPE:
            sys.exit(1)

    def _on_close(self):
        if self._win.context:
            self._win.close()

    def flip(self):
        self._win.switch_to()
        self._win.dispatch_events()
        self._win.flip()
        self.context.clear(*self._background_color)
        current_time = self.clock()
        self.prev_time = self.current_time
        self.current_time = current_time
        return self.current_time

    def close(self):
        self._win.close()

    @property
    def dt(self):
        return self.current_time - self.prev_time

    def set_mouse_visible(self, val):
        self._win.set_mouse_visible(val)

    @property
    def width(self):
        return self._win.width

    @property
    def height(self):
        return self._win.height

    @property
    def background_color(self):
        return self._background_color

    @background_color.setter
    def background_color(self, val):
        if len(val) != 4:
            raise ValueError('Background color must be RGBA.')
        self._background_color.xyzw = val

    @property
    def frame_period(self):
        # get a whole-number version of the frame period
        # very coarse and fragile, should get this from the
        # the video mode, e.g. glfw.get_video_mode
        if not hasattr(self, '_frame_period'):
            possible = [60.0, 144.0, 240.0]  # TODO: infer from machine...
            vals = []
            for _ in range(20):
                self.flip()
                vals.append(self.dt)
            # chop off the first few, which are not reflective of the
            # "real" FPS
            avg = 1/(sum(vals[5:])/float(len(vals[5:])))
            dff = [abs(avg - p) for p in possible]
            fps = [v for v, d in zip(possible, dff) if d == min(dff)]
            if not len(fps):
                self._frame_period = 1/60.0  # default
            else:
                self._frame_period = 1/fps[0]
        return self._frame_period
Ejemplo n.º 17
0
numsprites = int(sys.argv[1])
for i in range(numsprites):
    x = random.randint(0, w.width-img.width)
    y = random.randint(0, w.height-img.height)
    s = BouncySprite(x, y, img.width, img.height, img)
    s.dx = random.randint(-10, 10)
    s.dy = random.randint(-10, 10)
    sprites.append(s)

view = FlatView.from_window(w, sprites=sprites)
view.fx, view.fy = w.width/2, w.height/2

t = 0
numframes = 0
while 1:
    if w.has_exit:
        print 'FPS:', clock.get_fps()
        print 'us per sprite:', float(t) / (numsprites * numframes) * 1000000

        break
    t += clock.tick()
    w.dispatch_events()
    for s in sprites: s.update()
    view.clear()
    view.draw()
    w.flip()
    numframes += 1
w.close()


Ejemplo n.º 18
0
class ImageViewer(object):
    """A simple class for viewing images using pyglet."""
    def __init__(self,
                 caption,
                 height,
                 width,
                 monitor_keyboard=False,
                 relevant_keys=None):
        """
        Initialize a new image viewer.

        Args:
            caption (str): the caption/title for the window
            height (int): the height of the window
            width (int): the width of the window
            monitor_keyboard: whether to monitor events from the keyboard
            relevant_keys: the relevant keys to monitor events from

        Returns:
            None
        """
        self.caption = caption
        self.height = height
        self.width = width
        self.monitor_keyboard = monitor_keyboard
        self.relevant_keys = relevant_keys
        self._window = None
        self._pressed_keys = []
        self._is_escape_pressed = False

    @property
    def is_open(self):
        """Return a boolean determining if this window is open."""
        return self._window is not None

    @property
    def is_escape_pressed(self):
        """Return True if the escape key is pressed."""
        return self._is_escape_pressed

    @property
    def pressed_keys(self):
        """Return a sorted list of the pressed keys."""
        return tuple(sorted(self._pressed_keys))

    def _handle_key_event(self, symbol, is_press):
        """
        Handle a key event.

        Args:
            symbol: the symbol in the event
            is_press: whether the event is a press or release

        Returns:
            None

        """
        # remap the key to the expected domain
        symbol = KEY_MAP.get(symbol, symbol)
        # check if the symbol is the escape key
        if symbol == key.ESCAPE:
            self._is_escape_pressed = is_press
            return
        # make sure the symbol is relevant
        if self.relevant_keys is not None and symbol not in self.relevant_keys:
            return
        # handle the press / release by appending / removing the key to pressed
        if is_press:
            self._pressed_keys.append(symbol)
        else:
            self._pressed_keys.remove(symbol)

    def on_key_press(self, symbol, modifiers):
        """Respond to a key press on the keyboard."""
        self._handle_key_event(symbol, True)

    def on_key_release(self, symbol, modifiers):
        """Respond to a key release on the keyboard."""
        self._handle_key_event(symbol, False)

    def open(self):
        """Open the window."""
        # create a window for this image viewer instance
        self._window = Window(
            caption=self.caption,
            height=self.height,
            width=self.width,
            vsync=False,
            resizable=True,
        )

        # add keyboard event monitors if enabled
        if self.monitor_keyboard:
            self._window.event(self.on_key_press)
            self._window.event(self.on_key_release)
            self._window.set_exclusive_keyboard()

    def close(self):
        """Close the window."""
        if self.is_open:
            self._window.close()
            self._window = None

    def show(self, frame):
        """
        Show an array of pixels on the window.

        Args:
            frame (numpy.ndarray): the frame to show on the window

        Returns:
            None
        """
        # check that the frame has the correct dimensions
        if len(frame.shape) != 3:
            raise ValueError('frame should have shape with only 3 dimensions')
        # open the window if it isn't open already
        if not self.is_open:
            self.open()
        # prepare the window for the next frame
        self._window.clear()
        self._window.switch_to()
        self._window.dispatch_events()
        # create an image data object
        image = ImageData(frame.shape[1],
                          frame.shape[0],
                          'RGB',
                          frame.tobytes(),
                          pitch=frame.shape[1] * -3)
        # send the image to the window
        image.blit(0, 0, width=self._window.width, height=self._window.height)
        self._window.flip()
Ejemplo n.º 19
0
    camera.hud_mode(win.width, win.height)
    clockDisplay.draw()


def update(dt):
    for idx, entity in enumerate(entities):
        entity.angle += ((entity.x) + abs(entity.y)) / 10000
        entity.x += sin(entity.angle) / (1 + idx) * 10
        entity.y -= cos(entity.angle) / (1 + idx) * 10
    camera.zoom(1.008)


clock.schedule(update)  # triggers on_draw event when done

key_handlers = {
    key.ESCAPE: lambda: win.close(),
    key.PAGEUP: lambda: camera.zoom(2),
    key.PAGEDOWN: lambda: camera.zoom(0.5),
    key.LEFT: lambda: camera.pan(camera.scale, -pi / 2),
    key.RIGHT: lambda: camera.pan(camera.scale, +pi / 2),
    key.DOWN: lambda: camera.pan(camera.scale, pi),
    key.UP: lambda: camera.pan(camera.scale, 0),
    key.COMMA: lambda: camera.tilt(-1),
    key.PERIOD: lambda: camera.tilt(+1),
}


@win.event
def on_key_press(symbol, modifiers):
    handler = key_handlers.get(symbol, lambda: None)
    handler()
sprites = []
numsprites = int(sys.argv[1])
for i in range(numsprites):
    x = random.randint(0, w.width - img.width)
    y = random.randint(0, w.height - img.height)
    s = BouncySprite(x, y, img.width, img.height, img)
    s.dx = random.randint(-10, 10)
    s.dy = random.randint(-10, 10)
    sprites.append(s)

view = FlatView.from_window(w, sprites=sprites)
view.fx, view.fy = w.width / 2, w.height / 2

t = 0
numframes = 0
while 1:
    if w.has_exit:
        print 'FPS:', clock.get_fps()
        print 'us per sprite:', float(t) / (numsprites * numframes) * 1000000

        break
    t += clock.tick()
    w.dispatch_events()
    for s in sprites:
        s.update()
    view.clear()
    view.draw()
    w.flip()
    numframes += 1
w.close()
Ejemplo n.º 21
0
class SpriteModelTest(unittest.TestCase):
    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 tearDown(self):
        self.w.close()

    def test_top(self):
        assert self.s.top == 20
        self.s.top = 10
        assert (self.s.x, self.s.y) == (10, 0)

    def test_bottom(self):
        assert self.s.bottom == 10
        self.s.bottom = 0
        assert (self.s.x, self.s.y) == (10, 0)

    def test_right(self):
        assert self.s.right == 20
        self.s.right = 10
        assert (self.s.x, self.s.y) == (0, 10)

    def test_left(self):
        assert self.s.left == 10
        self.s.left = 0
        assert (self.s.x, self.s.y) == (0, 10)

    def test_center(self):
        assert self.s.center == (15, 15)
        self.s.center = (5, 5)
        assert (self.s.x, self.s.y) == (0, 0)

    def test_midtop(self):
        assert self.s.midtop == (15, 20)
        self.s.midtop = (5, 5)
        assert (self.s.x, self.s.y) == (0, -5)

    def test_midbottom(self):
        assert self.s.midbottom == (15, 10)
        self.s.midbottom = (5, 5)
        assert (self.s.x, self.s.y) == (0, 5)

    def test_midleft(self):
        assert self.s.midleft == (10, 15)
        self.s.midleft = (5, 5)
        assert (self.s.x, self.s.y) == (5, 0)

    def test_midright(self):
        assert self.s.midright == (20, 15)
        self.s.midright = (5, 5)
        assert (self.s.x, self.s.y) == (-5, 0)

    def test_topleft(self):
        assert self.s.topleft == (10, 20)
        self.s.topleft = (5, 5)
        assert (self.s.x, self.s.y) == (5, -5)

    def test_topright(self):
        assert self.s.topright == (20, 20)
        self.s.topright = (5, 5)
        assert (self.s.x, self.s.y) == (-5, -5)

    def test_bottomright(self):
        assert self.s.bottomright == (20, 10)
        self.s.bottomright = (5, 5)
        assert (self.s.x, self.s.y) == (-5, 5)

    def test_bottomleft(self):
        assert self.s.bottomleft == (10, 10)
        self.s.bottomleft = (5, 5)
        assert (self.s.x, self.s.y) == (5, 5)

    unittest.main()
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
Archivo: Game.py Proyecto: varnie/snake
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)
Ejemplo n.º 25
0
class ImageViewer(object):
    """A simple class for viewing images using pyglet."""
    def __init__(self, caption, height, width):
        """
        Initialize a new image viewer.

        Args:
            caption (str): the caption/title for the window
            height (int): the height of the window
            width (int): the width of the window

        Returns:
            None
        """
        self.caption = caption
        self.height = height
        self.width = width
        self._window = None

    def __repr__(self):
        """Return an executable string representing this object."""
        template = '{}(caption={}, height={}, width={})'
        return template.format(self.caption, self.height, self.width)

    def __del__(self):
        """Close any open windows and delete this object."""
        self.close()

    @property
    def is_open(self):
        """Return a boolean determining if this window is open."""
        return self._window is not None

    def open(self):
        """Open the window."""
        self._window = Window(
            caption=self.caption,
            height=self.height,
            width=self.width,
            vsync=False,
            resizable=True,
        )

    def show(self, frame):
        """
        Show an array of pixels on the window.

        Args:
            frame (numpy.ndarray): the frame to show on the window

        Returns:
            None
        """
        # check that the frame has the correct dimensions
        if len(frame.shape) != 3:
            raise ValueError('frame should have shape with only 3 dimensions')
        # open the window if it isn't open already
        if not self.is_open:
            self.open()
        # prepare the window for the next frame
        self._window.clear()
        self._window.switch_to()
        self._window.dispatch_events()
        # create an image data object
        image = ImageData(frame.shape[1],
                          frame.shape[0],
                          'RGB',
                          frame.tobytes(),
                          pitch=frame.shape[1] * -3)
        # send the image to the window
        image.blit(0, 0, width=self._window.width, height=self._window.height)
        self._window.flip()

    def close(self):
        """Close the window."""
        if self.is_open:
            self._window.close()
            self._window = None
Ejemplo n.º 26
0
class MapModelTest(unittest.TestCase):
    def setUp(self):
        self.w = Window(width=1, height=1, visible=False)

    def tearDown(self):
        self.w.close()

    def test_rect_neighbor(self):
        # test rectangular tile map
        #    +---+---+---+
        #    | d | e | f |
        #    +---+---+---+
        #    | a | b | c |
        #    +---+---+---+
        m = gen_rect_map(rmd, 10, 16)
        t = m.get_cell(0,0)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'd'
        assert m.get_neighbor(t, m.LEFT) is None
        assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'b'
        t = m.get_neighbor(t, m.UP)
        assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'd'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'a'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.LEFT) is None
        assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'e'
        t = m.get_neighbor(t, m.RIGHT)
        assert (t.x, t.y) == (1, 1) and t.properties['meta'] == 'e'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'b'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.RIGHT).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'd'
        t = m.get_neighbor(t, m.RIGHT)
        assert (t.x, t.y) == (2, 1) and t.properties['meta'] == 'f'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'c'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.RIGHT) is None
        assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'e'
        t = m.get_neighbor(t, m.DOWN)
        assert (t.x, t.y) == (2, 0) and t.properties['meta'] == 'c'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.RIGHT) is None
        assert m.get_neighbor(t, m.LEFT).properties['meta'] == 'b'

    def test_rect_coords(self):
        # test rectangular tile map
        #    +---+---+---+
        #    | d | e | f |
        #    +---+---+---+
        #    | a | b | c |
        #    +---+---+---+
        m = gen_rect_map(rmd, 10, 16)

        # test tile sides / corners
        t = m.get_cell(0,0)
        assert t.top == 16
        assert t.bottom == 0
        assert t.left == 0
        assert t.right == 10
        assert t.topleft == (0, 16)
        assert t.topright == (10, 16)
        assert t.bottomleft == (0, 0)
        assert t.bottomright == (10, 0)
        assert t.midtop == (5, 16)
        assert t.midleft == (0, 8)
        assert t.midright == (10, 8)
        assert t.midbottom == (5, 0)

    def test_rect_pixel(self):
        # test rectangular tile map
        #    +---+---+---+
        #    | d | e | f |
        #    +---+---+---+
        #    | a | b | c |
        #    +---+---+---+
        m = gen_rect_map(rmd, 10, 16)
        t = m.get(0,0)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(9,15)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(10,15)
        assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'b'
        t = m.get(9,16)
        assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'd'
        t = m.get(10,16)
        assert (t.x, t.y) == (1, 1) and t.properties['meta'] == 'e'

    def test_hex_neighbor(self):
        # test hexagonal tile map
        # tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
        #   /d\ /h\
        # /b\_/f\_/
        # \_/c\_/g\
        # /a\_/e\_/
        # \_/ \_/ 
        m = gen_hex_map(hmd, 32)
        t = m.get_cell(0,0)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'b'
        assert m.get_neighbor(t, m.DOWN_LEFT) is None
        assert m.get_neighbor(t, m.DOWN_RIGHT) is None
        assert m.get_neighbor(t, m.UP_LEFT) is None
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'c'
        t = m.get_neighbor(t, m.UP)
        assert (t.x, t.y) == (0, 1) and t.properties['meta'] == 'b'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'a'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.DOWN_LEFT) is None
        assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'c'
        assert m.get_neighbor(t, m.UP_LEFT) is None
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'd'
        t = m.get_neighbor(t, m.DOWN_RIGHT)
        assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'c'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'd'
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'a'
        assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'e'
        assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'b'
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'f'
        t = m.get_neighbor(t, m.UP_RIGHT)
        assert (t.x, t.y) == (2, 1) and t.properties['meta'] == 'f'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'e'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'c'
        assert m.get_neighbor(t, m.DOWN_RIGHT).properties['meta'] == 'g'
        assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'd'
        assert m.get_neighbor(t, m.UP_RIGHT).properties['meta'] == 'h'
        t = m.get_neighbor(t, m.DOWN_RIGHT)
        assert (t.x, t.y) == (3, 0) and t.properties['meta'] == 'g'
        assert m.get_neighbor(t, m.DOWN) is None
        assert m.get_neighbor(t, m.UP).properties['meta'] == 'h'
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'e'
        assert m.get_neighbor(t, m.DOWN_RIGHT) is None
        assert m.get_neighbor(t, m.UP_LEFT).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.UP_RIGHT) is None
        t = m.get_neighbor(t, m.UP)
        assert (t.x, t.y) == (3, 1) and t.properties['meta'] == 'h'
        assert m.get_neighbor(t, m.DOWN).properties['meta'] == 'g'
        assert m.get_neighbor(t, m.UP) is None
        assert m.get_neighbor(t, m.DOWN_LEFT).properties['meta'] == 'f'
        assert m.get_neighbor(t, m.DOWN_RIGHT) is None
        assert m.get_neighbor(t, m.UP_LEFT) is None
        assert m.get_neighbor(t, m.UP_RIGHT) is None

    def test_hex_coords(self):
        # test hexagonal tile map
        # tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
        #   /d\ /h\
        # /b\_/f\_/
        # \_/c\_/g\
        # /a\_/e\_/
        # \_/ \_/ 
        m = gen_hex_map(hmd, 32)

        # test tile sides / corners
        t00 = m.get_cell(0, 0)
        assert t00.top == 32
        assert t00.bottom == 0
        assert t00.left == (0, 16)
        assert t00.right == (36, 16)
        assert t00.center == (18, 16)
        assert t00.topleft == (9, 32)
        assert t00.topright == (27, 32)
        assert t00.bottomleft == (9, 0)
        assert t00.bottomright == (27, 0)
        assert t00.midtop == (18, 32)
        assert t00.midbottom == (18, 0)
        assert t00.midtopleft == (4, 24)
        assert t00.midtopright == (31, 24)
        assert t00.midbottomleft == (4, 8)
        assert t00.midbottomright == (31, 8)

        t10 = m.get_cell(1, 0)
        assert t10.top == 48
        assert t10.bottom == 16
        assert t10.left == t00.topright
        assert t10.right == (63, 32)
        assert t10.center == (45, 32)
        assert t10.topleft == (36, 48)
        assert t10.topright == (54, 48)
        assert t10.bottomleft == t00.right
        assert t10.bottomright == (54, 16)
        assert t10.midtop == (45, 48)
        assert t10.midbottom == (45, 16)
        assert t10.midtopleft == (31, 40)
        assert t10.midtopright == (58, 40)
        assert t10.midbottomleft == t00.midtopright
        assert t10.midbottomright == (58, 24)

        t = m.get_cell(2, 0)
        assert t.top == 32
        assert t.bottom == 0
        assert t.left == t10.bottomright
        assert t.right == (90, 16)
        assert t.center == (72, 16)
        assert t.topleft == t10.right
        assert t.midtopleft == t10.midbottomright

    def test_hex_pixel(self):
        # test hexagonal tile map
        # tiles = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]
        #   /d\ /h\
        # /b\_/f\_/
        # \_/c\_/g\
        # /a\_/e\_/
        # \_/ \_/ 
        m = gen_hex_map(hmd, 32)
        t = m.get(0,0)
        assert t is None
        t = m.get(0,16)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(16,16)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(35,16)
        assert (t.x, t.y) == (0, 0) and t.properties['meta'] == 'a'
        t = m.get(36,16)
        assert (t.x, t.y) == (1, 0) and t.properties['meta'] == 'c'

    def test_hex_dimensions(self):
        m = gen_hex_map([[{'a':'a'}]], 32)
        assert m.pxw, m.pxh == (36, 32)
        m = gen_hex_map([[{'a':'a'}]*2], 32)
        assert m.pxw, m.pxh == (36, 64)
        m = gen_hex_map([[{'a':'a'}]]*2, 32)
        assert m.pxw, m.pxh == (63, 48)
Ejemplo n.º 27
0
class SpriteModelTest(unittest.TestCase):

    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 tearDown(self):
        self.w.close()

    def test_top(self):
        assert self.s.top == 20
        self.s.top = 10
        assert (self.s.x, self.s.y) == (10, 0)

    def test_bottom(self):
        assert self.s.bottom == 10
        self.s.bottom = 0
        assert (self.s.x, self.s.y) == (10, 0)

    def test_right(self):
        assert self.s.right == 20
        self.s.right = 10
        assert (self.s.x, self.s.y) == (0, 10)

    def test_left(self):
        assert self.s.left == 10
        self.s.left = 0
        assert (self.s.x, self.s.y) == (0, 10)

    def test_center(self):
        assert self.s.center == (15, 15)
        self.s.center = (5, 5)
        assert (self.s.x, self.s.y) == (0, 0)

    def test_midtop(self):
        assert self.s.midtop == (15, 20)
        self.s.midtop = (5, 5)
        assert (self.s.x, self.s.y) == (0, -5)

    def test_midbottom(self):
        assert self.s.midbottom == (15, 10)
        self.s.midbottom = (5, 5)
        assert (self.s.x, self.s.y) == (0, 5)

    def test_midleft(self):
        assert self.s.midleft == (10, 15)
        self.s.midleft = (5, 5)
        assert (self.s.x, self.s.y) == (5, 0)

    def test_midright(self):
        assert self.s.midright == (20, 15)
        self.s.midright = (5, 5)
        assert (self.s.x, self.s.y) == (-5, 0)

    def test_topleft(self):
        assert self.s.topleft == (10, 20)
        self.s.topleft = (5, 5)
        assert (self.s.x, self.s.y) == (5, -5)

    def test_topright(self):
        assert self.s.topright == (20, 20)
        self.s.topright = (5, 5)
        assert (self.s.x, self.s.y) == (-5, -5)

    def test_bottomright(self):
        assert self.s.bottomright == (20, 10)
        self.s.bottomright = (5, 5)
        assert (self.s.x, self.s.y) == (-5, 5)

    def test_bottomleft(self):
        assert self.s.bottomleft == (10, 10)
        self.s.bottomleft = (5, 5)
        assert (self.s.x, self.s.y) == (5, 5)

    unittest.main()
Ejemplo n.º 28
0
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()