-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainMenu.py
More file actions
101 lines (78 loc) · 3.22 KB
/
MainMenu.py
File metadata and controls
101 lines (78 loc) · 3.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import os
import platform
from time import sleep
from utilities import getAndValidateUserInput
class MainMenu:
EXIT_FLAG = 0
NO_GAMES_FOUND_FLAG = -1
@staticmethod
def clearScreen():
if platform.system() == "Windows":
os.system("cls")
else: # Linux or Mac
os.system("clear")
def __init__(self, title):
self.gamesArray = []
self.title = title
def setTitle(self, newTitle):
if newTitle is None:
raise Exception("Title cannot be None")
self.title = newTitle
def addGame(self, gameObject):
"""" Game object must have a title and a startGame method. """
if gameObject is None:
raise Exception("Game object cannot be None")
self.gamesArray.append(gameObject)
def showGames(self):
if len(self.gamesArray) == 0:
print("No games found.")
return False
print("Choose a game: ")
for i in range(len(self.gamesArray)):
try:
print("\t", str(i + 1) + ": " + self.gamesArray[i].getTitle())
except AttributeError:
print("Game " + str(i + 1) + " has no title.")
print("\t", str(len(self.gamesArray) + 1) + ": Exit")
print()
return True
def showMenu(self):
print("==== " + self.title + " ====")
if not self.showGames():
return MainMenu.NO_GAMES_FOUND_FLAG
userChoice = int(getAndValidateUserInput([str(i + 1) for i in range(len(self.gamesArray) + 1)],
"Enter your choice: ", "Invalid choice. Please try again."))
if userChoice == len(self.gamesArray) + 1:
return MainMenu.EXIT_FLAG
try:
print("You chose: " + self.gamesArray[userChoice - 1].getTitle())
print("Starting game...")
print("\n\n")
sleep(1) # wait for 1 second to let the user read the message
MainMenu.clearScreen()
self.gamesArray[userChoice - 1].startGame()
# reset the game to its initial state after it finishes
self.gamesArray[userChoice - 1].__init__(self.gamesArray[userChoice - 1].getTitle())
print("Press q to go back to the menu.")
while input().lower() != "q":
pass
MainMenu.clearScreen()
except AttributeError:
raise Exception("Game " + str(userChoice) + " has no startGame method.")
return True
def startMenuLoop(self):
while True:
# clear screen and show menu
MainMenu.clearScreen()
menuFlag = self.showMenu()
if menuFlag is MainMenu.EXIT_FLAG:
print("Exiting...")
exit(MainMenu.EXIT_FLAG)
elif menuFlag is MainMenu.NO_GAMES_FOUND_FLAG:
exit(MainMenu.NO_GAMES_FOUND_FLAG)
print("Do you want to play another game? (y/n)")
userChoice = getAndValidateUserInput(["y", "n", "Y", "N"],
"Enter your choice: ",
"Invalid choice. Please try again.")
if userChoice.lower() == "n":
break