如何在pygame中链接菜单和主文件?

h6my8fg2  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(387)

例如,我有两个文件:
main.py
menu.py main 包含游戏和 menu 包含可单击以开始游戏的播放按钮。
每当我按下“播放”按钮时,我都想在这两个文件之间建立链接 main 在不创建新窗口的情况下开始运行。
我试过这个:

main.py > running = False
          while running:
              (main.py works)

menu.py > from main import *
          if click:
              running = True

但由于某种原因,它不起作用。。
你能帮帮我吗?

c9qzyr3d

c9qzyr3d1#

您应该将代码放入函数中,以便以后可以运行 main.run(screen) 运行游戏。
最少的工作示例。
首先它运行 menu 使用红色屏幕,当您单击时,它将使用 main.run(screen) 运行 main 带绿色屏幕。当您再次单击时,它将使用 return 回到 menu . menu.py ```
import pygame
import main

def run(screen=None):
print('[menu] run')

if not screen:
    pygame.init()
    screen = pygame.display.set_mode((800,600))

mainloop(screen)

def mainloop(screen):
print('[menu] mainloop')

running = True
while running:

    print('running menu ...')

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit() # skip rest of code
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                main.run(screen)  # run game

    screen.fill((255,0,0))
    pygame.display.flip()

if name == 'main':
run()
`main.py`
import pygame

def run(screen=None):
print('[main] run')

if not screen:
    pygame.init()
    screen = pygame.display.set_mode((800,600))

mainloop(screen)

def mainloop(screen):
print('[main] mainloop')

running = True
while running:

    print('running game ...')

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit() # skip rest of code
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                return  # go back to menu

    screen.fill((0,255,0))
    pygame.display.flip()

if name == 'main':
run()

正如您所看到的,这两个代码可能非常相似。您可以使用相同的代码创建窗口 `settings.py` ,  `results.py` 这样代码可以更简单,以后可以使用类重用某些元素。
为了使它更有用,你可以查字典 `config = {'screen': screen, ...}` 并将其发送到 `main.run(config)` ,  `settings.run(config)` ,  `results.run(config)` 并将其与 `return config` 

相关问题