首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >游戏窗口在与其交互后没有响应。

游戏窗口在与其交互后没有响应。
EN

Stack Overflow用户
提问于 2022-07-18 16:52:37
回答 1查看 36关注 0票数 2

我需要每秒钟在随机的地方产生圆圈。现在我有了这个密码。

代码语言:javascript
复制
import pygame as pg
from threading import Thread
import random

pg.init()

WIDTH = 600
HEIGH = 600

sc = pg.display.set_mode((WIDTH, HEIGH))
pg.display.set_caption("Bacteria")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

sc.fill(BLACK)
pg.display.flip()

clock = pg.time.Clock()
FPS = 24

class FoodGen(Thread):
    def run(self):
        while 1:
            clock.tick(1)
            pg.draw.circle(sc, WHITE, (random.randint(10, WIDTH-10), random.randint(10, WIDTH-10)), 10)

class Main(Thread):
    def run(self):
        running = 1
        while running:
            clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = 0
                    break
            pg.display.flip()
        pg.quit()

t1 = FoodGen()
t1.start()
t2 = Main()
t2.start()

当在窗口上移动鼠标时,它会转到等待模式。窗口在运行,直到我试图移动或关闭它。我已经查了很多关于这个问题的信息,但仍然无法解决。

EN

回答 1

Stack Overflow用户

发布于 2022-07-18 17:21:00

How to run multiple while loops at a time in Python。如果你想要控制一些东西,随着时间的推移,你有两个选择:

  1. 使用pygame.time.get_ticks()度量时间,并根据时间实现控制对象的逻辑。

  1. 使用计时器事件。使用pygame.time.set_timer()在事件队列中重复创建USEREVENT。在事件发生时更改对象状态。

例如:

代码语言:javascript
复制
import pygame as pg
import random

WIDTH, HEIGH = 600, 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
FPS = 24

pg.init()
sc = pg.display.set_mode((WIDTH, HEIGH))
pg.display.set_caption("Bacteria")
clock = pg.time.Clock()

timer_interval = 100 # 0.1 seconds
timer_event_id = pg.USEREVENT + 1
pg.time.set_timer(timer_event_id, timer_interval)

circles = []
running = 1
while running:
    clock.tick(FPS)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = 0
        if event.type == timer_event_id:
            circles.append((random.randint(10, WIDTH-10), random.randint(10, WIDTH-10)))
            
    sc.fill(BLACK)     
    for center in circles:
        pg.draw.circle(sc, WHITE, center, 10)
    pg.display.flip()

pg.quit()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73025914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档