我是学习Python的初学者,当我调试从书中复制的一系列代码时,我遇到了一个问题,我得到一个白色的屏幕窗口,而不是带有图案的窗口,这里是代码:
import pygame, sys, random
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
pygame.init()
windowWidth = 640
windowHeight = 480
surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('Pygame Shapes!')
while True:
surface.fill((200, 0, 0))
pygame.draw.rect(surface, (255, 0, 0), (random.randint(0, windowWidth), random.randint(0, windowHeight), 10, 10))
greenSquareX = windowWidth / 2
greenSquareY = windowHeight / 2
while True:
surface.fill((0, 0, 0))
pygame.draw.rect(surface, (0, 255, 0),
(greenSquareX, greenSquareY, 10, 10))
greenSquareX += 1
# greenSquareY += 1
pygame.draw.rect(surface, (0, 0, 255),
(blueSquareX, blueSquareY, 10, 10))
blueSquareX = 0.0
blueSquareY = 0.0
blueSquareVX = 1
blueSquareVy = 1
while True:
surface.fill((0, 0, 0))
pygame.draw.rect(surface, (0, 0, 255),
(blueSquareX, blueSquareY, 10, 10))
blueSquareX += blueSquareVX
blueSquareY += blueSquareVY
blueSquareVX += 0.1
blueSquareVY += 0.1
for event in GAME_EVENTS.GET():
if event.type == GAME_GLOBALS.QUIT:
pygame.quit()
sys.exit()
pygame.dispaly.update()
我得到的第一个错误是:E1101:Module 'pygame' has no 'init' member'(4 ,1)
。我以前用pygame.init()
运行了其他Python代码,结果很好;但这次我得到一个白色的窗口。我的代码出了什么问题?谢谢你的帮助!
答案 0 :(得分:3)
这需要我进行大量的调试才能修复,哈哈。
首先,您没有在任何while
循环中转义或更新。代码进入您的第一个while
循环后,在此之后没有任何内容(pygame.display
)更新 - 导致您的白屏综合症。
此外,请一致地命名变量并检查代码中的拼写错误。您创建了一个blueSquareVy
变量,以便稍后尝试将其引用为blueSquareVY
,并且您在代码末尾拼错了pygame.display.update()
。资本化很重要 - 这只是一些拼写错误!
代码中也存在逻辑错误。将图形绘制到屏幕上后,不填充窗口表面。看看你的变量,似乎你想要小方块移动。您可以在while
循环之外创建位置变量,就像在循环中创建它们一样,它们会在循环的每次迭代中以其初始值重新创建。
带注释和错误修复的代码:
import pygame, sys, random
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
pygame.init()
windowWidth = 640
windowHeight = 480
surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('Pygame Shapes!')
# Renamed variables to be consistent
# Moved variables out of the while loop
greenSquareX = windowWidth / 2
greenSquareY = windowHeight / 2
blueSquareX = 0.0
blueSquareY = 0.0
blueSquareVX = 1
blueSquareVY = 1
# Joined the two while loops into one
while True:
surface.fill((200, 0, 0))
pygame.draw.rect(surface, (255, 0, 0), (random.randint(0, windowWidth), random.randint(0, windowHeight), 10, 10))
surface.fill((0, 0, 0))
pygame.draw.rect(surface, (0, 255, 0),
(greenSquareX, greenSquareY, 10, 10))
greenSquareX += 1
greenSquareY += 1
pygame.draw.rect(surface, (0, 0, 255),
(blueSquareX, blueSquareY, 10, 10))
blueSquareX += blueSquareVX
blueSquareY += blueSquareVY
blueSquareVX += 0.1
blueSquareVY += 0.1
# Do not capitalize the .get() method for pygame.event class
for event in GAME_EVENTS.get():
if event.type == GAME_GLOBALS.QUIT:
pygame.quit()
sys.exit()
# Misspelled pygame.display
pygame.display.update()
希望这有帮助!