我一直在努力解决一个问题: gameLoop() 中的“ Local variable 'snake' referenced before assignment ” . 当我按下一把钥匙移动蛇时,它弹出......我不知道如何解决它 - 我认为"global 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()
1 回答
global snake
只是告诉displayElements()
在全局命名空间中使用snake
.但是,没有什么能告诉
gameLoop()
在全局命名空间中寻找蛇 .通常,您不应该使用
global
. 这个规则很少有例外,这绝对不是其中一个例外 - 你应该重写它来传入和传出函数 . 例如,像这样的东西 .