python-3.x - 在pygame的主循环内循环
问题描述
我对 python 和 pygame 还很陌生。我正在尝试制作一个简单的游戏作为练习。我的问题是我如何在主游戏循环内有一个循环(或多个循环),以便图形也在子循环内更新?例如,我有一个按钮和一个矩形,如果我按下按钮,我希望矩形在屏幕上移动。我尝试过的事情:
- 另一个while循环,它可以工作,但矩形不会“移动”,只会出现在循环完成的任何地方
- 自定义事件,但是它要么每帧工作一次,要么在 set_timer() 函数的情况下连续工作
这是我的代码:
import pygame as pg
pg.init()
clock = pg.time.Clock()
running = True
window = pg.display.set_mode((640, 480))
window.fill((255, 255, 255))
btn = pg.Rect(0, 0, 100, 30)
rect1 = pg.Rect(0, 30, 100, 100)
while running:
clock.tick(60)
window.fill((255, 255, 255))
for e in pg.event.get():
if e.type == pg.MOUSEBUTTONDOWN:
(mouseX, mouseY) = pg.mouse.get_pos()
if(btn.collidepoint((mouseX, mouseY))):
rect1.x = rect1.x + 1
if e.type == pg.QUIT:
running = False
#end event handling
pg.draw.rect(window, (255, 0, 255), rect1, 1)
pg.draw.rect(window, (0, 255, 255), btn)
pg.display.flip()
#end main loop
pg.quit()
任何帮助深表感谢
解决方案
你必须实现某种状态。通常,您会使用Sprite
该类,但在您的情况下,一个简单的变量就可以了。
看看这个例子:
import pygame as pg
pg.init()
clock = pg.time.Clock()
running = True
window = pg.display.set_mode((640, 480))
window.fill((255, 255, 255))
btn = pg.Rect(0, 0, 100, 30)
rect1 = pg.Rect(0, 30, 100, 100)
move_it = False
move_direction = 1
while running:
clock.tick(60)
window.fill((255, 255, 255))
for e in pg.event.get():
if e.type == pg.MOUSEBUTTONDOWN:
(mouseX, mouseY) = pg.mouse.get_pos()
if(btn.collidepoint((mouseX, mouseY))):
move_it = not move_it
if e.type == pg.QUIT:
running = False
#end event handling
if move_it:
rect1.move_ip(move_direction * 5, 0)
if not window.get_rect().contains(rect1):
move_direction = move_direction * -1
rect1.move_ip(move_direction * 5, 0)
pg.draw.rect(window, (255, 0, 255), rect1, 1)
pg.draw.rect(window, (255, 0, 0) if move_it else (0, 255, 255), btn)
pg.display.flip()
#end main loop
pg.quit()
按下按钮时,我们只需设置move_it
标志。然后,在主循环中,我们检查是否设置了这个标志,然后移动Rect
.
你应该避免在你的游戏中创建多个逻辑循环(对不起,我没有更好的词);看到你提到的问题。目标是做三件事的一个主循环:输入处理、游戏逻辑和绘图。
推荐阅读
- java - 将整数的最后一位四舍五入
- android - java.lang.NullPointerException: com.firebase.ui.database.FirebaseRecyclerAdapter.startListening()' 在空对象引用上
- jquery - 如何通过 JQuery 为 div 元素设置自定义属性
- elasticsearch - 分片(Elasticsearch)是否有自己的 JVM 设置
- excel - 如何在excel的两列中排列重复的条目?
- git - "git log" "tag:" 跨 repos 不一致
- c++ - 将静态库链接到共享:标头中的枚举类 -> 针对未定义符号重定位 R_X86_64_PC32
- php - 在 Laravel 中显示 cron 工作
- reactjs - 幕后 React JS 中的单击事件有效吗?
- vba - ComboBox Enter 事件从对象浏览器中消失