python - Pygame - 赋值前引用的局部变量

标签 python python-3.x pygame

我一直在努力解决一个问题: 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/

相关文章:

python - "walrus operator"赋值的多个条件

python - {1 :>2} in python programme of printing tables 的含义

python - Spark DataFrameWriter 使用 TIMESTAMP 而不是 DATETIME

python - 使用 FTPwalker 连接到 FTP 资源失败,错误代码为 "Name or service not known"

python - 在 PYGAME 中如何同时移动多个对象

python - 使用 Anaconda 安装 Pygame

python - Python 中无法解压不可迭代方法对象错误

python - AttributeError: 模块 'os' 没有属性 'chroot'

python-3.x - 带有覆盆子的数据矩阵

python - opencensus 导出商 - 一个全局或每个线程?