python-3.x - Pygame 没有移动我在屏幕上绘制的矩形

标签 python-3.x pygame

这是我正在尝试制作的游戏的代码(翻拍鸟重制版)

    def move():

        global bird_x
        global bird_y

        pygame.draw.rect(win,(0,0,0), (0,0,1000,1000))
        pygame.draw.rect(win,(255,0,0),(bird_x, bird_y, 30, 30))
        pygame.display.update()
    
while True:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        bird_y += 60
    fb.move()
    time.sleep(0.005)

当我尝试运行此代码时,“鸟”(红色方 block )没有移动,我更改了使用的键,我已经在函数中进出移动,但没有任何效果。 (这是经过修剪的代码,因此变量可能不存在)

完整代码:

import time
import random
pygame.init()

win = pygame.display.set_mode((400,600))
pygame.display.set_caption('Flappy Bird')

pipex = 345
pipe1y = -270
pipe2y = 420
width = 65
height1 = 400
height2 = 3000

vel = 5
bird_x = 20
bird_y = 300
isJump = False
jumpCount = 10

class fb:
    def move():
        global pipex
        global yy
        global pipe1y
        global pipe2y
        global bird_x
        global bird_y
        pipex -= 1
        if pipex < -60:
            pipex = 345
            yy = random.randint(-350,0)
            pipe1y = yy
            pipe2y = pipe1y + 555
        pygame.draw.rect(win,(0,0,0), (0,0,1000,1000))
        pygame.draw.rect(win,(0, 255, 0), (pipex, pipe1y, width, height1))
        pygame.draw.rect(win,(0, 255, 100), (pipex, pipe2y, width, height2))
        pygame.draw.rect(win,(255,0,0),(bird_x, bird_y, 30, 30))
        pygame.display.update()
    
while True:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        bird_y += 60
    fb.move()
    time.sleep(0.005)

最佳答案

将主循环更改为:

while True:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        bird_y -= 1
    if keys[pygame.K_DOWN]:
        bird_y += 1
    fb.move()
    time.sleep(0.005)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            break

您没有测试事件 你需要处理事件

PS: 我添加了向下运动

关于python-3.x - Pygame 没有移动我在屏幕上绘制的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63947615/

相关文章:

python - 在 Linux 上使用更新版本的 Python

python - 用户需要移动鼠标来发射子弹

python - 乘以一元素矩阵

Python 和 Pygame 值正在更新,但代码未考虑更新?

python - 替换 reduce() 的功能方法

arrays - 高效堆叠和连接 NumPy 数组

python - Pygame 滚动 map 进阶

python - 如何摆脱pygame表面?

python - While 循环在语音转文本聊天机器人中未按预期工作

python - 如何让可移动图像跟随鼠标旋转