当我发送箭头键时,没有任何工作,我的正方形不会移动。这是python课程的作业,我真的需要帮助,所以谁知道为什么吗?如果有,请告诉我……请
import pygame
pygame.init()
scrlengthX = 640
scrlengthY = 480
b = 20
x = (scrlengthX-b)/2
y = (scrlengthY-b)/2
r = pygame.Rect(x,y,b,b)
#this explains where the square is supposed to be
while True:
screen = pygame.display.set_mode([scrlengthX,scrlengthY])
# size of the screen
def draw():
screen.fill([0,0,255])
r = pygame.Rect(x,y,b,b)
pygame.draw.rect(screen,(0,0,0), r)
pygame.display.flip()
a = 1
while a == 1:
draw()
e = pygame.event.get(pygame.QUIT)
print(e)
if len(e) > 0:
pygame.quit()
k = pygame.event.get(pygame.KEYDOWN)
for i in k:
if i.key == pygame.K_UP:
y = y-5
if i.key == pygame.K_DOWN:
y = y+5
if i.key == pygame.K_LEFT:
x = x-5
if i.key == pygame.K_RIGHT:
x = x+5
# button detecting, but it does not work :(
# this is where everything goes wrong, anybody help?
pygame.quit()
试试这个细微的改变:
k = pygame.event.get()
for i in k:
if i.type == pygame.KEYDOWN:
if i.key == pygame.K_UP:
y -= 5
if i.key == pygame.K_DOWN:
y += 5
if i.key == pygame.K_LEFT:
x -= 5
if i.key == pygame.K_RIGHT:
x += 5
你可能搞砸了缩进吗?
据我所知,你的程序只会在退出时离开while a==1
循环,但是所有的输入处理都在循环后面。
我认为,您可能想要增加从k=...
行开始的代码的缩进。
修改后,代码就可以为我工作了。