Beispiel #1
0
class GameLoop(DirectorLoop):
    def __init__(self):
        super().__init__()
        self.clock = GameClock()
        try:
            import IPython.core
            shell = IPython.core.getipython.get_ipython()
            self._kernel = shell.kernel
        except ImportError:
            self._kernel = None

    def terminal_init(self):
        super().terminal_init()
        terminal.set("""
        window.resizeable=true;
        """)

    def get_initial_scene(self):
        return MainMenuScene()

    def terminal_update(self):
        self.clock.tick()
        if self._kernel:
            self._kernel.do_one_iteration()
        return super().terminal_update()
Beispiel #2
0
class GalaxyView:
    def __init__(self):
        self.galaxy = Galaxy()
        self.screen = pygame.display.set_mode((500, 500))
        self.clock = GameClock(FPS, update_callback=self.update)

    def draw_planets(self):
        for _planet in self.galaxy.planets:
            if isinstance(_planet, planet.Planet):
                self.screen.set_at(_planet.position, (255, 255, 255))

    def draw(self):
        self.screen.fill((0, 0, 0))
        self.draw_planets()
        pygame.display.flip()

    def main_loop(self):
        while True:
            self.clock.tick()

    def update(self, dt):
        self.galaxy.apply_dt(dt)
        self.draw()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
Beispiel #3
0
 def __init__(self):
     super().__init__()
     self.clock = GameClock()
     try:
         import IPython.core
         shell = IPython.core.getipython.get_ipython()
         self._kernel = shell.kernel
     except ImportError:
         self._kernel = None
Beispiel #4
0
	def run(self):
		def callback(time):
			self.evManager.post(TickEvent())
			return
		clock = GameClock()
		clock.schedule_interval(callback, 0.042)
		#clock.schedule_interval(callback, 0.25)
		
		while self.keepGoing:
			clock.tick()
Beispiel #5
0
class InteractiveApp(App):
    def __init__(self, kernel):
        self.kernel = kernel
        self.clock = GameClock()
        self.clock.frame_callback = self.my_update

    def init_root(self, width=80, height=26, show_credits=False):
        self.root = tdl.init(width, height)
        self.scratch = tdl.Console(width, height)
        self.temp_console = tdl.Console(width, height)
        self.width, self.height = width, height
        tdl.set_fps(30)
        if show_credits:
            tcod.console_credits()
            # tcod.sys_set_fps(self.max_fps)

    def draw(self):
        self.root.drawStr(1, 2, "No draw method defined, using default method.")
        self.root.drawStr(1, 3, "Time elapsed = {0}".format(tcod.sys_elapsed_milli()))
        self.root.drawStr(1, 4, "FPS = {0}".format(tcod.sys_get_fps()))

    def my_update(self, dt):
        self.root.clear()
        self.draw()
        tdl.flush()

    def runOnce(self):
        """Pump events to this App instance and then return.

        This works in the way described in L{App.run} except it immediately
        returns after the first L{update} call.

        Having multiple L{App} instances and selectively calling runOnce on
        them is a decent way to create a state machine.
        """
        self.kernel.do_one_iteration()
        self.clock.tick()
        for event in get():
            if event.type:  # exclude custom events with a blank type variable
                # call the ev_* methods
                method = 'ev_%s' % event.type  # ev_TYPE
                getattr(self, method)(event)
            if event.type == 'KEYDOWN':
                # call the key_* methods
                method = 'key_%s' % event.key  # key_KEYNAME
                if hasattr(self, method):  # silently exclude undefined methods
                    getattr(self, method)(event)
Beispiel #6
0
class InteractiveApp(App):
    def __init__(self, kernel):
        self.kernel = kernel
        self.clock = GameClock()
        self.clock.frame_callback = self.frame_update

    def init_root(self, width=80, height=26, show_credits=False):
        self.root = tdl.init(width, height)
        self.canvas = tdl.Console(width, height)
        self.temp_console = tdl.Console(width, height)
        self.width, self.height = width, height
        tdl.set_fps(30)
        if show_credits:
            tcod.console_credits()
            # tcod.sys_set_fps(self.max_fps)

    def draw(self):
        self.root.blit(self.canvas)

    def frame_update(self, dt):
        self.root.clear()
        self.draw()
        tdl.flush()

    def runOnce(self):
        """Pump events to this App instance and then return.

        This works in the way described in L{App.run} except it immediately
        returns after the first L{update} call.

        Having multiple L{App} instances and selectively calling runOnce on
        them is a decent way to create a state machine.
        """
        if self.kernel:
            self.kernel.do_one_iteration()
        self.clock.tick()
        for event in get():
            if event.type:  # exclude custom events with a blank type variable
                # call the ev_* methods
                method = 'ev_%s' % event.type  # ev_TYPE
                getattr(self, method)(event)
            if event.type == 'KEYDOWN':
                # call the key_* methods
                method = 'key_%s' % event.key  # key_KEYNAME
                if hasattr(self, method):  # silently exclude undefined methods
                    getattr(self, method)(event)
Beispiel #7
0
def main():
    global clock, pygame_clock, screen, screen_rect, sprite_group, eraser_image
    global USE_PYGAME_CLOCK, DO_KILL, USE_PREDICTION, PYGAME_FPS
    screen = pygame.display.set_mode((800, 600))
    screen.fill(BGCOLOR)
    screen_rect = screen.get_rect()
    eraser_image = screen.copy()
    which_settings = 0
    pygame_clock = pygame.time.Clock()
    clock = GameClock(*SETTINGS[which_settings],
                      update_callback=update_gameclock,
                      frame_callback=display_gameclock)
    clock.schedule_interval(set_caption_gameclock, 1.0)
    clock.use_wait = False
    sprite_group = pygame.sprite.Group([Ball() for i in range(INIT_BALLS)])
    #
    game_is_running = True
    while game_is_running:
        if USE_PYGAME_CLOCK:
            pygame_clock.tick(PYGAME_FPS)
            update_pygame()
            display_pygame()
        else:
            clock.tick()
        #
        for e in pygame.event.get():
            if e.type == QUIT:
                quit()
            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    quit()
                elif e.key == K_TAB:
                    which_settings += 1
                    if which_settings >= len(SETTINGS):
                        which_settings = 0
                    (clock.max_ups, clock.max_fps) = SETTINGS[which_settings]
                elif e.key == K_1:
                    sprite_group.add(Ball())
                elif e.key == K_b:
                    sprite_group.add([Ball() for i in range(25)])
                elif e.key == K_k:
                    DO_KILL = not DO_KILL
                elif e.key == K_l:
                    USE_PYGAME_CLOCK = not USE_PYGAME_CLOCK
                elif e.key == K_m:
                    if PYGAME_FPS == 0:
                        PYGAME_FPS = 30
                    else:
                        PYGAME_FPS = 0
                elif e.key == K_p:
                    USE_PREDICTION = not USE_PREDICTION
                elif e.key == K_w:
                    clock.use_wait = not clock.use_wait
Beispiel #8
0
 def __init__(self):
     self.screen = pygame.display.set_mode((800,600))
     self.screen_rect = self.screen.get_rect()
     self.font = pygame.font.SysFont(None, 16)
     self.clock = GameClock(
         30, 120,
         update_callback=self.update,
         frame_callback=self.draw,
         paused_callback=self.pause,
     )
     self.draw_line = pygame.draw.line
     self.ucolor = Color('grey')
     self.dcolor = Color('white')
     self.pcolor = Color('blue')
     self.running = True
     self.paused = False
     
     self.ball = pygame.Surface((30,30))
     self.ball.fill(Color(255,0,0))
     self.ball_start = 300
     self.ball_rect = self.ball.get_rect(x=self.ball_start)
     self.ball_from = self.ball_start
     self.ball_to = self.ball_start
     
     self.elapsed = 0.
     self.nupdates = 0
     self.n10updates = 0
     self.utime = pygame_time()
     self.dtime = pygame_time()
     self.ptime = pygame_time()
     self.uerror = 0
     self.derror = 0
     self.umax = 0
     self.dmax = 0
     self.ptxt = None
     self.msgs = []
     
     # Recur every second
     self.clock.schedule_interval(self.per_second, 1.)
     # Recur every 10 seconds
     self.clock.schedule_interval(self.per_10_second, 10.)
     # Recur every second, for two iterations
     self.clock.schedule_interval(self.recur, 1., 2)
Beispiel #9
0
class GalaxyView:
    def __init__(self):
        self.galaxy = Galaxy()
        self.screen = pygame.display.set_mode((500, 500))
        self.clock = GameClock(update_callback=self.update, max_ups=30)

    def update(self, dt):
        self.handle_events()
        self.screen.fill((30, 0, 0))
        for i in range(10):
            self.galaxy.apply_dt(dt/(2000*(i+1)))
        self.galaxy.load_from_gpu()
        for _planet in self.galaxy.planets_np:
            temp = _planet.astype(np.int)
            _planet_temp = planet.Planet(r=[temp[0], temp[1]])
            self.screen.set_at(_planet_temp.r, (255, 255, 255))
        pygame.display.flip()

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                self.galaxy.clicked = True
                return
            elif event.type == pygame.MOUSEBUTTONUP:
                self.galaxy.clicked = False
                return
            elif event.type == pygame.MOUSEMOTION:
                if self.galaxy.clicked:
                    x, y = event.pos
                    y = 500-y
                    print(x, y)
                    self.galaxy.click = np.array([x, y], dtype=np.float32)

    def main_loop(self):
        while True:
            self.clock.tick()
Beispiel #10
0
    def run(self):
        def callback(time):
            self.evManager.post(TickEvent())
            return

        clock = GameClock()
        clock.schedule_interval(callback, 0.042)
        #clock.schedule_interval(callback, 0.25)

        while self.keepGoing:
            clock.tick()
Beispiel #11
0
def main():
    global clock, pygame_clock, screen, screen_rect, sprite_group, eraser_image
    global USE_PYGAME_CLOCK, DO_KILL, USE_PREDICTION, PYGAME_FPS
    screen = pygame.display.set_mode((800, 600))
    screen.fill(BGCOLOR)
    screen_rect = screen.get_rect()
    eraser_image = screen.copy()
    which_settings = 0
    pygame_clock = pygame.time.Clock()
    clock = GameClock(*SETTINGS[which_settings], update_callback=update_gameclock, frame_callback=display_gameclock)
    clock.schedule_interval(set_caption_gameclock, 1.0)
    clock.use_wait = False
    sprite_group = pygame.sprite.Group([Ball() for i in range(INIT_BALLS)])
    #
    game_is_running = True
    while game_is_running:
        if USE_PYGAME_CLOCK:
            pygame_clock.tick(PYGAME_FPS)
            update_pygame()
            display_pygame()
        else:
            clock.tick()
        #
        for e in pygame.event.get():
            if e.type == QUIT: quit()
            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE: quit()
                elif e.key == K_TAB:
                    which_settings += 1
                    if which_settings >= len(SETTINGS):
                        which_settings = 0
                    (clock.max_ups, clock.max_fps) = SETTINGS[which_settings]
                elif e.key == K_1:
                    sprite_group.add(Ball())
                elif e.key == K_b:
                    sprite_group.add([Ball() for i in range(25)])
                elif e.key == K_k:
                    DO_KILL = not DO_KILL
                elif e.key == K_l:
                    USE_PYGAME_CLOCK = not USE_PYGAME_CLOCK
                elif e.key == K_m:
                    if PYGAME_FPS == 0:
                        PYGAME_FPS = 30
                    else:
                        PYGAME_FPS = 0
                elif e.key == K_p:
                    USE_PREDICTION = not USE_PREDICTION
                elif e.key == K_w:
                    clock.use_wait = not clock.use_wait
Beispiel #12
0
class Game(object):
    
    def __init__(self):
        self.screen = pygame.display.set_mode((800,600))
        self.screen_rect = self.screen.get_rect()
        self.font = pygame.font.SysFont(None, 16)
        self.clock = GameClock(
            30, 120,
            update_callback=self.update,
            frame_callback=self.draw,
            paused_callback=self.pause,
        )
        self.draw_line = pygame.draw.line
        self.ucolor = Color('grey')
        self.dcolor = Color('white')
        self.pcolor = Color('blue')
        self.running = True
        self.paused = False
        
        self.ball = pygame.Surface((30,30))
        self.ball.fill(Color(255,0,0))
        self.ball_start = 300
        self.ball_rect = self.ball.get_rect(x=self.ball_start)
        self.ball_from = self.ball_start
        self.ball_to = self.ball_start
        
        self.elapsed = 0.
        self.nupdates = 0
        self.n10updates = 0
        self.utime = pygame_time()
        self.dtime = pygame_time()
        self.ptime = pygame_time()
        self.uerror = 0
        self.derror = 0
        self.umax = 0
        self.dmax = 0
        self.ptxt = None
        self.msgs = []
        
        # Recur every second
        self.clock.schedule_interval(self.per_second, 1.)
        # Recur every 10 seconds
        self.clock.schedule_interval(self.per_10_second, 10.)
        # Recur every second, for two iterations
        self.clock.schedule_interval(self.recur, 1., 2)
    
    def run(self):
        clock = self.clock
        while self.running:
            clock.tick()
    
    def update(self, dt):
        # Track accuracy. For example, at 30 ups, each update+frames set
        # should not exceed 33 ms.
        t = pygame_time()
        utime = self.utime
        mydt = (t - utime)/1000.
        self.uerror += dt - mydt
        self.utime = t
        
        for e in pygame.event.get():
            if e.type == KEYDOWN:
                self.on_key_down(e)
        
        self.ball_from = self.ball_to
        self.ball_to += dt * 200
        
        ## waste many ms / update
        if SIM_LOAD:
            pygame.time.wait(self.umax)
    
    def draw(self, interp):
        t = pygame_time()
        #
        self.screen.fill((0,0,0))
        x = self.screen_rect.centerx
        
        y = 10
        error = min(max(self.uerror/1000,-100),100)
        self.draw_line(self.screen, self.ucolor, (x,y), (x+error,y), 5)
        
        y += 10
        txt = self.font.render('DT Update ms error: {0:+0.3f}'.format(self.uerror), True, self.ucolor)
        r = txt.get_rect(centerx=x,top=y)
        self.screen.blit(txt, r)
        
        y += 20
        self.ball_rect.y = y
        dx = (self.ball_to - self.ball_from) * self.clock.interpolate
        self.ball_rect.centerx = self.ball_from + dx
        self.screen.blit(self.ball, self.ball_rect)
        
        for i,msg in enumerate(self.msgs):
            r = msg.get_rect(x=3)
            r.y = 3 + (3+r.h) * i
            self.screen.blit(msg, r)
        
        pygame.display.flip()
        
        ## waste many ms / frame
        if SIM_LOAD:
            pygame.time.wait(self.dmax)
    
    def pause(self):
        for e in pygame.event.get():
            if e.type == KEYDOWN:
                self.on_key_down(e)
        msg = 'Time is PAUSED' if self.paused else 'Time is Running'
        self.msgs[0] = self.font.render(msg, True, Color('grey'))
        self.draw(self.clock.interpolate)
    
    def per_second(self, *args):
        # flip the ball and performance meter every second
        self.nupdates += 1
        del self.msgs[:]
        for msg in (
            'Time is PAUSED' if self.paused else 'Time is Running',
            '{0:d} second elapsed'.format(self.nupdates),
            '{0:d} 10-second elapsed'.format(self.n10updates),
            '{0:.1f} / {1:.1f} ups/max'.format(self.clock.ups, self.clock.max_ups),
            '{0:.1f} / {1:.1f} fps/max'.format(self.clock.fps, self.clock.max_fps),
            '{0:d} update waste ms'.format(self.umax),
            '{0:d} draw waste ms'.format(self.dmax),
            '{0:d} use wait'.format(self.clock.use_wait),
            '{0:f} DT update'.format(self.clock.dt_update),
            '{0:f} cost of update'.format(self.clock.cost_of_update),
            '{0:f} DT frame'.format(self.clock.dt_frame),
            '{0:f} cost of frame'.format(self.clock.cost_of_frame),
        ):
            self.msgs.append(self.font.render(msg, True, Color('grey')))
        self.ball_from = self.ball_start
        self.ball_to = self.ball_from + self.clock.dt_update * 200
    
    def per_10_second(self, *args):
        self.n10updates += 10
        msg = '{0:d} 10-second elapsed'.format(self.n10updates)
        self.msgs[2] = self.font.render(msg, True, Color('grey'))
    
    def recur(self, *args):
        print 'RECUR'
    
    def on_key_down(self, e):
        if e.key == K_SPACE:
            # toggle max FPS: 0 vs. 60
            self.clock.max_fps = 0 if self.clock.max_fps else 120
            if DEBUG: print '\n--- max_fps:{0:d} ---'.format(self.clock.max_fps)
        elif e.key == K_UP:
            if e.mod & KMOD_SHIFT:
                # increment simulated update load
                self.umax += 5
                if DEBUG: print '\n--- umax +5:{0:d} ---'.format(self.umax)
            else:
                # increment simulated draw load
                self.dmax += 5
                if DEBUG: print '\n--- dmax +5:{0:d} ---'.format(self.dmax)
        elif e.key == K_DOWN:
            if e.mod & KMOD_SHIFT and self.umax:
                # decrement simulated update load
                self.umax -= 5
                if DEBUG: print '\n--- umax -5:{0:d} ---'.format(self.umax)
            elif self.dmax:
                # decrement simulated draw load
                self.dmax -= 5
                if DEBUG: print '\n--- dmax -5:{0:d} ---'.format(self.dmax)
        elif e.key == K_d:
            # toggle debug messages
            gameclock.DEBUG = not gameclock.DEBUG
            if gameclock.DEBUG:
                print '\n--- debug on ---'
            else:
                print '\n--- debug off ---'
        elif e.key == K_p:
            if self.paused:
                # pause clock
                self.paused = False
                self.clock.resume()
            else:
                # unpause clock
                self.paused = True
                self.clock.pause()
        elif e.key == K_w:
            # toggle use_wait
            self.clock.use_wait = not self.clock.use_wait
            if self.clock.use_wait:
                if DEBUG: print '\n--- wait on---'
            else:
                if DEBUG: print '\n--- wait off ---'
        elif e.key == K_ESCAPE:
            quit()
Beispiel #13
0
 def __init__(self, kernel):
     self.kernel = kernel
     self.clock = GameClock()
     self.clock.frame_callback = self.frame_update
Beispiel #14
0
    # noinspection PyUnusedLocal
    def _update(_):
        """
        Pump events to the current GameState and tell its objects to update
        :param _: unused dt provided by GameClock
        :return:
        """
        events = get()
        CONTEXT["gamestate"].handle_input(events)
        CONTEXT["gamestate"].update()
        # gamestate.handle_input(events)
        # gamestate.update()


    # noinspection PyUnusedLocal
    def _draw(_):
        """
        Ask the current GameState to redraw itself
        :param _: unused interp provided by GameClock
        :return:
        """
        # gamestate.draw()
        CONTEXT["gamestate"].draw()
        flip()

    CLOCK = GameClock(max_ups=60, max_fps=60, update_callback=_update, frame_callback=_draw)

    while True:
        CLOCK.tick()
Beispiel #15
0
 def __init__(self):
     self.galaxy = Galaxy()
     self.screen = pygame.display.set_mode((500, 500))
     self.clock = GameClock(update_callback=self.update, max_ups=30)
Beispiel #16
0
 def __init__(self):
     self.galaxy = Galaxy()
     self.screen = pygame.display.set_mode((500, 500))
     self.clock = GameClock(FPS, update_callback=self.update)
Beispiel #17
0
    
    game_board = Board()
    scoreboard = Scoreboard(player_list)

    voice.say("Starting game!")


#Create scorebox
sbox = ScoreBox(scoreboard.player_list)
sbox.start()
sbox.set_letters(scoreboard.get_tiles_in_bag())
sbox.set_rnd(scoreboard.turn_round)
sbox.update_scores(scoreboard.points)

#Game clock
clock = GameClock(sbox)
clock.start()

#STart up the webserver
serve = webserver.ScrabbleServer(game_board, scoreboard)
serve.start()

#Register interrupt handler
def signal_handler(signal, frame):
    print "\nProgram terminating!"
    voice.kill()
    sv.kill()
    sbox.kill()
    clock.kill()
    serve.kill()
    sys.exit(0)
Beispiel #18
0
 def __init__(self, kernel):
     self.kernel = kernel
     self.clock = GameClock()
     self.clock.frame_callback = self.my_update