作为新手。我有一个关于pygame的问题。我看到很多人只需输入颜色就可以选择颜色,比如screen.fill(white)
。这是我的代码
import pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption("Snake")
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
screen.fill(white)
pygame.display.update()
pygame.quit()
为什么它显示
NameError: name 'white' is not defined
?此外,我记得有另一种方法可以做到这一点,pygame.COLOR("white")
答案 0 :(得分:0)
您需要通过在项目开头键入来定义颜色:white=(255,255,255)
或black=(0,0,0)
。这会将变量white
和black
设置为颜色(255,255,255)
和(0,0,0)
。您看到的程序在项目中具有这些功能,否则screen.fill(white)
将无效。请参阅http://www.discoveryplayground.com/computer-programming-for-kids/rgb-colors/以获取帮助。
答案 1 :(得分:0)
如前所述,您没有定义要使用的变量'white',因为没有自动定义的颜色,尽管有预定义的颜色可以按其名称查找。您必须选择要在程序中使用的那些。
有些非常明显,您可以像这样轻松地抓住它们:
white = pygame.Color("white")
其他名称不太明显,您必须找到所需的字符串名称。我经常发现自己试图查找颜色名称,并发现此片段非常方便:
import pygame
from pprint import pprint
color_list = [ (c, v) for c, v in pygame.color.THECOLORS.items() if 'slategrey' in c]
pprint(color_list)
输出:
[('darkslategrey', (47, 79, 79, 255)),
('slategrey', (112, 128, 144, 255))
('lightslategrey', (119, 136, 153, 255))]
我在一个交互式会话中这样做,以获取所有包含“ slategrey”的名称,然后在我的实际代码中,可以这样使用我想要的名称:
slategrey = pygame.Color("slategrey")
,然后在代码中稍后像这样引用它:
screen.fill(slategrey, pygame.Rect( 0, 0, 100, 100))