• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python time.Clock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pygame.time.Clock的典型用法代码示例。如果您正苦于以下问题:Python Clock类的具体用法?Python Clock怎么用?Python Clock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Clock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

def main():
    """ Starting function for the application. Initialize pygame and quidditas and start
        the game.
    """
    pygame.init()
    pygame.display.set_caption("Tower defense example using Quidditas")
    
    screen = pygame.display.set_mode((640, 480))
    clock = Clock()
    running = 1
    
    images = {}
    images["soldier"] = load("res/soldier.png")

    q = init_quidditas(screen, images)

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = 0
        q.update(clock.get_time())
        update(clock.get_time())
        render(clock.get_time())

        pygame.display.flip()
        clock.tick(60)
开发者ID:Alwnikrotikz,项目名称:quidditas,代码行数:26,代码来源:tdf.py


示例2: main

def main():
    """Main program loop"""
    
    pygame.init()
    screen = pygame.display.set_mode(opt.window_size)
    
    sys_font = Font(get_default_font(), opt.font_size)
    clock = Clock()
    
    manager = YarsManager()

    running = True
    
    while running:
        #limit framerate and prepare FPS display text
        clock.tick(opt.max_framerate)
        fps = clock.get_fps()
        fps_text = sys_font.render("FPS: {0:.1f}".format(fps), False, opt.white)
        
        if event.get(pygame.QUIT):
            sys.exit()

        running = manager.handle_events(event.get(), key.get_pressed())
        manager.update()

        screen.fill(opt.black)
        manager.draw(screen)
        screen.blit(fps_text, fps_text.get_rect(top = 0, right = opt.width))
        pygame.display.update()
		
    sys.exit()
开发者ID:rubiximus,项目名称:yars-revenge,代码行数:31,代码来源:game.py


示例3: Asteroids

class Asteroids(object):
    """ Class definition for the asteroids game. """

    def __init__(self):
        """ Create a new instance of the asteroids game. """
        pygame.init()
        pygame.display.set_caption("Asteroids example using Quidditas")

        screen = pygame.display.set_mode((640, 480))
        self.clock = Clock()

        self.to_update = []
        self.to_render= []

        self.event_bus = cyrusbus.Bus()
        self.event_bus.subscribe("event.exit", self.on_exit)

        images = {}
        images["asteroid"] = load("res/asteroid.png")
        images["spaceship"] = load("res/player.png")
        self.q = self.init_quidditas(screen, images)

    def on_exit(self, event):
        """ Handle an exit event that comes via the event bus. """
        self.running = 0

    def start(self):
        """ Start the game loop. """

        self.running = 1
        while self.running:
            for event in pygame.event.get(pygame.QUIT):
                self.running = 0
            time = self.clock.get_time()
            self.q.update(time)
            self.update(time)
            self.render(time)

            self.clock.tick(60)
        pygame.quit()

    def update(self, time):
        """ Iterate over all processors that update game logic and call their update. """
        [processor.update(time) for processor in self.to_update]

    def render(self, time):
        """ Iterate over all processors that render the game and call their update. """
        [processor.update(time) for processor in self.to_render]
        pygame.display.flip()

    def init_quidditas(self, screen, images):
        """ Initialize the quidditas instance and create the processors. """
        q = quidditas.Quidditas()
        q.add_type_definitions(type_definitions.definitions)

        self.to_update.append(q.add_processor(processors.RenderProcessor(screen, images)))
        self.to_update.append(q.add_processor(processors.AsteroidSpawner()))
        self.to_update.append(q.add_processor(processors.ControlsProcessor(self.event_bus)))
        self.to_render.append(q.add_processor(processors.MovementProcessor((640, 480))))
        return q
开发者ID:Alwnikrotikz,项目名称:quidditas,代码行数:60,代码来源:asteroids.py


示例4: update

 def update(self, deps, callback, max_fps):
   c = Clock()
   while self.running:
     env = self.compose(deps)
     callback(*env)
     c.tick(max_fps)
   self.logger.debug("Thread with deps %s ending" % (str(deps)))
开发者ID:bossjones,项目名称:Jarvis,代码行数:7,代码来源:Engine.py


示例5: run

def run():
    clock = Clock()
    initialize()
    while(True):
        dt = clock.tick(60)
        update()
        render()
开发者ID:OneGameAMonth,项目名称:1gam-jan-shadow,代码行数:7,代码来源:TestShadow.py


示例6: main

def main():
    pygame.init()

    size = width, height = 1280, 720
    speed = [2,2]
    black = 0, 0, 0
    pos = posx, posy = width/2, height/2
    radius = 20
    color = THECOLORS["red"]
    clock = Clock()
    screen = pygame.display.set_mode(size)
    surface = pygame.display.get_surface()
    rmanager = RingManager( width, height, center = pos)
    r = 0
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: pygame.quit(); sys.exit()
            elif event.type == KEYDOWN:
                if pygame.key.get_pressed()[K_1]:
                    r = 0
                if pygame.key.get_pressed()[K_2]:
                    r = 1
                if pygame.key.get_pressed()[K_3]:
                    r = 2
                if pygame.key.get_pressed()[K_4]:
                    r = 3
                if pygame.key.get_pressed()[K_LEFT]:
                    rmanager.rings[r] << 1
                elif pygame.key.get_pressed()[K_RIGHT]:
                    rmanager.rings[r] >> 1
        rmanager.checkCollide()
        rmanager.paintAll(surface)
        pygame.display.flip()
        clock.tick(60)
开发者ID:danimanimal,项目名称:Crazy-chemistry-prototype,代码行数:34,代码来源:testballs.py


示例7: __init__

class CpuSpinner:
    def __init__(self, directory, ttl=False, gameticks=Parameters.GAMETICKS, gamespeed=Parameters.GAMESPEED):
        self.clock = GameClock(gameticks)
        self.clock.set_speed(gamespeed)
        self.clock.start()

        self.limitclock = Clock()

        self._running = True

        self.__ttl = ttl * Parameters.GAMETICKS

        self._directory = directory

        self.__aupdatecounter = 0

    def __gettick(self):
        return self.clock.game_tick

    def __getbetweenframe(self):
        return self.clock.get_between_frame()

    def start(self):
        self.__loop()

    def __loop(self):
        while self._running:
            for i in self.clock.update():
                self.__update()
            self._draw()

    def __update(self):
        if self.__ttl:
            self.__ttl -= 1
            if self.__ttl == 0:
                self._running = False

        # regular update done x times by seconds
        for updatable in self._directory.get(Tags.UPDATABLE):
            updatable.update(self.__gettick())

        self.__aupdatecounter += 1

        if self.__aupdatecounter == Parameters.AGAMETICKS:
            self.__aupdatecounter = 0
            self._aupdate()

    def _aupdate(self):
        # alternative (heavy update) every x updates
        self._directory.update()
        # print self.clock.average_fps

    def _draw(self):
        self._directory.get_single(Tags.RENDERER).draw(self.__getbetweenframe())
        if Parameters.FPSLIMIT:
            self.limitclock.tick(Parameters.FPSLIMIT)
开发者ID:VertPingouin,项目名称:projectjudge,代码行数:56,代码来源:cpuspinner.py


示例8: run

 def run(self):
     clock = Clock()
     while True:
         clock.tick(50)
         for event in pygame.event.get():
             if event.type == QUIT:
                 return
             if event.type == KEYDOWN:
                 return
         self.draw(self.screen)
开发者ID:bpa,项目名称:renegade,代码行数:10,代码来源:editor.py


示例9: __init__

 def __init__(self):
     self.input = InputHandler()
     self.state_manager = GameStateManager()
     self.hiscores = Hiscores(resources.get_hiscores(HISCORES_FILENAME))
     self.logic_clock = Clock()
     self.render_clock = Clock()
     self.renderer = Thread(target=self.render_loop, args=())
     self.renderer.daemon = True
     self.rendering = Lock()
     self.running = False
     self.screen = None
     self.canvas = None
开发者ID:PatriqDesigns,项目名称:PyOng,代码行数:12,代码来源:game.py


示例10: TaltosGame

class TaltosGame():

    def __init__(self):
        pygame.init()
        self.clock = Clock()
        MusicPlayer.MusicPlayer().playContinously()

        self.gameMode = GameMode.GameMode(GameModes.RPG)
        self.gameScreen = MainScreen.MainScreen()
        self.gameScreen.setScreenMode(self.gameMode.getGameMode())
        self.language = Menu.Menu(self.gameScreen.getScreen()).languageChooser()

        """
        self.gameModules = {
                GameModes.RPG : None,
                GameModes.CYBERSPACE : None }
        """
        self.changeGameMode(GameModes.RPG)

    def changeGameMode(self, newGameMode):
        self.gameMode.setGameMode(newGameMode)
        self.gameScreen.setScreenMode(self.gameMode.getGameMode())
        if self.gameMode.getGameMode() == GameModes.RPG:
            self.currentGameModule = Rpg.Rpg(self.gameScreen, self.language)
        if self.gameMode.getGameMode() == GameModes.CYBERSPACE:
            self.currentGameModule = Cyberspace.Cyberspace(self.gameScreen, self.language)
        """
        if self.gameMode.getGameMode() == GameModes.RPG:
            if self.gameModules[GameModes.RPG] is None:
                self.gameModules[GameModes.RPG] = Rpg.Rpg(self.gameScreen, self.language)
        if self.gameMode.getGameMode() == GameModes.CYBERSPACE:
            if self.gameModules[GameModes.CYBERSPACE] is None:
                self.gameModules[GameModes.CYBERSPACE] = Cyberspace.Cyberspace(self.gameScreen, self.language)
        self.currentGameModule = self.gameModules[self.gameMode.getGameMode()]
        """

    def gameLoop(self):
        while True:
            try:
                self.clock.tick(30)
                self.currentGameModule.handleKeyEvents()
                self.currentGameModule.gameLoop()
            except MainExceptions.Exit:
                exit()
            except MainExceptions.ChangeGameMode as gameModeChange:
                self.changeGameMode(gameModeChange.newGameMode)

            if self.gameMode.getGameMode() == GameModes.RPG:
                pygame.display.update()
            if self.gameMode.getGameMode() == GameModes.CYBERSPACE:
                pygame.display.flip()
开发者ID:tobal,项目名称:Taltos,代码行数:51,代码来源:Main.py


示例11: main

def main():
    pygame.init()
    # pygame.mixer.init()
    pygame.mixer.init(frequency=22050, size=8, channels=2, buffer=2048)

    from all_notes import AllNotes

    allnotes = AllNotes()
    from plingpling import Glaspling

    pling = Glaspling()
    from random_sounds import Random

    random = Random()
    from beats import Trummor

    beats = Trummor()

    sounds = {"random": random, "all": allnotes, "pling": pling, "trummor": beats}

    if len(sys.argv) < 4:
        print "Usage: python sequences.py midi_file track1 sound1 track2 sound2 ..."
        print "  available sounds: " + str(sounds.keys())
        sys.exit(1)

    midi_file = sys.argv[1]
    tempo = float(sys.argv[2])
    our_tracks = sys.argv[3::2]
    our_sounds = sys.argv[4::2]

    song = midi.read_midifile(midi_file)
    clk = Clock()
    all_we_need = []

    for (tid, soundname) in zip(our_tracks, our_sounds):
        track = song[int(tid)]
        event = track[0]
        tick = event.tick
        sound = sounds.get(soundname, pling)
        all_we_need.append({"track": track, "event_idx": 0, "event": event, "ticks_left": tick, "play": sound.play})

    while True:
        ticks_passed = clk.tick() * tempo

        if len(all_we_need) == 0:
            break

        for index, track in enumerate(all_we_need):
            advance(track, ticks_passed)

    print "Bye bye"
开发者ID:HackOutWest15,项目名称:synthetic-music-group,代码行数:51,代码来源:sequences.py


示例12: GameClock

class GameClock(Observable):
    """Keeps track of how fast the game clock runs"""

    # Fires when game time advances
    # :param dt: Amount of game time that elapsed
    @EventType
    def REAL_TIME_ADVANCE(dt):
        """Game time has advanced
        :param dt: Amount of game time that elapsed, in "seconds"
        """

    @EventType
    def GAME_TIME_ADVANCE(dt):
        """Real time has passed
        :param dt: Amount of real time that elapsed, in milliseconds
        """

    def __init__(self, framerate, multiplier=1.0):
        super(GameClock, self).__init__()

        self.clock = Clock()
        self._multiplier = multiplier
        self.framerate = framerate
        self.isPaused = False

    @property
    def multiplier(self):
        """Get the real/game time ratio"""
        if self.isPaused:
            return 0
        else:
            return self._multiplier

    @multiplier.setter
    def multiplier(self, multiplier):
        """Get the real/game time ratio"""
        self._multiplier = multiplier

    def toggle(self):
        self.isPaused ^= True

    def update(self):
        # pygame.time.Clock::tick() returns milliseconds
        real_dt = self.clock.tick(self.framerate)
        # self.notify(GameClock.REAL_TIME_ADVANCE, real_dt)
        game_dt = real_dt * self.multiplier / 1000.0
        self.notify(GameClock.GAME_TIME_ADVANCE, game_dt)

    def zero(self):
        """Drain any time off the internal clock without calling any updaters"""
        real_dt = self.clock.tick(self.framerate)
开发者ID:karlrwjohnson,项目名称:pythongame,代码行数:51,代码来源:GameClock.py


示例13: main

def main():
    """The main function of the game.
    Initializes PyGame objects and then enters the game loop
    """
    
    pygame.init()
    screen = pygame.display.set_mode(window_size)
    
    sys_font = Font(get_default_font(), font_size)
    clock = Clock()
    
    #now that pygame is initialized, initialize inherited classes properly
    global enemy_wave, player
    enemy_wave = EnemyGroup(evil_bullets)
    
    player = Player(window_size, ship_filename, ship_speed)
    
    while 1:
        #limit framerate and prepare FPS display text
        clock.tick(max_framerate)
        fps = clock.get_fps()
        fps_text = sys_font.render("FPS: {0:.1f}".format(fps), False, white)
        
        score_text = sys_font.render("SCORE: {}".format(score), False, white)
        lives_text = sys_font.render("MANS: {}".format(lives), False, white)
    
        #check for QUIT event to prevent endless loopage
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            
        #call the game's thinking functions
        check_gameover()
        keyboard()
        evil_bullets.update()
        good_bullets.update()
        enemy_wave.update()
        collisions()
            
        #draw the stuff
        screen.fill(black)
        good_bullets.draw(screen)
        evil_bullets.draw(screen)
        enemy_wave.draw(screen)
        screen.blit(player.image, player.rect)
        screen.blit(score_text, score_text.get_rect(top = 0, left = 0))
        screen.blit(lives_text, lives_text.get_rect(top = 0, centerx = width / 2))
        screen.blit(fps_text, fps_text.get_rect(top = 0, right = width))
        pygame.display.update()
开发者ID:rubiximus,项目名称:invader-shootan,代码行数:48,代码来源:game.py


示例14: __init__

    def __init__(self, evManager):
        self.evManager = evManager
	self.evManager.RegisterListener( self )
     
        self.clock = Clock()

	self.keepGoing = 1
开发者ID:sentientWilder,项目名称:Pygame-Demo,代码行数:7,代码来源:CPUSpinnerController.py


示例15: start_display_output

 def start_display_output(self):
     """ Start thread for graphical VU meter """
     
     pygame.event.clear()
     clock = Clock()
     self.meter.start()        
     while 1:
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 self.exit()
             elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                 keys = pygame.key.get_pressed() 
                 if (keys[pygame.K_LCTRL] or keys[pygame.K_RCTRL]) and event.key == pygame.K_c:
                     self.exit()                                                 
         self.refresh()
         clock.tick(1)
开发者ID:project-owner,项目名称:PeppyMeter,代码行数:16,代码来源:peppymeter.py


示例16: __init__

    def __init__(self, framerate, multiplier=1.0):
        super(GameClock, self).__init__()

        self.clock = Clock()
        self._multiplier = multiplier
        self.framerate = framerate
        self.isPaused = False
开发者ID:karlrwjohnson,项目名称:pythongame,代码行数:7,代码来源:GameClock.py


示例17: __init__

 def __init__(self):
     if Time._instance is None:
         Time._instance = self
     else:
         pass
     self._delta_time = 0
     self._time_scale = 1
     self._clock = Clock()
开发者ID:temdisponivel,项目名称:temdisponivellib_pygame,代码行数:8,代码来源:timeutils.py


示例18: __init__

 def __init__(self, *args, **kargs):
     super(TimeLockedState, self).__init__(*args, **kargs)
     self._lock = True
     self._waited = 0
     if not "lock" in kargs.keys():
         raise Exception("you must provide an argument named 'lock'.")
     self._time_to_wait = kargs["lock"]
     self._clock = Clock()
开发者ID:MrGecko,项目名称:pyguane,代码行数:8,代码来源:gamestate.py


示例19: Time

class Time(object):
    """
    A helper class for dealing with time.
    """
    _instance = None

    def __init__(self):
        if Time._instance is None:
            Time._instance = self
        else:
            pass
        self._delta_time = 0
        self._time_scale = 1
        self._clock = Clock()

    def update(self):
        self._delta_time = self._clock.tick(Configuration.instance().frame_cap )

    @property
    def delta_time(self):
        return self._delta_time / self.time_scale

    @property
    def time_scale(self):
        return self._time_scale

    @time_scale.setter
    def time_scale(self, time_scale):
        self._time_scale = time_scale

    @property
    def clock(self):
        return self._clock

    @property
    def frame_rate(self):
        """
        :return: The frame rate which the game is current running.
        """
        return self._clock.get_fps()

    @staticmethod
    def instance():
        if Time._instance is None:
            Time._instance = Time()
        return Time._instance
开发者ID:temdisponivel,项目名称:temdisponivellib_pygame,代码行数:46,代码来源:timeutils.py


示例20: __init__

class GetIP:

	def __init__(self, height, width):
		self._height = height
		self._width = width
		self.IPtext = ""
		self.clock = Clock()
	
	def get_key(self):
		while True:
			event = pygame.event.poll()
			if event.type == KEYDOWN:
				return event.key
			elif event.type == pygame.QUIT:
				exit()
			else:
				pass

	def draw(self, view):
		tfont = pygame.font.Font(None, 20)
		pygame.draw.rect(view, (0,0,0), ((self._width/2)-100, (self._height/2)-10, 200,20), 0)
		pygame.draw.rect(view, (255,255,255), ((self._width/2)-102, (self._height/2)-12, 204,24), 1)
		view.blit(tfont.render("IP address: "+ self.IPtext, 1, (255,0,0)), ((self._width/ 2) - 100, (self._height/ 2) - 10))
		pygame.display.update()

	def get_ip(self,view):
		IP = []
		self.IPtext = ""
		self.draw(view)
		while True:
			inputkey = self.get_key()
			if inputkey == K_BACKSPACE:
				IP = IP[0:-1]
			elif inputkey == K_RETURN:
				break
			elif inputkey <=127:
				IP.append(chr(inputkey))

			self.IPtext = (string.join(IP,""))
			self.draw(view)
			
			self.clock.tick(40)
		return self.IPtext
开发者ID:usercngit,项目名称:INF123_TeamCSS,代码行数:43,代码来源:GetIP.py



注:本文中的pygame.time.Clock类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python transform.rotate函数代码示例发布时间:2022-05-25
下一篇:
Python time.wait函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap