我正在关注有关YouTube的教程,该教程导致在白色背景上显示红色斑点/圆点。我只得到黑屏,而不是预期的结果。
我尝试在代码中找到任何错误,但找不到任何错误。当我运行代码时,会看到一个带有黑色背景的窗口,上面没有任何内容。唯一起作用的代码是退出按钮。我认为,如果脚本的那部分工作正常,那么所有工作都会正常工作,但我想我仍然很困惑。帮助将不胜感激。
这是我的代码:
import pygame
import random
width = 800
height = 600
white = (255,255,255)
red = (255,0,0)
blue = (0,0,255)
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("2D Blob world")
clock = pygame.time.Clock()
class blob:
def __init__(self, color):
self.x = random.randrange(0,width)
self.y = random.randrange(0,height)
self.size = random.randrange(5,10)
self.color = color
def move(self):
self.x += random.randrange(-5,5)
self.y += random.randrange(-5,5)
if self.x >width:
self.x = width
elif self.x <0:
self.x = 0
if self.y >height:
self.y = height
elif self.y <0:
self.y = 0
def draw_environment(blob):
game_display.fill((white))
pygame.draw.circle(game_display, blob.color,(blob.x, blob.y), blob.size)
pygame.display.update()
def main():
red_blob = blob(red)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw_environment(red_blob)
clock.tick(60)
if __name__ == '__main__':
main()
draw_environment(red_blob)
其结果将是在白色背景上出现一个红点。
答案 0 :(得分:0)
以上代码的问题在main方法的定义内。您正在创建blob对象,然后进入无限循环,而不是先绘制环境。 要解决此问题,您需要将draw_environment(red_blob)从第48行移动到第41行之后,以便您的主要方法如下:
def main():
red_blob = blob(red)
draw_environment(red_blob)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
clock.tick(60)
您可能还需要根据需要将clock.tick(60)方法移动到上方。