Python - Pygame名称错误:名称'display_s'未定义。 (错误?)+如何从内部“范围” GET变量
问题描述:
最近开始在pygame的项目工作,以及跨越这个错误传来:Python - Pygame名称错误:名称'display_s'未定义。 (错误?)+如何从内部“范围” GET变量
Traceback (most recent call last):
File "GameTesting.py", line 50, in <module>
screen.blit(display_s, (space_ship_rect.centerx, space_ship_rect.centery))
NameError: name 'display_s' is not defined
它的大部分弹出的时间,但事情是有时候它并没有拿出一个错误,并且运行完全正常,下面的代码:(我评论说是很重要的这个线程的部分)
import sys, pygame, math, time;
from pygame.locals import *;
spaceship = ('spaceship.png')
mouse_c = ('crosshair.png')
backg = ('background.jpg')
fire_beam = ('beams.png')
pygame.init()
screen = pygame.display.set_mode((800, 600))
bk = pygame.image.load(backg).convert_alpha()
mousec = pygame.image.load(mouse_c).convert_alpha()
space_ship = pygame.image.load(spaceship).convert_alpha()
f_beam = pygame.image.load(fire_beam).convert_alpha()
f_beam = pygame.transform.scale(f_beam, (50, 50))
f_beam_rect = f_beam.get_rect()
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
space_ship_rect = space_ship.get_rect()
space_ship_rect.centerx = 375
space_ship_rect.centery = 300
speed = 3.5
pressed_down = 0
while True:
clock.tick(60)
screen.blit(bk, (0, 0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
global movex
global movey
global degs #HERE is where I need movex, movey, degs from below..
#This probably won't work, don't even know what global does...
elif event.type == MOUSEBUTTONDOWN and event.button == 3:
pressed_down = 1
elif event.type == MOUSEBUTTONUP:
pressed_down = 0
if pressed_down == 1:
x, y = pygame.mouse.get_pos()
x1, y1 = x - space_ship_rect.x, y - space_ship_rect.y
angle = math.atan2(y1, x1)
dx = speed*math.cos(angle)
dy = speed*math.sin(angle)
movex = space_ship_rect.centerx = space_ship_rect.centerx + dx
movey = space_ship_rect.centery = space_ship_rect.centery + dy
if event.type == MOUSEMOTION:
x1, y1 = pygame.mouse.get_pos()
x2, y2 = space_ship_rect.x, space_ship_rect.y
dx, dy = x2 - x1, y2 - y1
rads = math.atan2(dx, dy)
degs = math.degrees(rads)
display_s = pygame.transform.rotate(space_ship, (degs)) #ERROR HERE
screen.blit(display_s, (space_ship_rect.centerx, space_ship_rect.centery))#ERROR HERE
pos = pygame.mouse.get_pos()
screen.blit(mousec, (pos))
pygame.display.update()
答
几率是不是,当你触发它不是有错误event.type == MOUSEMOTION
- 因为display_s
被定义。
如果在游戏运行的第一个刻度中移动鼠标,则会初始化display_s
,因此您不会收到错误。如果您不移动鼠标,则会发生错误。
一种解决方案是在初始级别加载代码中为display_s
创建默认值。
为什么你遇到很多麻烦可能是由你的代码结构造成的,或者是由于它的缺乏。
尝试refactoring你的代码,我喜欢让我的游戏循环类似于:
def main():
load()
while(playing == True):
handle_input()
update()
draw()
unload()