我有一个Pygame的以下程序:
import pygame
import time
pygame.init()
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((600,800))
gameExit = False
x=0
y=0
w=25
h=25
class Shape:
square = pygame.draw.rect(gameDisplay,color,[x,y,w,h])
def __init__(self,color,x,y,w,h):
self.color = color
self.x = x
self.y = y
self.w = w
self.h = h
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
shape = Shape(white,x,y,w,h)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
我想用 init 初始化Shape类的square属性,但是我得到以下错误。 NameError:未定义名称“颜色”。 如何初始化square属性。
答案 0 :(得分:2)
我建议以这种方式重写代码:只需将颜色和pygame.Rect
存储在Shape
类中,并为其提供draw
方法。将主循环放在Shape
类中是没有意义的。现在,您可以根据需要创建任意数量的形状,并在while循环中绘制它们。
import sys
import pygame
pygame.init()
WHITE = pygame.Color('white')
class Shape:
def __init__(self, color, x, y, w, h):
self.color = color
self.rect = pygame.Rect(x, y, w, h)
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
def main():
game_display = pygame.display.set_mode((600, 800))
shape = Shape(WHITE, 0, 0, 25, 25)
shape2 = Shape(pygame.Color('sienna1'), 100, 100, 25, 25)
clock = pygame.time.Clock()
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
game_display.fill((40, 40, 40))
shape.draw(game_display)
shape2.draw(game_display)
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
main()
pygame.quit()
sys.exit()
作为旁注,Python中的变量名应该用snake_case
编写(带下划线的小写)。另外,使用sys.exit()
退出游戏。
答案 1 :(得分:1)
shape = Shape(white,x,y,w,h)
然后 init 方法使用您指定的参数作为该方法中的参数传递。
如果您的代码按原样编写,则您不会执行该特定行。尝试dedenting while循环,使其不在类定义中。或者,只是为了测试它,尝试通过分别运行特定行shape = Shape(white,x,y,w,h)来初始化类作为测试。
答案 2 :(得分:1)
尝试以下代码。希望这会有所帮助..
import pygame
import time
class Shape:
def __init__(self,color,x,y,w,h):
self.color = color
self.x = x
self.y = y
self.w = w
self.h = h
def draw_rect(self, gameDisplay):
square = pygame.draw.rect(gameDisplay,self.color,
[self.x,self.y,self.w,self.h]
)
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
pygame.display.update()
clock.tick(60)
def main():
pygame.init()
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((600,800))
gameExit = False
x=0
y=0
w=25
h=25
sobj = shape(white,0,0,25,25)
sobj.draw_rect(gameDisplay)
if __name__ == '__main__':
main()