コード例 #1
0
ファイル: windows.py プロジェクト: ff-/pineal
    def on_draw(self):
        self.clear()

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        (w, h) = self.get_size()
        gl.glScalef(
            float(min(w, h))/w,
            -float(min(w, h))/h,
            1
        )

        gl.gluPerspective(45.0, 1, 0.1, 1000.0)
        gl.gluLookAt(0, 0, 2.4,
                     0, 0, 0,
                     0, 1, 0)

        global render_texture
        render_texture = self.texture

        for v in self.visions.values():
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glLoadIdentity()
            v.iteration()

        buf = pyglet.image.get_buffer_manager().get_color_buffer()
        rawimage = buf.get_image_data()
        self.texture = rawimage.get_texture()

        clock.tick()
コード例 #2
0
ファイル: gameloop.py プロジェクト: tartley/sole-scion
    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()
コード例 #3
0
    def test_sprite(self):
        w = pyglet.window.Window(width=320, height=320)

        image = Image2d.load(ball_png)
        ball = Sprite(0, 0, 64, 64, image)
        view = FlatView(0, 0, 320, 320, sprites=[ball])

        w.push_handlers(view.camera)

        dx, dy = (10, 5)

        clock.set_fps_limit(30)
        while not w.has_exit:
            clock.tick()
            w.dispatch_events()

            # move, check bounds
            ball.x += dx; ball.y += dy
            if ball.left < 0: ball.left = 0; dx = -dx
            elif ball.right > w.width: ball.right = w.width; dx = -dx
            if ball.bottom < 0: ball.bottom = 0; dy = -dy
            elif ball.top > w.height: ball.top = w.height; dy = -dy

            # keep our focus in the middle of the window
            view.fx = w.width/2
            view.fy = w.height/2

            view.clear()
            view.draw()
            w.flip()

        w.close()
コード例 #4
0
ファイル: SPRITE_OVERLAP.py プロジェクト: odyaka341/pyglet
    def test_sprite(self):
        w = pyglet.window.Window(width=320, height=320)

        image = Image2d.load(ball_png)
        ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
        ball2 = BouncySprite(288, 0, 64, 64, image, properties=dict(dx=-10, dy=5))
        view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
        view.fx, view.fy = 160, 160

        clock.set_fps_limit(60)
        e = TintEffect((0.5, 1, 0.5, 1))
        while not w.has_exit:
            clock.tick()
            w.dispatch_events()

            ball1.update()
            ball2.update()
            if ball1.overlaps(ball2):
                if "overlap" not in ball2.properties:
                    ball2.properties["overlap"] = e
                    ball2.add_effect(e)
            elif "overlap" in ball2.properties:
                ball2.remove_effect(e)
                del ball2.properties["overlap"]

            view.clear()
            view.draw()
            w.flip()

        w.close()
コード例 #5
0
ファイル: gameFunc.py プロジェクト: axemaster1974/MegaJump2
def instructionScreen(windowSurface, WWIDTH, FRAMES, background_image, background_position):

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        windowSurface.blit(background_image, background_position)
        
        displayText(windowSurface, 128, WWIDTH / 2, 125, 'MEGA', RED)
        displayText(windowSurface, 128, WWIDTH / 2, 275, 'JUMP!', GREEN)
        displayText(windowSurface, 20, WWIDTH / 2, 400, 'Space to jump (+ down arrow for small jump, M for MegaJump)', GREEN)
        displayText(windowSurface, 20, WWIDTH / 2, 450, 'Left & Right arrows to move (+ up arrow to move faster)', GREEN)
        displayText(windowSurface, 20, WWIDTH / 2, 500, 'Q to quit, R to reset', GREEN)
        displayText(windowSurface, 20, WWIDTH / 2, 550, 'Only 1 MegaJump per game!', RED)
        displayText(windowSurface, 20, WWIDTH / 2, 600, 'Press ESC to return to main screen', GREEN)

        pygame.draw.circle(windowSurface, GOLD, (510, 550), 10, 0)

        if pygame.key.get_pressed()[K_ESCAPE]:
            return

        pygame.display.flip()

        clock.set_fps_limit(FRAMES)
        clock.tick()
コード例 #6
0
ファイル: FPS.py プロジェクト: DiscoBizzle/Ghost-Simulator
    def test_limit_fps(self):
        """
        Test that the clock effectively limits the
        frames per second to 60 Hz when set to.

        Because the fps are bounded, we expect a small error (1%)
        from the expected value.
        """
        ticks = 20
        fps_limit = 60
        expected_delta_time = ticks*1./fps_limit

        clock.set_fps_limit(fps_limit)

        t1 = time.time()
        # Initializes the timer state.
        clock.tick()
        for i in range(ticks):
            clock.tick()
        t2 = time.time()

        computed_time_delta = t2 - t1

        self.assertAlmostEqual(computed_time_delta,
                               expected_delta_time,
                               delta=0.01*expected_delta_time)
コード例 #7
0
ファイル: motion.py プロジェクト: alicen6/brain_assessor
def wait(ms):
	a = clock.get_fps()
	ct = 0
	loopcount = (ms / 1000.0) * a
	while ct < loopcount:
		clock.tick()
		ct+=1
コード例 #8
0
ファイル: grid.py プロジェクト: reuteran/game-of-life
 def main_loop(self):
     clock.set_fps_limit(self.update_fps)
     while not self.has_exit:
         self.dispatch_events()
         self.update_cells()
         self.draw_grid()
         clock.tick()
         self.flip()
コード例 #9
0
ファイル: FPS.py プロジェクト: njoubert/UndergraduateProjects
 def test_fps(self):
     clock.set_default(clock.Clock())
     self.assertTrue(clock.get_fps() == 0)
     for i in range(10):
         time.sleep(0.2)
         clock.tick()
     result = clock.get_fps()
     self.assertTrue(abs(result - 5.0) < 0.05)
コード例 #10
0
 def on_draw(self):
     self.clear() # clearing buffer
     clock.tick() # ticking the clock
     
     # showing FPS
     self.fpstext.text = "fps: %d" % clock.get_fps()
     self.fpstext.draw()
                
     # flipping
     self.flip()
コード例 #11
0
ファイル: TICK.py プロジェクト: DatRollingStone/nwidget
 def test_tick(self):
     clock.set_default(clock.Clock())
     result = clock.tick()
     self.assertTrue(result == 0)
     time.sleep(1)
     result_1 = clock.tick()
     time.sleep(1)
     result_2 = clock.tick()
     self.assertTrue(abs(result_1 - 1.0) < 0.05)
     self.assertTrue(abs(result_2 - 1.0) < 0.05)
コード例 #12
0
ファイル: FPS_LIMIT.py プロジェクト: DatRollingStone/nwidget
    def test_fps_limit(self):
        clock.set_default(clock.Clock())
        clock.set_fps_limit(20)
        self.assertTrue(clock.get_fps() == 0)

        t1 = time.time()
        clock.tick() # One to get it going
        for i in range(20):
            clock.tick()
        t2 = time.time()
        self.assertTrue(abs((t2 - t1) - 1.) < 0.05)
コード例 #13
0
ファイル: SCHEDULE.py プロジェクト: DatRollingStone/nwidget
    def test_schedule_multiple(self):
        clock.set_default(clock.Clock())
        clock.schedule(self.callback)
        clock.schedule(self.callback)
        self.callback_count = 0

        clock.tick()
        self.assertTrue(self.callback_count == 2)

        clock.tick()
        self.assertTrue(self.callback_count == 4)
コード例 #14
0
ファイル: SCHEDULE.py プロジェクト: DatRollingStone/nwidget
    def test_unschedule(self):
        clock.set_default(clock.Clock())
        clock.schedule(self.callback)

        result = clock.tick()
        self.assertTrue(result == self.callback_dt)
        self.callback_dt = None
        time.sleep(1)
        clock.unschedule(self.callback)

        result = clock.tick()
        self.assertTrue(self.callback_dt == None)
コード例 #15
0
ファイル: track00.py プロジェクト: Knio/miru
def main():
    global target, step
    while not w.has_exit:
        clock.tick()
        w.clear()
        
        target.pos.x += step
        if abs(target.pos.x) >= 17:
            step *= -1
        w.dispatch_events()
        context.render()
        w.flip()
コード例 #16
0
ファイル: gameFunc.py プロジェクト: axemaster1974/MegaJump2
def savedGameScreen(savedGames, windowSurface, WWIDTH, WHEIGHT, FRAMES, background_image, background_position):        

    time.sleep(0.3)
    
    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        windowSurface.blit(background_image, background_position)
        displayTextLJ(windowSurface, 36, 50, 50, 'Saved Games List', RED)
        displayTextLJ(windowSurface, 24, 50, 100, "Name", RED)
        displayTextLJ(windowSurface, 24, 200, 100, "Difficulty", RED)
        displayTextLJ(windowSurface, 24, 350, 100, "Platforms", RED)
        displayTextLJ(windowSurface, 24, 500, 100, "Record", RED)
        
        displayTextLJ(windowSurface, 20, 50, 550, 'Press number to select game or D plus number to delete game', RED)
        displayTextLJ(windowSurface, 20, 50, 600, 'Escape to return to previous screen', RED)
        
        count = 1
        for game in savedGames:
            displayTextLJ(windowSurface, 20, 50, 100 + (count * 30), str(count) + ". " + game['name'], GREEN)
            displayTextLJ(windowSurface, 20, 200, 100 + (count * 30), game['difficulty'], GREEN)
            displayTextLJ(windowSurface, 20, 350, 100 + (count * 30), game['pnumber'], GREEN)
            if game['difficulty'] == "INSANE":
                displayTextLJ(windowSurface, 20, 500, 100 + (count * 30), "Score: " + game['score'], GREEN)
            else:
                displayTime(windowSurface, int(game['record']), 500, 100 + (count * 30), GREEN, 20, "True")
            count += 1

        if not pygame.key.get_pressed()[ord('d')]:
            for i in range(len(savedGames)):
                if pygame.key.get_pressed()[ord(str(i+1))]:
                    return savedGames[i], i

        if pygame.key.get_pressed()[ord('d')]:
            for i in range(len(savedGames)):
                if pygame.key.get_pressed()[ord(str(i+1))]:
                     del savedGames[i]
                     saveGames(windowSurface, WWIDTH, WHEIGHT, None, savedGames, None, "Delete")
                     time.sleep(0.5)
                     break
                       
        if pygame.key.get_pressed()[K_ESCAPE]:
            return None, None

        pygame.display.flip()

        clock.set_fps_limit(FRAMES)
        clock.tick()
コード例 #17
0
ファイル: tartley.py プロジェクト: bjmgeek/babytux
    def mainLoop(self):
        while not self.win.has_exit:
            self.win.dispatch_events()

            self.world.tick()

            self.camera.worldProjection()
            self.world.draw()

            self.camera.hudProjection()
            self.hud.draw()

            clock.tick()
            self.win.flip()
コード例 #18
0
 def on_draw(self):
     self.clear() # clearing buffer
     clock.tick() # ticking the clock
     
     # showing FPS
     self.fpstext.text = "fps: %d" % clock.get_fps()
     self.fpstext.draw()
     
     self.spaceship.draw()
     for alien in self.aliens:
         alien.draw()
     
     # flipping
     self.flip()
コード例 #19
0
ファイル: fowl.py プロジェクト: jseutter/featherwars
 def main_loop(self):
     clock.set_fps_limit(30)
     clock.schedule_interval(self.animate_bird, 0.01)
     
     while not self.has_exit:
         self.dispatch_events()
         self.clear()
     
         self.update()
         self.draw()
     
         #Tick the clock
         clock.tick()
         self.flip()
コード例 #20
0
 def run_test(self):
     clock.set_fps_limit(30)
     while not self.w.has_exit:
         clock.tick()
         self.w.dispatch_events()
         self.view.fx += (self.keyboard[key.RIGHT] - self.keyboard[key.LEFT]) * 5
         self.view.fy += (self.keyboard[key.UP] - self.keyboard[key.DOWN]) * 5
         if self.marker is not None:
             self.marker.x = self.view.fx
             self.marker.y = self.view.fy
         self.view.clear()
         self.view.draw()
         self.w.flip()
     self.w.close()
コード例 #21
0
    def main_loop(self):
        ft = font.load('Arial', 28)
        fps_text = font.Text(ft, y=10)

        while not self.has_exit:
            self.dispatch_events()

            self.update()
            self.draw()

            clock.tick()
            fps_text.text = "fps: %d" % clock.get_fps()
            fps_text.draw()

            self.flip()
コード例 #22
0
ファイル: game.py プロジェクト: safetydank/astar-strategy
    def loop(self):
        try:
            clock.tick()

            while not self.has_exit:
                self.dispatch_events()
                dt = clock.tick()
                self.game.update(dt)
                self.draw()
                self.flip()

        except Exception, e:
            print "Error", e
            traceback.print_exc()
            self.close()
コード例 #23
0
ファイル: apygm.py プロジェクト: mhangman/Oyun-APyGM
		def mainLoop(self):
				
				ft = font.load('Arial', 28)
				fps_text = font.Text(ft, y=10)
				
				while not self.has_exit:
						self.dispatch_events()
						self.clear
						
						clock.tick()
						
						fps_text = ("fps: %d") % (clock.get_fps())
						fps_text.draw()
						
						self.flip()
コード例 #24
0
ファイル: DeckBuilder.py プロジェクト: mcgillij/REZD
 def main_loop(self):
     self.batch = pyglet.graphics.Batch()
     self.register_event_type('on_update')
     pyglet.clock.schedule(self.update_kytten)
     self.fps = pyglet.clock.ClockDisplay()
     self.generateMenu()
     while not self.has_exit: # main loop
         #self.push_handlers(self.on_mouse_release)
         self.clear()
         clock.tick()
         self.dispatch_events()
         self.batch.draw()
         self.drawSelectedCard()
         self.drawNewDeckList()
         self.fps.draw()
         self.flip() #flip to the other opengl buffer
コード例 #25
0
ファイル: mower.py プロジェクト: pdevine/suburbia
def main():
    clock.schedule(rabbyt.add_time)

    window.game_window = Window(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
    rabbyt.set_default_attribs()

    mower = Mower()
    bubble = RPMBubble()
    guage = Guage(mower)

    objs = [mower, guage, bubble]
    magicEventRegister(window.game_window, events, objs)

    while not window.game_window.has_exit:
        tick = clock.tick()
        window.game_window.dispatch_events()

        for obj in objs:
            obj.update(tick)
        
        events.ConsumeEventQueue()

        rabbyt.clear((1, 1, 1))

        guage.draw()
        mower.draw()
        bubble.draw()

        window.game_window.flip()
コード例 #26
0
ファイル: animation.py プロジェクト: avuserow/yoyobrawlah
def main():
    win = pyglet.window.Window( width=800, height=600 )

    anims = []

    @win.event
    def on_key_press(symbol, modifiers):
        #print 'Flipping', anims
        for anim in anims:
            anim.flip()

    anims.append( Anim('subWalkNorm', 5) )
    anims.append( BeerThrowAnim() )

    while not win.has_exit:
        done = False
        clock.set_fps_limit(FRAMES_PER_SECOND)

        while not done:
            timeChange = clock.tick()

            win.dispatch_events()
            for anim in anims:
                anim.update( timeChange )

            win.clear()
            if done or win.has_exit:
                break

            for anim in anims:
                anim.draw()

            win.flip()
コード例 #27
0
ファイル: garbage.py プロジェクト: pdevine/suburbia
def main():
    global win
    clock.schedule(rabbyt.add_time)

    win = pyglet.window.Window(width=leaves.SCREEN_WIDTH, height=leaves.SCREEN_HEIGHT)
    window.set_window(win)
    rabbyt.set_default_attribs()

    garbage = GarbageCan()

    leafs = leaves.LeafGroup()
    leafs += [leaves.Leaf(), leaves.Leaf(), leaves.Leaf() ]
    for i in range(len(leafs)):
        leafs[i].logicalX = 260 + i*80
        leafs[i].logicalY = 100 + i*60
        leafs[i].logicalZ = 10

    while not win.has_exit:
        tick = clock.tick()
        win.dispatch_events()

        leafs.update(tick)
        garbage.update(tick)
        
        events.ConsumeEventQueue()

        rabbyt.clear((1, 1, 1))

        leafs.draw()
        garbage.draw()

        win.flip()
コード例 #28
0
ファイル: experiment.py プロジェクト: psederberg/smile
    def run(self, initial_state=None):
        """
        Run the experiment.
        """

        # first clear and do a flip
        # glClear(GL_COLOR_BUFFER_BIT)
        self.window.on_draw(force=True)
        self.blocking_flip()

        # start the first state (that's this experiment)
        self.enter()

        # process events until done
        self._last_time = now()
        while not self.done and not self.window.has_exit:
            # record the time range
            self._new_time = now()
            time_err = (self._new_time - self._last_time) / 2.0
            self.event_time = event_time(self._last_time + time_err, time_err)

            # process the events that occurred in that range
            self.window.dispatch_events()

            # handle all scheduled callbacks
            dt = clock.tick(poll=True)

            # put in sleeps if necessary
            if dt < 0.0001:
                # do a usleep for half a ms (might need to tweak)
                self.clock.sleep(500)

            # save the time
            self._last_time = self._new_time
コード例 #29
0
ファイル: sky.py プロジェクト: pdevine/suburbia
def main():
    global fps_display

    win = Window(width=800, height=600)

    clock.schedule(rabbyt.add_time)

    rabbyt.set_default_attribs()

    bg = Background()

    fps_display = clock.ClockDisplay()

    while not win.has_exit:
        tick = clock.tick()
        win.dispatch_events()

        bg.update(tick)

        rabbyt.clear((bg.color))

        bg.draw()
        fps_display.draw()

        win.flip()
コード例 #30
0
ファイル: gutter.py プロジェクト: pdevine/suburbia
def main():
    global win
    clock.schedule(rabbyt.add_time)

    win = Window(width=800, height=600)
    rabbyt.set_default_attribs()

    lawn = Lawn()
    wind = Wind()

    magicEventRegister(win, events, list(lawn))

    while not win.has_exit:
        tick = clock.tick()
        win.dispatch_events()

        lawn.update(tick)
        wind.update(tick)
        events.ConsumeEventQueue()

        rabbyt.clear((1, 1, 1))

        lawn.draw()

        win.flip()
コード例 #31
0
def savedGameScreen(savedGames, windowSurface, WWIDTH, WHEIGHT, FRAMES,
                    background_image, background_position):

    time.sleep(0.3)

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        windowSurface.blit(background_image, background_position)
        displayTextLJ(windowSurface, 36, 50, 50, 'Saved Games List', RED)
        displayTextLJ(windowSurface, 24, 50, 100, "Name", RED)
        displayTextLJ(windowSurface, 24, 200, 100, "Difficulty", RED)
        displayTextLJ(windowSurface, 24, 350, 100, "Platforms", RED)
        displayTextLJ(windowSurface, 24, 500, 100, "Record", RED)

        displayTextLJ(
            windowSurface, 20, 50, 550,
            'Press number to select game or D plus number to delete game', RED)
        displayTextLJ(windowSurface, 20, 50, 600,
                      'Escape to return to previous screen', RED)

        count = 1
        for game in savedGames:
            displayTextLJ(windowSurface, 20, 50, 100 + (count * 30),
                          str(count) + ". " + game['name'], GREEN)
            displayTextLJ(windowSurface, 20, 200, 100 + (count * 30),
                          game['difficulty'], GREEN)
            displayTextLJ(windowSurface, 20, 350, 100 + (count * 30),
                          game['pnumber'], GREEN)
            if game['difficulty'] == "INSANE":
                displayTextLJ(windowSurface, 20, 500, 100 + (count * 30),
                              "Score: " + game['score'], GREEN)
            else:
                displayTime(windowSurface, int(game['record']), 500,
                            100 + (count * 30), GREEN, 20, "True")
            count += 1

        if not pygame.key.get_pressed()[ord('d')]:
            for i in range(len(savedGames)):
                if pygame.key.get_pressed()[ord(str(i + 1))]:
                    return savedGames[i], i

        if pygame.key.get_pressed()[ord('d')]:
            for i in range(len(savedGames)):
                if pygame.key.get_pressed()[ord(str(i + 1))]:
                    del savedGames[i]
                    saveGames(windowSurface, WWIDTH, WHEIGHT, None, savedGames,
                              None, "Delete")
                    time.sleep(0.5)
                    break

        if pygame.key.get_pressed()[K_ESCAPE]:
            return None, None

        pygame.display.flip()

        clock.set_fps_limit(FRAMES)
        clock.tick()
コード例 #32
0
ファイル: play_human_record.py プロジェクト: simula/toadstool
def play_human_record(callback=None):
    """
    Play the environment using keyboard as a human.

    Returns:
        None

    """
    # Start on the first world
    first_world = 'SuperMarioBros-1-1-v0'
    env = gym_super_mario_bros.make(first_world)

    observations = []  #For Storing observations

    # set the frame rate for pyglet
    clock.set_fps_limit(env.metadata['video.frames_per_second'])
    # ensure the observation space is a box of pixels
    assert isinstance(env.observation_space, gym.spaces.box.Box)
    # ensure the observation space is either B&W pixels or RGB Pixels
    obs_s = env.observation_space
    is_bw = len(obs_s.shape) == 2
    is_rgb = len(obs_s.shape) == 3 and obs_s.shape[2] in [1, 3]
    assert is_bw or is_rgb
    # get the mapping of keyboard keys to actions in the environment
    if hasattr(env, 'get_keys_to_action'):
        keys_to_action = env.get_keys_to_action()
    elif hasattr(env.unwrapped, 'get_keys_to_action'):
        keys_to_action = env.unwrapped.get_keys_to_action()
    else:
        raise ValueError('env has no get_keys_to_action method')

    # create the image viewer
    from tkinter import Tk
    root = Tk()

    # Determining screen size
    height = root.winfo_screenheight()
    width = int(((height / 240) * 256))

    viewer = ImageViewer(
        env.spec.id if env.spec is not None else env.__class__.__name__,

        #env.observation_space.shape[0], # height
        #env.observation_space.shape[1], # width
        height,
        width,
        monitor_keyboard=True,
        relevant_keys=set(sum(map(list, keys_to_action.keys()), [])))
    # create a done flag for the environment
    done = False
    state = env.reset()
    viewer.show(env.unwrapped.screen)

    # for keeping score
    score = 0
    level_score = 1000
    death_score = -100
    cur_level_score = level_score
    min_score = 200

    # start the main game loop
    finish = False
    start = None
    try:
        world = 1
        stage = 1
        stage_num = 0
        steps = 0
        start = time.time()  # timestamp for start of game

        while True:
            # clock tick
            clock.tick()

            # reset if the environment is done
            if done:
                done = False

                if cur_level_score > min_score:
                    cur_level_score += death_score

                # Go to new stage if flag/axe reached or time-limit is up
                if finish or steps >= time_limit:
                    if finish:
                        score += cur_level_score
                    cur_level_score = level_score

                    stage_num += 1
                    world, stage, new_world = stages.make_next_stage(
                        world, stage, stage_num)
                    env.close()
                    env = gym_super_mario_bros.make(new_world)
                    finish = False
                    steps = 0

                state = env.reset()
                viewer.show(env.unwrapped.screen)

            # unwrap the action based on pressed relevant keys
            action = keys_to_action.get(viewer.pressed_keys, _NOP)
            next_state, reward, done, info = env.step(action)
            steps += 1

            if info['flag_get']:
                finish = True

            # Adding observation to list
            observations.append(action)

            viewer.show(env.unwrapped.screen)
            # pass the observation data through the callback
            if callback is not None:
                callback(state, action, reward, done, next_state)
            state = next_state
            # shutdown if the escape key is pressed
            if viewer.is_escape_pressed:
                break
            # shutdown if playtime is up
            now = time.time()
            if now - start > play_time:
                break

    except KeyboardInterrupt:
        pass

    end = time.time()
    #Storing the data
    data = {}
    data['obs'] = observations
    data['obs_n'] = len(observations)
    data['start_time'] = start
    data['stop_time'] = end
    data['score'] = score

    folder_path = './DATA/sessions/'

    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    path, dirs, files = next(os.walk(folder_path))
    file_count = len(files)

    file_path = folder_path + 'session' + str(file_count)

    print('Saving observations to file')
    with open(file_path, 'w') as outfile:
        json.dump(data, outfile)

    viewer.close()
    env.close()
コード例 #33
0
ファイル: run_tests.py プロジェクト: pyzh/pyglet
def run(xml_file):
    gui = GUI(window)
    loadxml.fromFile(gui, xml_file)
    if '--dump' in sys.argv:
        print('-' * 75)
        gui.dump()
        print('-' * 75)

    window.push_handlers(gui)

    gui.push_handlers(dragndrop.DragHandler('.draggable'))

    @gui.select('#press-me')
    def on_click(widget, *args):
        print('on_click', widget)
        return event.EVENT_HANDLED

    @gui.select('#enable-other')
    def on_click(widget, *args):
        w = gui.get('#press-me')
        w.setEnabled(not w.isEnabled())
        return event.EVENT_HANDLED

    @gui.select('button, text-button')
    def on_click(widget, *args):
        print('DEBUG', widget, 'PRESSED')
        return event.EVENT_UNHANDLED

    @gui.select('.show-value')
    def on_change(widget, value):
        print('DEBUG', widget, 'VALUE CHANGED', repr(value))
        return event.EVENT_UNHANDLED

    @gui.select('frame#menu-test', 'on_click')
    def on_menu(w, x, y, button, modifiers, click_count):
        if not widgets.PopupMenu.isActivatingClick(button, modifiers):
            return event.EVENT_UNHANDLED
        gui.get('#test-menu').expose((x, y))
        return event.EVENT_HANDLED

    @gui.select('.hover')
    def on_element_enter(widget, *args):
        print('ENTER ELEMENT', widget.id)
        return event.EVENT_HANDLED

    @gui.select('.hover')
    def on_element_leave(widget, *args):
        print('LEAVE ELEMENT', widget.id)
        return event.EVENT_HANDLED

    @gui.select('.drawer-control')
    def on_click(widget, *args):
        id = widget.id.replace('drawer-control', 'test-drawer')
        gui.get('#' + id).toggle_state()
        return event.EVENT_HANDLED

    @gui.select('#question-dialog-test')
    def on_click(widget, *args):
        def f(*args):
            print('DIALOG SAYS', args)

        dialogs.Question(widget.getGUI(), 'Did this appear correctly?',
                         callback=f).run()
        return event.EVENT_HANDLED

    @gui.select('#message-dialog-test')
    def on_click(widget, *args):
        def f(*args):
            print('DIALOG SAYS', args)

        dialogs.Message(widget.getGUI(), 'Hello, World!', callback=f).run()
        return event.EVENT_HANDLED

    @gui.select('#music-test')
    def on_click(widget, x, y, button, modifiers, click_count):
        if not button & mouse.RIGHT:
            return event.EVENT_UNHANDLED

        def load_music(file=None):
            if not file:
                return
            gui.get('#music-test').delete()
            m = widgets.Music(gui, file, id='music-test', playing=True)
            m.gainFocus()

        dialogs.FileOpen(gui, callback=load_music).run()
        return event.EVENT_HANDLED

    @gui.select('#movie-test')
    def on_click(widget, x, y, button, modifiers, click_count):
        if not button & mouse.RIGHT:
            return event.EVENT_UNHANDLED

        def load_movie(file=None):
            print('DIALOG SELECTION:', file)
            if not file:
                return
            gui.get('#movie-test').delete()
            m = widgets.Movie(gui, file, id='movie-test', playing=True)
            m.gainFocus()

        dialogs.FileOpen(gui, callback=load_movie).run()
        return event.EVENT_HANDLED

    @gui.select('#movie-test')
    def on_text(widget, text):
        if text == 'f':
            gui.get('#movie-test').video.pause()
            anim.Delayed(gui.get('#movie-test').video.play, duration=10)
            window.set_fullscreen()
        return event.EVENT_HANDLED

    @gui.select('.droppable')
    def on_drop(widget, x, y, button, modifiers, element):
        element.reparent(widget)
        widget.bgcolor = (1, 1, 1, 1)
        return event.EVENT_HANDLED

    @gui.select('.droppable')
    def on_drag_enter(widget, x, y, element):
        widget.bgcolor = (.8, 1, .8, 1)
        return event.EVENT_HANDLED

    @gui.select('.droppable')
    def on_drag_leave(widget, x, y, element):
        widget.bgcolor = (1, 1, 1, 1)
        return event.EVENT_HANDLED

    try:
        sample = gui.get('#xhtml-sample')
    except KeyError:
        sample = None
    if sample:
        @layout.select('#click-me')
        def on_mouse_press(element, x, y, button, modifiers):
            print('CLICK ON', element)
            return event.EVENT_HANDLED

        sample.label.push_handlers(on_mouse_press)

    if gui.has('.progress-me'):
        class Progress:
            progress = 0
            direction = 1

            def animate(self, dt):
                self.progress += dt * self.direction
                if self.progress > 5:
                    self.progress = 5
                    self.direction = -1
                elif self.progress < 0:
                    self.progress = 0
                    self.direction = 1
                for e in gui.get('.progress-me'):
                    e.value = self.progress / 5.

        animate_progress = Progress().animate
        clock.schedule(animate_progress)

    my_escape.has_exit = False
    while not (window.has_exit or my_escape.has_exit):
        clock.tick()
        window.dispatch_events()
        media.dispatch_events()

        glClearColor(.2, .2, .2, 1)
        glClear(GL_COLOR_BUFFER_BIT)
        gui.draw()
        fps.draw()
        window.flip()
        if '--once' in sys.argv:
            window.close()
            sys.exit()

    if '--dump' in sys.argv:
        print('-' * 75)
        gui.dump()
        print('-' * 75)

    if gui.has('.progress-me'):
        clock.unschedule(animate_progress)

    # reset everything
    window.pop_handlers()
    gui.delete()
    window.set_size(800, 600)

    return window.has_exit
コード例 #34
0
ファイル: experiment.py プロジェクト: eweich/smile
    def run(self):
        """
        Run the experiment.
        """
        # create the window
        if self.fullscreen:
            self.window = ExpWindow(self,
                                    fullscreen=True,
                                    caption=self.name,
                                    vsync=self.pyglet_vsync,
                                    screen=self.screen)
        else:
            self.window = ExpWindow(self,
                                    *(self.resolution),
                                    fullscreen=self.fullscreen,
                                    caption=self.name,
                                    vsync=self.pyglet_vsync,
                                    screen=self.screen)

        # set the clear color
        self.window.set_clear_color(self._background_color)

        # set the mouse as desired
        #self.window.set_exclusive_mouse()
        self.window.set_mouse_visible(False)

        # some gl stuff (must look up to remember why we want them)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        # get flip interval
        self.flip_interval = self._calc_flip_interval()
        print "Monitor Flip Interval is %f (%f Hz)" % (self.flip_interval,
                                                       1. / self.flip_interval)

        # first clear and do a flip
        #glClear(GL_COLOR_BUFFER_BIT)
        self.window.on_draw(force=True)
        self.blocking_flip()

        # start the first state (that's this experiment)
        self.enter()

        # process events until done
        self._last_time = now()
        while not self.done and not self.window.has_exit:
            # record the time range
            self._new_time = now()
            time_err = (self._new_time - self._last_time) / 2.
            self.event_time = event_time(self._last_time + time_err, time_err)

            # process the events that occurred in that range
            self.window.dispatch_events()

            # handle all scheduled callbacks
            dt = clock.tick(poll=True)

            # put in sleeps if necessary
            if dt < .0001:
                # do a usleep for 1/4 of a ms (might need to tweak)
                self.clock.sleep(250)

            # save the time
            self._last_time = self._new_time

        # write out csv logs if desired
        if not self.nocsv:
            self.state_log_stream.flush()
            yaml2csv(self.state_log,
                     os.path.splitext(self.state_log)[0] + '.csv')
            self.exp_log_stream.flush()
            yaml2csv(self.exp_log, os.path.splitext(self.exp_log)[0] + '.csv')

        # close the window and clean up
        self.window.close()
        self.window = None
コード例 #35
0
    def run(self):
        global _activeLevel
        global soundtrack
        _activeLevel = self
        self.done = False
        clock.set_fps_limit(60)
        win = window.window

        avSprite = AvatarSprite(self.avatar)
        self.avatar.feetPos = self.startLoc
        self.avatar.walkMask = self.walkMask
        self.avatar.triggerZones = self.triggerZones

        events.Fire('AvatarBirth', self.avatar)
        events.Fire('LevelStartedEvent', self)

        while not self.done:
            timeChange = clock.tick()

            #if soundtrack and self.sound:
            #    print soundtrack
            #    soundtrack.dispatch_events()

            events.ConsumeEventQueue()
            win.dispatch_events()

            if self.deathDelay:
                self.deathDelay -= timeChange
                if self.deathDelay <= 0:
                    self.done = True

            if self.done or win.has_exit:
                player.strings = self.avatar.strings[:]
                events.Reset()
                break

            avSprite.update(timeChange)
            for miscSprite in self.miscSprites:
                miscSprite.update(timeChange)
            for enemySprite in self.enemySprites.values():
                enemySprite.update(timeChange)
            for sprite in self.visualEffects.sprites:
                sprite.update(timeChange)

            win.clear()

            # find the combined height of the background images

            bgWidth = 0
            bgHeight = 0

            for bg in self.bgImages:
                bgWidth += bg.width
                bgHeight += bg.height

            offset = self.calcBGOffset(self.avatar.x, self.avatar.y, win.width,
                                       win.height, bgWidth, bgHeight)

            window.bgOffset[0] = offset[0]
            window.bgOffset[1] = offset[1]

            #self.bg.blit(*window.bgOffset)
            #[bg.blit(*window.bgOffset) for bg in self.bgImages]

            for count, bg in enumerate(self.bgImages):
                bg.blit(count * 1024 + window.bgOffset[0], window.bgOffset[1])

            for miscSprite in self.miscSprites:
                miscSprite.draw()
            avSprite.draw()

            for enemySprite in self.enemySprites.values():
                enemySprite.draw()
            for sprite in self.visualEffects.sprites:
                sprite.draw()

            #self.healthText.draw()
            self.healthBar.draw(self.avatar)
            self.energyBar.draw(self.avatar)

            if DEBUG:
                self.fpsText.text = "fps: %d" % clock.get_fps()
                self.fpsText.draw()

            if clock.get_fps() < 30:
                events.Fire('LowFPS30')

            win.flip()

        return self.getNextScene()
コード例 #36
0
    blood = []

    def splatter(direction):
        for drop in range(0, randint(15, 20)):
            blood.append(
                Blood(
                    euclid.Vector2(200, 200), direction +
                    euclid.Vector2(randint(-2, 2), randint(-2, 2))))

    @win.event
    def on_key_press(symbol, modifiers):
        if symbol == window.key.RIGHT:
            splatter(Blood.right)
        elif symbol == window.key.LEFT:
            splatter(Blood.left)

    while not win.has_exit:
        win.dispatch_events()
        tick = clock.tick()

        for drop in blood:
            drop.update(tick)
            if drop.lifetime < 0:
                blood.remove(drop)

        win.clear()

        [drop.draw() for drop in blood]

        win.flip()
コード例 #37
0
ファイル: los.py プロジェクト: pyzh/pyglet
sprites = list()
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()
コード例 #38
0
def step_events():
    win.dispatch_events()
    media.dispatch_events()
    clock.tick()
コード例 #39
0
ファイル: main.py プロジェクト: MWilliams15/AI4G
    # create a pyglet window and set glOptions
    win = window.Window(width=500, height=500, vsync=False, 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_resize)

    # create a world for agents
    world = World(500, 500)
    # add one agent
    world.target = Target(world, 10, 10)
    world.shooter = Shooter(world, 10, 0.01)
    # unpause the world ready for movement
    world.paused = False

    while not win.has_exit:
        win.dispatch_events()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        # show nice FPS bottom right (default)
        delta = clock.tick()
        world.update(delta)
        world.render()
        fps_display.draw()
        # swap the double buffer
        win.flip()
コード例 #40
0
ファイル: tree_test.py プロジェクト: thabotr/pyglet
w1 = Window(width=300, height=300)
w1.switch_to()
setup_scene()
tree1 = Tree(n=10, r=True)
w1.push_handlers(tree1)

w2 = Window(width=300, height=300)
w2.switch_to()
setup_scene()
tree2 = Tree(n=10, r=False)
w2.push_handlers(tree2)

n = 0
clock.set_fps_limit(30)
while not (w1.has_exit or w2.has_exit):
    clock.tick()
    n += 1

    # draw
    w1.switch_to()
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    w1.dispatch_events()
    tree1.draw()
    w1.flip()

    w2.switch_to()
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    w2.dispatch_events()
    tree2.draw()
    w2.flip()
コード例 #41
0
def play(game='SonicTheHedgehog-Genesis', state='GreenHillZone.Act1', scenario='scenario', frame_jump=1):
	'''
	:param game: game to load
	:param state: level to load
	:param scenario: scenario to load
	:return:
	'''

	print('\n\tBACKSPACE : reset the level'
		  '\n\tECHAP : End')

	jump = 0
	env = retro.make(game=game, state=state, use_restricted_actions=retro.ACTIONS_ALL, scenario=scenario)
	obs = env.reset()

	win_width = 900
	screen_height, screen_width = obs.shape[:2]
	win_height = win_width * screen_height // screen_width
	win = pyglet.window.Window(width=win_width, height=win_height, vsync=False)

	key_handler = pyglet.window.key.KeyStateHandler()
	win.push_handlers(key_handler)

	key_previous_states = {}

	pyglet.app.platform_event_loop.start()

	fps_display = pyglet.clock.ClockDisplay()
	clock.set_fps_limit(60)

	glEnable(GL_TEXTURE_2D)
	texture_id = GLuint(0)
	glGenTextures(1, ctypes.byref(texture_id))
	glBindTexture(GL_TEXTURE_2D, texture_id)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, screen_width, screen_height, 0, GL_RGB, GL_UNSIGNED_BYTE, None)

	total_reward = 0.0
	while not win.has_exit:
		win.dispatch_events()

		win.clear()

		keys_clicked = set()
		keys_pressed = set()
		for key_code, pressed in key_handler.items():
			if pressed:
				keys_pressed.add(key_code)

			if not key_previous_states.get(key_code, False) and pressed:
				keys_clicked.add(key_code)
			key_previous_states[key_code] = pressed

		buttons_pressed = set()

		# End of the session
		if keycodes.ESCAPE in keys_pressed:
			pyglet.app.platform_event_loop.stop()
			return

		# Reset of the level and the recorded images and actions
		elif keycodes.BACKSPACE in keys_pressed:
			print('reset level')
			env.reset()

		inputs = {
			'A': keycodes.Z in keys_pressed or ButtonCodes.A in buttons_pressed,
			'B': keycodes.A in keys_pressed or ButtonCodes.B in buttons_pressed,
			'C': keycodes.E in keys_pressed,
			'X': keycodes.Q in keys_pressed or ButtonCodes.X in buttons_pressed,
			'Y': keycodes.S in keys_pressed or ButtonCodes.Y in buttons_pressed,
			'Z': keycodes.D in keys_pressed,

			'UP': keycodes.UP in keys_pressed or ButtonCodes.D_UP in buttons_pressed,
			'DOWN': keycodes.DOWN in keys_pressed or ButtonCodes.D_DOWN in buttons_pressed,
			'LEFT': keycodes.LEFT in keys_pressed or ButtonCodes.D_LEFT in buttons_pressed,
			'RIGHT': keycodes.RIGHT in keys_pressed or ButtonCodes.D_RIGHT in buttons_pressed,

			'MODE': keycodes.TAB in keys_pressed or ButtonCodes.SELECT in buttons_pressed,
			'START': keycodes.ENTER in keys_pressed or ButtonCodes.START in buttons_pressed,
		}

		if jump == 0:
			action = [inputs[b] for b in env.BUTTONS]
			last_action = action
			obs, rew, done, info = env.step(action)
			jump = frame_jump
		else:
			obs, rew, done, info = env.step(last_action)
		total_reward += rew
		print(total_reward)
		print(rew)
		jump -= 1

		glBindTexture(GL_TEXTURE_2D, texture_id)
		video_buffer = ctypes.cast(obs.tobytes(), ctypes.POINTER(ctypes.c_short))
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, obs.shape[1], obs.shape[0], GL_RGB, GL_UNSIGNED_BYTE, video_buffer)

		x = 0
		y = 0
		h = win.height
		w = win.width

		pyglet.graphics.draw(4,
							 pyglet.gl.GL_QUADS,
							 ('v2f', [x, y, x + w, y, x + w, y + h, x, y + h]),
							 ('t2f', [0, 1, 1, 1, 1, 0, 0, 0]),
							 )

		fps_display.draw()

		win.flip()

		timeout = clock.get_sleep_time(False)
		pyglet.app.platform_event_loop.step(timeout)

		clock.tick()

	pyglet.app.platform_event_loop.stop()
コード例 #42
0
def main():
    w = window.Window(vsync=False, resizable=True)
    w.set_mouse_cursor(w.get_system_mouse_cursor('text'))

    @w.event
    def on_key_press(symbol, modifiers):
        if sys.platform == 'darwin':
            accel = key.MOD_COMMAND
        else:
            accel = key.MOD_CTRL

        if modifiers & accel:
            if symbol == key.B:
                toggle_style('bold')
            elif symbol == key.I:
                toggle_style('italic')
            elif symbol in (key.EQUAL, key.NUM_ADD):
                add_font_size(2)
            elif symbol in (key.MINUS, key.NUM_SUBTRACT):
                add_font_size(-2)

        if symbol == key.ESCAPE:
            w.has_exit = True

    def toggle_style(attribute):
        old = caret.get_style(attribute)
        if old == style.INDETERMINATE:
            value = True
        else:
            value = not old
        caret.set_style({attribute: value})

    def add_font_size(size):
        old_size = caret.get_style('font_size')
        if old_size in (style.INDETERMINATE, None):
            old_size = 12
        caret.set_style({'font_size': old_size + size})

    def on_resize(width, height):
        text.x = border
        text.y = height - border
        text.width = width - border * 2
        text.height = height - border * 2
        caret._update()

    w.push_handlers(on_resize)

    if len(sys.argv) > 1:
        content = open(sys.argv[1]).read()
    else:
        content = resource.file('info.att').read()

    # Draw to this border so we can test clipping.
    border = 50

    batch = graphics.Batch()
    doc = attributed(content)
    text = layout.IncrementalTextLayout(doc,
                                        w.width - border * 2,
                                        w.height - border * 2,
                                        multiline=True,
                                        batch=batch)
    caret = caret_module.Caret(text)
    caret.color = (0, 0, 0)
    caret.visible = True
    caret.position = 0
    w.push_handlers(caret)

    fps = clock.ClockDisplay(font=font.load('', 10, dpi=96),
                             color=(0, 0, 0, 1),
                             interval=1.,
                             format='FPS: %(fps)d')
    fps.label.x = 2
    fps.label.y = 15
    stats_text = font.Text(font.load('', 10, dpi=96),
                           '',
                           x=2,
                           y=2,
                           color=(0, 0, 0, 1))

    def update_stats(dt):
        states = list(batch.state_map.values())
        usage = 0.
        blocks = 0
        domains = 0

        fragmentation = 0.
        free_space = 0.
        capacity = 0.

        for state in states:
            for domain in list(state.values()):
                domains += 1
                free_space += domain.allocator.get_free_size()
                fragmentation += domain.allocator.get_fragmented_free_size()
                capacity += domain.allocator.capacity
                blocks += len(domain.allocator.starts)
        if free_space:
            fragmentation /= free_space
        else:
            fragmentation = 0.
        free_space /= capacity
        usage = 1. - free_space
        stats_text.text = \
            'States: %d  Domains: %d  Blocks: %d  Usage: %d%%  Fragmentation: %d%%' % \
            (len(states), domains, blocks, usage * 100, fragmentation * 100)

    clock.schedule_interval(update_stats, 1)

    glClearColor(1, 1, 1, 1)
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
    while not w.has_exit:
        clock.tick()
        w.dispatch_events()
        w.clear()
        batch.draw()
        fps.draw()
        stats_text.draw()

        glPushAttrib(GL_CURRENT_BIT)
        glColor3f(0, 0, 0)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        glRectf(border - 2, border - 2, w.width - border + 4,
                w.height - border + 4)
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
        glPopAttrib()

        w.flip()

    main()
コード例 #43
0
ファイル: streamers.py プロジェクト: DatRollingStone/nwidget
def update_stats(dt):
    np = len(streamers)
    usage = streamers[0].domain.allocator.get_usage()
    fragmentation = streamers[0].domain.allocator.get_fragmentation()
    blocks = len(streamers[0].domain.allocator.starts)
    stats_text.text = \
        'Streamers: %d  Blocks: %d  Usage: %d%%  Fragmentation: %d%%' % \
        (np, blocks, usage * 100, fragmentation * 100)


clock.schedule_interval(update_stats, 1)

fps_text = clock.ClockDisplay()

while not win.has_exit:
    win.dispatch_events()
    dt = clock.tick()
    dt = min(dt, 0.05)

    update_streamers()
    for i in range(min(MAX_ADD_STREAMERS, MAX_STREAMERS - len(streamers))):
        add_streamers()

    win.clear()
    batch.draw()

    stats_text.draw()
    fps_text.draw()

    win.flip()
コード例 #44
0
def test_first_tick_is_delta_zero():
    """
    Tests that the first tick is dt = 0.
    """
    dt = clock.tick()
    assert dt == 0
コード例 #45
0
from pyglet.window import Window
from pyglet import clock
from scene2d.textsprite import *
from pyglet import font

width, height = 640, 480
window = Window(width=width, height=height)

arial = font.load('Arial', 500, bold=True)
commander = TextSprite(arial, 'COMMANDER', color=(1, 1, 1, 0.5))
keen = TextSprite(arial, 'KEEN', color=(1, 1, 1, 0.5))

print dir(keen)
commander.x = width
keen.x = -keen.width
commander.dx = -(commander.width + width) / 10
keen.dx = (keen.width + width) / 10

clock.set_fps_limit(30)

while not window.has_exit:
    window.dispatch_events()
    time = clock.tick()
    glClear(GL_COLOR_BUFFER_BIT)
    for text in (commander, keen):
        glLoadIdentity()
        text.x += text.dx * time
        text.draw()
    window.flip()
コード例 #46
0
ファイル: display.py プロジェクト: 1160629/DoggoneWasteland
    def update(self):
        self.dt_count += clock.tick()

        if self.dt_count >= 0.025:
            self.dt_count = 0
コード例 #47
0
ファイル: test_clock_fps.py プロジェクト: tritruong9201/C4T16
 def test_first_tick_is_delta_zero(self):
     """
     Tests that the first tick is dt = 0.
     """
     dt = clock.tick()
     self.assertTrue(dt == 0)
コード例 #48
0
def generate_data(game='SonicTheHedgehog-Genesis', state='GreenHillZone.Act1', scenario='scenario', extension_name='',
				  frame_jump=1, save_images=True, save_actions=True, fixed_record_size=False):
	'''
	Play to Sonic and save the images and actions of the session in order to create data for neural networks trainings

	:param game: game to load
	:param state: level to load
	:param scenario: the scenario file
	:param extension_name: extension's name of the image arrays and actions that will be saved
	:param frame_jump: factor for not saving images
		ex :frame_jump = 1 : every image of the session is saved
			frame_jump = 3 : only 1/3 images are saved
		The last action is repeated during the jumped frames
	:return:

	Actions :
		Move Sonic : Directional arrows
		Z : Jump
		S : Down
		R : Save session (images + actions). The name of the save will end by extension_name + an index which is
			incremented every save.
		C : Cancel current recording (images + actions are cleaned)
		BackSpace : level reset (images + actions are cleaned)
	'''

	print('\n\tBACKSPACE : reset level'
		  '\n\tC : Cancel current recording'
		  '\n\tR : Save current recording'
		  '\n\tECHAP : End')

	jump = 0
	# Level loading
	env = retro.make(game=game, state=state, use_restricted_actions=retro.ACTIONS_ALL, scenario=scenario)
	obs = env.reset()
	save_index = 1


	win_width = 900
	screen_height, screen_width = obs.shape[:2]
	win_height = win_width * screen_height // screen_width
	win = pyglet.window.Window(width=win_width, height=win_height, vsync=False)

	key_handler = pyglet.window.key.KeyStateHandler()
	win.push_handlers(key_handler)

	key_previous_states = {}

	pyglet.app.platform_event_loop.start()

	fps_display = pyglet.clock.ClockDisplay()
	clock.set_fps_limit(60)

	glEnable(GL_TEXTURE_2D)
	texture_id = GLuint(0)
	glGenTextures(1, ctypes.byref(texture_id))
	glBindTexture(GL_TEXTURE_2D, texture_id)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, screen_width, screen_height, 0, GL_RGB, GL_UNSIGNED_BYTE, None)

	# Array of the session's images
	images = []
	# Array of the session's actions
	actions = []
	while not win.has_exit:
		win.dispatch_events()

		win.clear()

		keys_clicked = set()
		keys_pressed = set()
		for key_code, pressed in key_handler.items():
			if pressed:
				keys_pressed.add(key_code)

			if not key_previous_states.get(key_code, False) and pressed:
				keys_clicked.add(key_code)
			key_previous_states[key_code] = pressed

		buttons_pressed = set()

		# End of the session
		if keycodes.ESCAPE in keys_pressed:
			pyglet.app.platform_event_loop.stop()
			return
		# Reset images and actions
		elif keycodes.C in keys_pressed:
			print('reset record')
			print(len(images))
			images = []
			actions = []
		# Images and actions of the game session are saved
		elif fixed_record_size and len(images) == SEQ_LENGTH + 1:
			if save_images:
				images = np.array(images, dtype=np.uint8)
				np.save('./data/images/' + state + extension_name + str(save_index), images)
				print('Images saved at : ./data/images/' + state + extension_name + str(save_index))

			if save_actions:
				actions = np.array(actions, dtype=np.bool)
				np.save('./data/actions/' + state + extension_name + str(save_index), actions)
				print('Actions saved at : ./data/actions/' + state + extension_name + str(save_index))

			images = []
			actions = []
			save_index += 1
		elif keycodes.R in keys_pressed:
			if save_images and len(images) > 10:
				images = np.array(images, dtype=np.uint8)
				np.save('./data/images/' + state + extension_name + str(save_index), images)
				print('Images saved at : ./data/images/' + state + extension_name + str(save_index))

			if save_actions and len(actions) > 10:
				actions = np.array(actions, dtype=np.bool)
				np.save('./data/actions/' + state + extension_name + str(save_index), actions)
				print('Actions saved at : ./data/actions/' + state + extension_name + str(save_index))

			images = []
			actions = []
			save_index += 1
		# Reset of the level, actions and images
		elif keycodes.BACKSPACE in keys_pressed:
			print('level reset')
			env.reset()
			images = []
			actions = []

		inputs = {
			'A': keycodes.Z in keys_pressed or ButtonCodes.A in buttons_pressed,
			'B': keycodes.A in keys_pressed or ButtonCodes.B in buttons_pressed,
			'C': keycodes.E in keys_pressed,
			'X': keycodes.Q in keys_pressed or ButtonCodes.X in buttons_pressed,
			'Y': keycodes.S in keys_pressed or ButtonCodes.Y in buttons_pressed,
			'Z': keycodes.D in keys_pressed,

			'UP': keycodes.UP in keys_pressed or ButtonCodes.D_UP in buttons_pressed,
			'DOWN': keycodes.DOWN in keys_pressed or ButtonCodes.D_DOWN in buttons_pressed,
			'LEFT': keycodes.LEFT in keys_pressed or ButtonCodes.D_LEFT in buttons_pressed,
			'RIGHT': keycodes.RIGHT in keys_pressed or ButtonCodes.D_RIGHT in buttons_pressed,

			'MODE': keycodes.TAB in keys_pressed or ButtonCodes.SELECT in buttons_pressed,
			'START': keycodes.ENTER in keys_pressed or ButtonCodes.START in buttons_pressed,
		}

		if jump == 0:
			action = [inputs[b] for b in env.BUTTONS]
			last_action = action
			obs, rew, done, info = env.step(action)
			jump = frame_jump
			if save_images:
				images.append(obs)
			if save_actions:
				actions.append([inputs['A'], inputs['LEFT'], inputs['RIGHT'], inputs['DOWN']])
		else:
			obs, rew, done, info = env.step(last_action)

		jump -= 1

		glBindTexture(GL_TEXTURE_2D, texture_id)
		video_buffer = ctypes.cast(obs.tobytes(), ctypes.POINTER(ctypes.c_short))
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, obs.shape[1], obs.shape[0], GL_RGB, GL_UNSIGNED_BYTE, video_buffer)

		x = 0
		y = 0
		h = win.height
		w = win.width

		pyglet.graphics.draw(4,
							 pyglet.gl.GL_QUADS,
							 ('v2f', [x, y, x + w, y, x + w, y + h, x, y + h]),
							 ('t2f', [0, 1, 1, 1, 1, 0, 0, 0]),
							 )

		fps_display.draw()

		win.flip()

		timeout = clock.get_sleep_time(False)
		pyglet.app.platform_event_loop.step(timeout)

		clock.tick()

	pyglet.app.platform_event_loop.stop()