首页 > 解决方案 > 在pygame的主循环内循环

问题描述

我对 python 和 pygame 还很陌生。我正在尝试制作一个简单的游戏作为练习。我的问题是我如何在主游戏循环内有一个循环(或多个循环),以便图形也在子循环内更新?例如,我有一个按钮和一个矩形,如果我按下按钮,我希望矩形在屏幕上移动。我尝试过的事情:

这是我的代码:

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()

任何帮助深表感谢

标签: python-3.xwhile-looppygame

解决方案


你必须实现某种状态。通常,您会使用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.


在此处输入图像描述


你应该避免在你的游戏中创建多个逻辑循环(对不起,我没有更好的词);看到你提到的问题。目标是做三件事的一个主循环:输入处理、游戏逻辑和绘图。


推荐阅读