【问题标题】:Loop within main loop in pygame在pygame的主循环内循环
【发布时间】:2019-03-13 14:04:37
【问题描述】:

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

非常感谢任何帮助

【问题讨论】:

    标签: python-3.x while-loop pygame


    【解决方案1】:

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



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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2014-06-18
      相关资源
      最近更新 更多