Pygame 中的倒计时器

2024-12-11 08:47:00
admin
原创
147
摘要:问题描述:我开始使用 pygame,我想做一个简单的游戏。我需要的元素之一是倒数计时器。如何在 PyGame 中设置倒计时(例如 10 秒)?解决方案 1:另一种简单的方法是简单地使用 pygame 的事件系统。这是一个简单的例子:import pygame pygame.init() screen = py...

问题描述:

我开始使用 pygame,我想做一个简单的游戏。我需要的元素之一是倒数计时器。如何在 PyGame 中设置倒计时(例如 10 秒)?


解决方案 1:

另一种简单的方法是简单地使用 pygame 的事件系统。

这是一个简单的例子:

import pygame
pygame.init()
screen = pygame.display.set_mode((128, 128))
clock = pygame.time.Clock()

counter, text = 10, '10'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.SysFont('Consolas', 30)

run = True
while run:
    for e in pygame.event.get():
        if e.type == pygame.USEREVENT: 
            counter -= 1
            text = str(counter).rjust(3) if counter > 0 else 'boom!'
        if e.type == pygame.QUIT: 
            run = False

    screen.fill((255, 255, 255))
    screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
    pygame.display.flip()
    clock.tick(60)

在此处输入图片描述

解决方案 2:

在此页面上,您将找到所需的内容http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks

在开始倒计时之前,您需要下载一次刻度(这可以是游戏中的触发器 - 关键事件,等等)。例如:

start_ticks=pygame.time.get_ticks() #starter tick
while mainloop: # mainloop
    seconds=(pygame.time.get_ticks()-start_ticks)/1000 #calculate how many seconds
    if seconds>10: # if more than 10 seconds close the game
        break
    print (seconds) #print how many seconds

解决方案 3:

在 pygame 中存在一个计时器事件。用于pygame.time.set_timer()重复创建一个USEREVENT。例如:

timer_interval = 500 # 0.5 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event , timer_interval)

注意,在 pygame 中可以定义客户事件。每个事件都需要一个唯一的 ID。用户事件的 ID 必须介于pygame.USEREVENT(24) 和pygame.NUMEVENTS(32) 之间。在本例中pygame.USEREVENT+1是计时器事件的事件 ID。

要禁用事件的计时器,请将毫秒参数设置为 0。

在事件循环中接收事件:

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

         elif event.type == timer_event:
             # [...]

可以通过将 0 传递给时间参数来停止计时器事件。


请看示例:

IT科技

import pygame

pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 10
text = font.render(str(counter), True, (0, 128, 0))

timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == timer_event:
            counter -= 1
            text = font.render(str(counter), True, (0, 128, 0))
            if counter == 0:
                pygame.time.set_timer(timer_event, 0)                

    window.fill((255, 255, 255))
    text_rect = text.get_rect(center = window.get_rect().center)
    window.blit(text, text_rect)
    pygame.display.flip()

解决方案 4:

pygame.time.Clock.tick返回自上次调用以来的时间clock.tick(增量时间,dt)以毫秒为单位,因此您可以使用它来增加或减少计时器变量。

import pygame as pg


def main():
    pg.init()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 40)
    gray = pg.Color('gray19')
    blue = pg.Color('dodgerblue')
    # The clock is used to limit the frame rate
    # and returns the time since last tick.
    clock = pg.time.Clock()
    timer = 10  # Decrease this to count down.
    dt = 0  # Delta time (time since last tick).

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        timer -= dt
        if timer <= 0:
            timer = 10  # Reset it to 10 or do something else.

        screen.fill(gray)
        txt = font.render(str(round(timer, 2)), True, blue)
        screen.blit(txt, (70, 70))
        pg.display.flip()
        dt = clock.tick(30) / 1000  # / 1000 to convert to seconds.


if __name__ == '__main__':
    main()
    pg.quit()

解决方案 5:

有几种方法可以做到这一点 - 这里是其中一种。据我所知,Python 没有中断机制。

import time, datetime

timer_stop = datetime.datetime.utcnow() +datetime.timedelta(seconds=10)
while True:
    if datetime.datetime.utcnow() > timer_stop:
        print "timer complete"
        break

解决方案 6:

有很多方法可以做到这一点,这是其中之一

import pygame,time, sys
from pygame.locals import*
pygame.init()
screen_size = (400,400)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("timer")
time_left = 90 #duration of the timer in seconds
crashed  = False
font = pygame.font.SysFont("Somic Sans MS", 30)
color = (255, 255, 255)

while not crashed:
    for event in pygame.event.get():
        if event.type == QUIT:
            crashed = True
    total_mins = time_left//60 # minutes left
    total_sec = time_left-(60*(total_mins)) #seconds left
    time_left -= 1
    if time_left > -1:
        text = font.render(("Time left: "+str(total_mins)+":"+str(total_sec)), True, color)
        screen.blit(text, (200, 200))
        pygame.display.flip()
        screen.fill((20,20,20))
        time.sleep(1)#making the time interval of the loop 1sec
    else:
        text = font.render("Time Over!!", True, color)
        screen.blit(text, (200, 200))
        pygame.display.flip()
        screen.fill((20,20,20))




pygame.quit()
sys.exit()

解决方案 7:

这其实很简单。感谢 Pygame 创建了一个简单的库!

import pygame
x=0
while x < 10:
    x+=1
    pygame.time.delay(1000)

就这些了!祝你玩得开心!

解决方案 8:

另一种方法是设置一个新 USEREVENT 来触发一个 tick,设置它的时间间隔,然后将该事件放入你的游戏循环中'''

import pygame
from pygame.locals import *
import sys
pygame.init()

#just making a window to be easy to kill the program here
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("tick tock")

#set tick timer 
tick = pygame.USEREVENT
pygame.time.set_timer(tick,1000)

while 1:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.USEREVENT:
            if event.type == tick:
                ## do whatever you want when the tick happens
                print('My tick happened')
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用