我一直在努力解决一个问题: gameLoop() 中的“赋值前引用的局部变量‘snake’”。 当我按下一个键来移动蛇时,它会弹出......我不知道如何解决它 - 我认为“全局蛇”就足够了。如果您有任何解决方案,请告诉我 - 提前非常感谢! :)
import pygame
import sys
black = (0, 0, 0)
white = (255, 255, 255)
def displayElements():
global snake
snake = pygame.Rect(360, 200, 30, 10)
pygame.draw.rect(screen, white, snake)
def gameSetup():
global screen, window, fps, step
pygame.init()
screen = pygame.display.set_mode((720, 400))
window = screen.get_rect()
pygame.key.set_repeat(15, 15)
fps = pygame.time.Clock()
step = 5
displayElements()
def gameLoop():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake = snake.move(0,-step)
if event.key == pygame.K_DOWN:
snake = snake.move(0,step)
fps.tick(120)
pygame.display.flip()
def main():
gameSetup()
gameLoop()
main()
最佳答案
global Snake
只是告诉 displayElements()
在全局命名空间中使用 snake
。
不过,没有任何东西告诉 gameLoop()
在全局命名空间中查找蛇。
通常,您不应使用全局
。此规则很少有异常(exception),这绝对不是这些异常(exception)之一 - 您应该重写此规则以将引用传入和传出函数。例如,类似这样的事情。
def displayElements():
snake = pygame.Rect(360, 200, 30, 10)
pygame.draw.rect(screen, white, snake)
return snake
def gameSetup():
...
return displayElements()
def gameLoop(snake):
...
def main():
snake = gameSetup()
gameLoop(snake)
关于python - Pygame - 赋值前引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697852/