pygame 个字符在按下某个键时没有移动

A pygame character isn't moving upon a key being pressed

我正在 pygame 制作游戏,虽然当我想移动我的玩家时,pygame 并没有移动角色。它正在注册一个键已被按下但没有任何反应。有人可以告诉我错误的来源并指出正确的方向。以下是我的代码。

请注意游戏尚未完全开发。

import pygame as pg, random as r, sys

pg.init()
window = pg.display.set_mode((1200, 600))
pg.display.set_caption("The Pygame Version")

White = (255, 255, 255)
Black = (0, 0, 0)
Green = (0, 255, 0)
Red = (255, 0, 0)
DarkGreen = (0, 126, 0)
def draw():
    global runner, chaser
    background = pg.draw.rect(window, Green, (0, 0, 1200, 600))
    chaser = pg.draw.rect(window, Black, (1015, 225, 150, 150))
    runner = pg.draw.rect(window, Red, (30, 225, 150, 150))
   
    track1 = pg.draw.line(window, DarkGreen, (0, 200), (1200, 200),10)
    track2 = pg.draw.line(window, DarkGreen, (0, 400), (1200, 400),10)

score = 0
font = pg.font.Font('freesansbold.ttf', 28)
scoreBoard = font.render("Score: 0", True, Black)

speed = 150
text = 0
collision = 0
draw()
while True:
    keys = pg.key.get_pressed()
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
    if keys[pg.K_w]:
        runner.y -= 200
        runner.width = 300
        draw()
        print ("We are moving")
pg.quit()

您正在以固定位置和固定大小绘制矩形:

chaser = pg.draw.rect(window, Black, (1015, 225, 150, 150))
runner = pg.draw.rect(window, Red, (30, 225, 150, 150))

请注意,pygame.draw.rect returns 一个新的矩形边界更改的像素。它实际上returnspygame.Rect(1015, 225, 150, 150)分别pygame.Rect(30, 225, 150, 150)


你必须反过来做:

创建 pygame.Rect 个对象 chaserrunner

chaser = pg.Rect(1015, 225, 150, 150)
runner = pg.Rect(30, 225, 150, 150)

并使用对象在draw中绘制矩形:

def draw():
    global runner, chaser
    pg.draw.rect(window, Green, (0, 0, 1200, 600))
    
    pg.draw.rect(window, Black, chaser)
    pg.draw.rect(window, Red, runner)

    # [...]