<p>确保将主代码放入函数中。接下来创建另一个保留主菜单屏幕的函数。启动游戏时,请调用主菜单屏幕,并确保其上包含一个调用游戏主功能的按钮</p>
<p>我给你我下面使用的按钮类</p>
<pre><code>class Button():
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw(self, win, outline=None):
# Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 20)
text = font.render(self.text, 1, (0, 0, 0))
win.blit(text, (
self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))
</code></pre>
<p>接下来创建一个主菜单,如下所示</p>
<pre><code> def main_menu():
setDefaults()
pygame.display.set_caption("Main Menu")
run = True
bright_green = (0, 255, 0)
green = (0, 200, 0)
screen.fill((163, 163, 194))
</code></pre>
<p>Set defaults是一个将所有值转换为原始值的函数。在这个基本的主菜单之后,请确保使用我之前提供给您的按钮类添加一个按钮,并将其链接到您的主功能或执行此操作</p>
<pre><code> while run:
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
run = False
if 400 + 100 > mouse[0] > 400 and 275 + 50 > mouse[1] > 275:
pygame.draw.rect(screen, bright_green, (400, 275, 100, 50))
if event.type == pygame.MOUSEBUTTONDOWN:
main()
else:
pygame.draw.rect(screen, green, (400, 275, 100, 50))
</code></pre>
<p>另外,当您的健康状况降至0以下(或任何其他情况)时,请务必调用主菜单。
希望这有帮助</p>
<p>编辑
要将整个代码放入函数中,请执行以下操作</p>
<pre><code>def main_loop():
global dependencies for edits
while running:
....your code...
</code></pre>
<p>编辑2</p>
<p>下面是我的主菜单,请根据需要更改变量。还要确保用<code>maingameloop</code>函数替换<code>main()</code></p>
<pre><code>def main_menu():
setDefaults()
pygame.display.set_caption("Main Menu")
run = True
bright_green = (0, 255, 0)
green = (0, 200, 0)
screen.fill((163, 163, 194))
# pygame.mixer.music.load('background_music_wav.wav')
# pygame.mixer.music.play(-1)
while run:
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
run = False
if 400 + 100 > mouse[0] > 400 and 275 + 50 > mouse[1] > 275:
pygame.draw.rect(screen, bright_green, (400, 275, 100, 50))
if event.type == pygame.MOUSEBUTTONDOWN:
main()
else:
pygame.draw.rect(screen, green, (400, 275, 100, 50))
screen.blit(font_large.render("Game-Name", True, (255, 255, 255)), (325, 50))
screen.blit(font.render("Play", True, (0, 0, 0)), (417, 285))
pygame.display.flip()
clock.tick(FPS)
main_menu()
</code></pre>