You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame开发Pong游戏时ball变量未定义的NameError问题求助

解决Pygame Pong游戏中ball变量NameError问题

问题描述

我正在使用Pygame开发一款Pong游戏,已将ball变量设为全局变量,但在main_loop函数中调用ball.x和ball.y时持续出现NameError(名称未定义)错误。需要在draw_screen函数中保留ball的赋值操作,求解决方法。

原代码

import pygame
width = 800 
height = 600 
player1_pos_y = 250
player2_pos_y = 250
vel_bol_x = 9
vel_bol_y = 9

def load():
    global clock
    clock = pygame.time.Clock() 

def update(dt):
    global player1_pos_y, player2_pos_y
    keys = pygame.key.get_pressed()

def draw_screen(screen):
    global ball
    screen.fill((0,0,0))
    player1 = pygame.draw.rect(screen, (255,255,255), (0, 250, 10, 100))
    player2 = pygame.draw.rect(screen, (255,255,255), (790, 250, 10, 100))    
    ball = pygame.draw.circle(screen, (255,255,255), (400,250), 10 )
    linha = pygame.draw.rect(screen, (255,255,255), (400, 0, 2, 600))

def main_loop(screen):  
    global ball, clock
    ball.x += vel_bol_x
    ball.y += vel_bol_y
    running = True
    while running:
        for e in pygame.event.get(): 
            if e.type == pygame.QUIT:
                running = False
                break

        clock.tick(60)         
        dt = clock.get_time()
        draw_screen(screen)
        update(dt)
    pygame.display.update() 

pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Exemplo de Audio")
load()
main_loop(screen)
pygame.quit()

报错信息

Exception has occurred: NameError
name 'ball' is not defined
 File "C:\Users\Antonio\Desktop\Pong T9.py", line 32, in main_loop
   ball.x += vel_bol_x
   ^^^^
 File "C:\Users\Antonio\Desktop\Pong T9.py", line 56, in <module>
   main_loop(screen)
NameError: name 'ball' is not defined

解决方案

1. 全局初始化ball变量

在所有函数之外的全局作用域添加ball的初始定义,确保main_loop访问它前变量已存在:

# 在全局变量块添加
ball = pygame.Rect(390, 240, 20, 20)  # 对应圆心(400,250)、半径10的矩形范围

2. 调整main_loop的代码逻辑与缩进

把小球位置更新的代码移到while循环内部,同时修正pygame.display.update()的缩进(必须放在循环内才能实时刷新画面):

def main_loop(screen):  
    global ball, clock
    running = True
    while running:
        for e in pygame.event.get(): 
            if e.type == pygame.QUIT:
                running = False
                break

        # 先更新小球位置,再绘制
        ball.x += vel_bol_x
        ball.y += vel_bol_y

        clock.tick(60)         
        dt = clock.get_time()
        draw_screen(screen)
        update(dt)
        pygame.display.update()  # 缩进至while循环内

3. 修改draw_screen中的ball赋值逻辑

保留draw_screen里的ball赋值,同时使用已初始化的ball.center来绘制小球,保证位置同步:

def draw_screen(screen):
    global ball
    screen.fill((0,0,0))
    player1 = pygame.draw.rect(screen, (255,255,255), (0, 250, 10, 100))
    player2 = pygame.draw.rect(screen, (255,255,255), (790, 250, 10, 100))    
    # 使用当前ball的中心位置绘制,再重新赋值ball为返回的Rect对象
    ball = pygame.draw.circle(screen, (255,255,255), ball.center, 10 )
    linha = pygame.draw.rect(screen, (255,255,255), (400, 0, 2, 600))

说明

原错误核心:main_loop在调用draw_screen前就尝试访问ball,但ball是在draw_screen中才被创建的,导致变量未定义。全局初始化ball后,变量在程序启动时就存在,后续draw_screen的赋值会更新这个全局变量的状态。

内容的提问来源于stack exchange,提问作者Khristofor Sarmento

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:10:16