【问题标题】:Why do my bots in pygame move at such an inconsistent speed?为什么我的 pygame 中的机器人以如此不一致的速度移动?
【发布时间】:2021-11-28 04:20:49
【问题描述】:

所以我的问题是我的机器人会以不一致的速度移动,有时甚至不会移动。我已经尝试用clock.ticks(30) 更改 fps(然后更少),但它不会变得更顺畅!

pygame.init()
clock = pygame.time.Clock()

bot4x = random.randint(0, 600)
bot4y = random.randint(0, 600)

randb4 = round(random.randint(0, 4))

def bot4():
    screen.blit(pygame.image.load("DOT.png"), (bot4x, bot4y))

clock.tick(60)
run = True
while run:
    screen.fill((255, 255, 255))

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

        if randb4 == 1:
            bot4x = bot4x + 5
        elif randb4 == 2:
            bot4x = bot4x - 5
        elif randb4 == 3:
            bot4y = bot4y + 5
        elif randb4 == 4:
            bot4y = bot4y - 5

        if bot4x >= 568:
            bot4x = 568
        elif bot4x <= 0:
            bot4x = 0
        elif bot4y >= 568:
            bot4y = 568
        elif bot4y <= 0:
            bot4y = 0
    bot4()
    pygame.display.update()

【问题讨论】:

    标签: python pygame frame-rate


    【解决方案1】:

    这是Indentation 的问题。您必须在应用程序循环而不是事件循环中计算移动:

    pygame.init()
    clock = pygame.time.Clock()
    
    bot4x = random.randint(0, 600)
    bot4y = random.randint(0, 600)
    
    randb4 = round(random.randint(0, 4))
    
    def bot4():
        screen.blit(pygame.image.load("DOT.png"), (bot4x, bot4y))
    
    clock.tick(60)
    run = True
    while run:
        screen.fill((255, 255, 255))
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
        # INDENTATION
        #<--|
    
        if randb4 == 1:
            bot4x = bot4x + 5
        elif randb4 == 2:
            bot4x = bot4x - 5
        elif randb4 == 3:
            bot4y = bot4y + 5
        elif randb4 == 4:
            bot4y = bot4y - 5
    
        if bot4x >= 568:
            bot4x = 568
        elif bot4x <= 0:
            bot4x = 0
        elif bot4y >= 568:
            bot4y = 568
        elif bot4y <= 0:
            bot4y = 0
    
        bot4()
        pygame.display.update()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多