使用d板移动矩形

问题描述

我试图通过使用键盘上的d-pad移动矩形来理解pygame的基本知识,但是矩形并没有移动其停留在初始位置的位置

import pygame
import sys

x1=0
y1=0
x2=100
y2=100

pygame.init()
screen=pygame.display.set_mode((288,512))
clock=pygame.time.Clock()
x = pygame.draw.rect(screen,(0,255,0),x2,y2))

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_DOWN:
               y1-=100



pygame.display.update()
clock.tick(120)

解决方法

您必须在每帧中绘制重绘整个场景。这意味着您必须清除显示,绘制矩形并在每一帧中更新显示。
此外,您还要在位置(x1,y1)处绘制矩形。使用pygame.draw.rect时,必须指定左上角的位置以及矩形的宽度和高度:

import pygame
import sys

x1,y1,w1,h1 = 0,100,100

pygame.init()
screen=pygame.display.set_mode((288,512))
clock=pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_DOWN:
               y1 += 10

    screen.fill(0)
    x = pygame.draw.rect(screen,(0,255,0),(x1,h1))
    pygame.display.update()
    clock.tick(120)