问题描述
我正在上 Python 初学者课程,我们正在做我们的最终项目。然而,对于我的游戏,我希望能够重新启动游戏本身。我通过使用导入来启动一个新脚本然后重新运行我的游戏来做到这一点。但是,每当我尝试多次执行此操作时,我的窗口都会中断,或者代码不会导入下一个文件。我的游戏有点长,所以我创建了一个很短的程序来举例说明我的问题。
(这是文件 yin.py)
import pygame
BLACK = (0,0)
pygame.init()
SIZE = [300,300]
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
import yang
done = True
screen.fill(BLACK)
pygame.display.flip()
clock.tick(30)
pygame.quit()
(和这个文件 yang.py)
import pygame
WHITE = (255,255,255)
pygame.init()
SIZE = [300,300]
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
import yin
done = True
screen.fill(WHITE)
pygame.display.flip()
clock.tick(30)
pygame.quit()
我尝试过做多件事,但到目前为止我一无所获,即使我有“pygame.init()”,它仍然给我显示未初始化。我的老师没有回复我的电子邮件,而且我的截止日期越来越紧迫。任何帮助将不胜感激。 :p
解决方法
“import”语句只导入一次。如果名称已存在,则不会再次导入。您应该将代码放入一个函数中。然后,您可以根据需要多次调用该函数。