Skip to content

Commit 487353e

Browse files
committed
feat(entity, map, main): add type hints, improve loading messages, and enhance map speed control
1 parent 34e8835 commit 487353e

File tree

3 files changed

+40
-20
lines changed

3 files changed

+40
-20
lines changed

core/entity.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def __loadJSON(self) -> bool: # Chargement des entités depuis le dossier "entit
2828
except(Exception):
2929
return(False)
3030

31-
def __build(self, coord) -> dict[str, str]: # Build with relative position
31+
def __build(self, coord: tuple[int]) -> dict[str, str]: # Build with relative position
3232
entities = dict[str, str](self.__entities)
3333

3434
for name in entities:
@@ -41,5 +41,5 @@ def __build(self, coord) -> dict[str, str]: # Build with relative position
4141
def getEntitiesName(self) -> list[str]:
4242
return([ str(e) for e in self.__entities ])
4343

44-
def get(self, name, coord = (5, 5)) -> str: # Récupération d'une entité
44+
def get(self, name: str, coord: tuple[int] = (5, 5)) -> str: # Récupération d'une entité
4545
return(self.__build(coord)[name])

core/map.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(self, mapName: str = "world"): # Fichier de chargement par défaut:
5050
self.__cells = int(self.__dims[0]*self.__dims[1])
5151
self.__map = list[list[int]]([])
5252
self.__iterations = int(0)
53-
self.__sleep = float(.03)
53+
self.__sleep = float(.0625)
5454
self.mapName = str(mapName)
5555
self.loaded = bool(self.__loadJSON())
5656
self.helper = bool(True)
@@ -79,7 +79,8 @@ def __saveJSON(self) -> bool: # Sauvegarde dans un fichier
7979
return(False)
8080

8181
def __decreaseSpeed(self) -> None:
82-
self.__sleep *= 2
82+
if(self.__sleep < 2):
83+
self.__sleep *= 2
8384

8485
def __increaseSpeed(self) -> None:
8586
if(self.__sleep > .001):
@@ -117,7 +118,7 @@ def __update(self) -> None: # Mise à jour de la map
117118

118119
self.__map = map
119120

120-
def addCells(self, cells) -> bool: # Ajout de cellule(s) active(s)
121+
def addCells(self, cells: list[tuple[int]]) -> bool: # Ajout de cellule(s) active(s)
121122
for cell in cells:
122123
self.__map[int(cell[0])-1][int(cell[1])-1] = 1
123124

@@ -139,15 +140,13 @@ def display(self) -> bool: # Affichage de la map avec/sans les statistiques
139140
if(bool(self.helper)):
140141
_ = int(12)
141142
help = (
142-
f"{Colors.yellow}{'Space':<{_}}{Colors.end}: {'Pause/Resume':<{13}}",
143-
f"{Colors.yellow}{'Up/Down':<{_}}{Colors.end}: {'Speed up/Slow down':<{19}}",
144-
f"{Colors.red}{'Esc':<{_}}{Colors.end}: {'Exit':<{5}}",
145-
)[::-1]
143+
f"{Colors.red}{'Esc (Q)':<{_}}{Colors.end}: {'Exit':<{5}}",
144+
f"{Colors.yellow}{'Space (P)':<{_}}{Colors.end}: {'Pause/Resume':<{13}}",
145+
f"{Colors.yellow}{'(U)p/(D)own':<{_}}{Colors.end}: {'Speed up/Slow down':<{19}}"
146+
)
146147

147148
for i, line in enumerate(self.__map):
148-
row = ""
149-
for value in line:
150-
row += f'{f"{Colors.green}O" if(value) else f"{Colors.cyan}."}{Colors.end} '
149+
row = "".join([ f"{f'{Colors.green}O' if(v) else f'{Colors.cyan}.'}{Colors.end} " for v in line ])
151150

152151
if(bool(self.stats) and (i < len(stats))): # Affichage des statistiques
153152
row += f" {stats[i]}"
@@ -159,9 +158,9 @@ def display(self) -> bool: # Affichage de la map avec/sans les statistiques
159158

160159
return(True)
161160

162-
def initMap(self, x, y) -> bool: # Initialisation de la map dans l'objet
163-
self.__map = list(self.__makeMap((int(x), int(y))))
164-
self.__dims = tuple((int(x), int(y)))
161+
def initMap(self, x: int, y: int) -> bool: # Initialisation de la map dans l'objet
162+
self.__map = list[list[int]](self.__makeMap((int(x), int(y))))
163+
self.__dims = tuple[int]((int(x), int(y)))
165164
self.__cells = int(self.__dims[0]*self.__dims[1])
166165

167166
return(self.__saveJSON())
@@ -176,7 +175,7 @@ def reset(self) -> bool: # Reset complet de toute la map
176175
def start(self) -> bool: # Lancement du jeu
177176
if(SYSTEM == "Windows"):
178177
_keyPressed = [ False ]
179-
_hook = on_press(lambda e:self.__onKeyPress(_keyPressed))
178+
_hook = on_press(lambda _:self.__onKeyPress(_keyPressed))
180179

181180
shell(CMD_CLEAR)
182181

@@ -224,7 +223,7 @@ def start(self) -> bool: # Lancement du jeu
224223
self.__decreaseSpeed()
225224

226225
except(KeyboardInterrupt):
227-
self.__label(f"STOP", Colors.red)
226+
self.__label(f"STOPPED", Colors.red)
228227

229228
if(self.__saveJSON()):
230229
print(f"{Icons.succ}{self.mapName.capitalize()}{' saved !':<{self.__dims[1]-len(self.mapName)}}")

main.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
#!/usr/bin/python3
22
# -*- coding: utf-8 -*-
33

4-
from os import system as shell
4+
from os import listdir, system as shell
5+
from os.path import abspath, dirname
56
from sys import argv, version_info
67

78
# Importation des dépendances internes
@@ -26,6 +27,7 @@ def errMsg() -> bool:
2627
(("-A", "--add-entity"), "<mapName> <type> <x> <y>"),
2728
(("-d", "--display"), "<mapName>"),
2829
(("-n", "--new"), "<mapName> <x> <y>"),
30+
(("-l", "--list"), ""),
2931
(("-r", "--reset"), "<mapName>"),
3032
(("-s", "--start"), "<mapName>"),
3133
(("-h", "--help"), ""),
@@ -36,6 +38,7 @@ def errMsg() -> bool:
3638
"Insert an entity",
3739
"Display the saved map",
3840
"Create a new map",
41+
"List all saved map",
3942
"Reset a map",
4043
"Play a map\n",
4144
"Display the help menu",
@@ -55,9 +58,19 @@ def errMsg() -> bool:
5558
elif(argv[1] in args["prefix"][-1][0]):
5659
print(" conwayGameOfLife.py 2.3 - Florian Cardinal\n")
5760

61+
elif(argv[1] in args["prefix"][4][0]):
62+
saves = [ s.split(".")[0] for s in listdir(f"{abspath(dirname(__file__))}/saves/") ]
63+
64+
output = [ "Saved map:\n" ]
65+
for i, save in enumerate(saves, 1):
66+
output.append(f" {' '*(2-len(str(i)))}{i}. {save}")
67+
68+
print("\n".join(output), end="\n"*2)
69+
5870
if(
5971
not (argv[1] in args["prefix"][-2][0])
6072
and not (argv[1] in args["prefix"][-1][0])
73+
and not (argv[1] in args["prefix"][4][0])
6174
):
6275
try:
6376
map = Map(str(argv[2]))
@@ -126,7 +139,7 @@ def errMsg() -> bool:
126139
print(f"{Icons.warn}Specify the <x> and <y> dimensions")
127140
return(False)
128141

129-
elif(argv[1] in args["prefix"][4][0]):
142+
elif(argv[1] in args["prefix"][5][0]):
130143
if(map.loaded):
131144
map.reset()
132145
shell(CMD_CLEAR)
@@ -135,7 +148,7 @@ def errMsg() -> bool:
135148
else:
136149
return(errMsg())
137150

138-
elif(argv[1] in args["prefix"][5][0]):
151+
elif(argv[1] in args["prefix"][6][0]):
139152
if(map.loaded):
140153
map.start()
141154

@@ -145,6 +158,14 @@ def errMsg() -> bool:
145158
return(True)
146159

147160
def main() -> bool: # Fonction principale de l'execution du programme
161+
saves = [ s.split(".")[0] for s in listdir(f"{abspath(dirname(__file__))}/saves/") ]
162+
163+
output = [ "Saved map:\n" ]
164+
for i, save in enumerate(saves, 1):
165+
output.append(f" {' '*(2-len(str(i)))}{i}. {save}")
166+
167+
print("\n".join(output), end="\n"*2)
168+
148169
map = Map(str(input(f"Enter a map name to load: {Colors.green}")))
149170
print(Colors.end)
150171

0 commit comments

Comments
 (0)