为什么我的运动在我将其放入功能后不起作用?
Why isn't my movement working after I put it in a function?
def playing():
global in_game
x = 250
y = 250
width = 10
height = 10
white = (255, 255, 255)
black = (0, 0, 0)
keys = pygame.key.get_pressed()
while in_game:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
in_game = False
if keys[pygame.K_UP]:
y -= 1
elif keys[pygame.K_DOWN]:
y += 1
elif keys[pygame.K_LEFT]:
x -= 1
elif keys[pygame.K_RIGHT]:
x += 1
win.fill(white)
pygame.draw.rect(win, black, (x, y, width, height))
pygame.display.flip()
在这段代码中,我将 x 和 y 作为水平和垂直移动。我在屏幕底部调用了我的函数。
pygame.key.get_pressed()
returns 表示键当前状态的布尔值列表。您必须在应用程序循环中连续评估键的状态,而不是在循环之前评估一次:
# keys = pygame.key.get_pressed() <----- DELETE
while in_game:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
in_game = False
keys = pygame.key.get_pressed() # <----- INSERT
if keys[pygame.K_UP]:
y -= 1
elif keys[pygame.K_DOWN]:
y += 1
elif keys[pygame.K_LEFT]:
x -= 1
elif keys[pygame.K_RIGHT]:
x += 1
# [...]
def playing():
global in_game
x = 250
y = 250
width = 10
height = 10
white = (255, 255, 255)
black = (0, 0, 0)
keys = pygame.key.get_pressed()
while in_game:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
in_game = False
if keys[pygame.K_UP]:
y -= 1
elif keys[pygame.K_DOWN]:
y += 1
elif keys[pygame.K_LEFT]:
x -= 1
elif keys[pygame.K_RIGHT]:
x += 1
win.fill(white)
pygame.draw.rect(win, black, (x, y, width, height))
pygame.display.flip()
在这段代码中,我将 x 和 y 作为水平和垂直移动。我在屏幕底部调用了我的函数。
pygame.key.get_pressed()
returns 表示键当前状态的布尔值列表。您必须在应用程序循环中连续评估键的状态,而不是在循环之前评估一次:
# keys = pygame.key.get_pressed() <----- DELETE
while in_game:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
in_game = False
keys = pygame.key.get_pressed() # <----- INSERT
if keys[pygame.K_UP]:
y -= 1
elif keys[pygame.K_DOWN]:
y += 1
elif keys[pygame.K_LEFT]:
x -= 1
elif keys[pygame.K_RIGHT]:
x += 1
# [...]