0

Using IDLE, I have written an interactive python program using pygame and saved it as file Songboard01.py. I use IDLE's run command or f5 to run the script. The user responds initially to the IDLE shell, which asks a startup question, after which all the responses are mouse clicks on the pygame screen. In addition to game play, the screen allows the user to click on alternatives such as (1) 'Quit', (2) 'Instructions', (3) 'Credits', (4) 'Solutions', and (5) 'Play again'. The first three work fine, and the game is able to pick up without a problem after (2) or (3). It is 'Play again' that has me stumped.

This function:

def new_game(): done = True # closes pygame while-loop pygame.quit() import Songboard01.py 

will start the game over with the startup question in the IDLE shell, but it only works once. If the user tries to get a new game a second time, the error message ends:

File "/Users/anobium/Desktop/SongBoard/Songboard01.py", line 314, in new_game import Songboard01.py ModuleNotFoundError: No module named 'Songboard01.py'; 'Songboard01' is not a package

1

1 Answer 1

0

A python program cannot import itself, and using the import function will raise an error. Also, you shouldn't put a ".py" at the end of a package name. I recommend putting your main game loop and putting a break if the user chooses (1), (2), (3), or (4). Put a continue if the user chooses (5). Your game will go back to the start if the user chooses (5).

Sample code:

#do your imports import pygame #and all other needed modules #Make classes or setup the game while True: #Do all of the game stuff #Ok now make the buttons #if button = 1 or 2 or 3 or 4: break #else if button = 5: continue 
Sign up to request clarification or add additional context in comments.

7 Comments

Explain to me, or point me to the explanation, how a python program imports itself once, but not twice.
self importing will work, but you put a .py at the end of Songboard01. Also, you cannot import a file with numbers in it's name, so you should rename. Then the code would work.
The function new_game(), defined here, imports SongboardOne once and only once: def new_game():
To Math Coder 101: when I replace 'Songboard01.py' by 'SongboardOne' in the function new_game() above, I am still able to import once, but only once.
To Math Coder 101: I'm using Python3 (with IDLE) on a MacBook Pro, OS X 10.14.6. Are you using Windows?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.