Reputation: 11
For example I have two files:
main
contains the game and menu
contains a play button which to click to start the game.
I want to link between these two files for whenever I press play button the main
starts to run without creating a new window.
I tried this:
main.py > running = False
while running:
(main.py works)
menu.py > from main import *
if click:
running = True
but it didn't worked for some reason..
Would you consider helping me out?
Upvotes: 0
Views: 1108
Reputation: 142720
You should put code in functions so later you can run main.run(screen)
to run game.
Minimal working example.
First it runs menu
with red screen and when you click then it uses main.run(screen)
to run main
with green screen. When you click again then it uses return
to go back to 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()
As you can see both code can be very similar. You could use the same code to create window with settings.py
, results.py
, etc. This way code can be simpler and later you can reuse some elements using classes.
To make it even more usefull you could dictionary config = {'screen': screen, ...}
and send it to main.run(config)
, settings.run(config)
, results.run(config)
and send it back with return config
Upvotes: 1