Skip to content

Commit 1d3c75f

Browse files
authored
Merge pull request mouredev#5670 from Kenysdev/33.py
mouredev#33 - python
2 parents 81aab50 + 9500194 commit 1d3c75f

File tree

1 file changed

+198
-0
lines changed

1 file changed

+198
-0
lines changed
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
# ╔═════════════════════════════════════╗
2+
# ║ Autor: Kenys Alvarado ║
3+
# ║ GitHub: https://github.com/Kenysdev ║
4+
# ║ 2024 - Python ║
5+
# ╚═════════════════════════════════════╝
6+
7+
# ---------------------------------------
8+
# 32 * RESCATANDO A MICKEY
9+
# ---------------------------------------
10+
"""
11+
* EJERCICIO:
12+
* ¡Disney ha presentado un montón de novedades en su D23!
13+
* Pero... ¿Dónde está Mickey?
14+
* Mickey Mouse ha quedado atrapado en un laberinto mágico
15+
* creado por Maléfica.
16+
* Desarrolla un programa para ayudarlo a escapar.
17+
* Requisitos:
18+
* 1. El laberinto está formado por un cuadrado de 6x6 celdas.
19+
* 2. Los valores de las celdas serán:
20+
* - ⬜️ Vacío
21+
* - ⬛️ Obstáculo
22+
* - 🐭 Mickey
23+
* - 🚪 Salida
24+
* Acciones:
25+
* 1. Crea una matriz que represente el laberinto (no hace falta
26+
* que se genere de manera automática).
27+
* 2. Interactúa con el usuario por consola para preguntarle hacia
28+
* donde se tiene que desplazar (arriba, abajo, izquierda o derecha).
29+
* 3. Muestra la actualización del laberinto tras cada desplazamiento.
30+
* 4. Valida todos los movimientos, teniendo en cuenta los límites
31+
* del laberinto y los obtáculos. Notifica al usuario.
32+
* 5. Finaliza el programa cuando Mickey llegue a la salida.
33+
"""
34+
35+
from typing import List, Dict, Tuple
36+
import random
37+
38+
# ________________________
39+
class Moves:
40+
def __init__(self, config: Dict[str, str], ref_matrix: List[List[int]]) -> None:
41+
self._config = config
42+
self._maze: List[List[int]] = ref_matrix
43+
self._position: Tuple[int, int] = (0, 0)
44+
self._exit: Tuple[int, int] = (0, 0)
45+
46+
def print_maze(self) -> None:
47+
print("--------------------------------------")
48+
for row in self._maze:
49+
print("".join(row))
50+
print("--------------------------------------")
51+
52+
def _can_move(self, y: int, x: int) -> bool:
53+
size: int = len(self._maze)
54+
if y < 0 or x < 0 or y >= size or x >= size:
55+
print("🚨I can't jump over the edges.🚨")
56+
return False
57+
58+
if self._maze[y][x] == self._config["obstacle"]:
59+
print("🚨You pushed me against the wall.🚨")
60+
return False
61+
62+
self._position = (y, x)
63+
print("✅Correct move.✅")
64+
self._maze[y][x] = config["mouse"]
65+
return True
66+
67+
def up(self) -> None:
68+
y, x = self._position
69+
if not self._can_move(y - 1, x):
70+
return None
71+
self._maze[y][x] = self._config["empty"]
72+
73+
def down(self) -> None:
74+
y, x = self._position
75+
if not self._can_move(y + 1, x):
76+
return None
77+
self._maze[y][x] = self._config["empty"]
78+
79+
def right(self) -> None:
80+
y, x = self._position
81+
if not self._can_move(y, x + 1):
82+
return None
83+
self._maze[y][x] = self._config["empty"]
84+
85+
def left(self) -> None:
86+
y, x = self._position
87+
if not self._can_move(y, x - 1):
88+
return None
89+
self._maze[y][x] = self._config["empty"]
90+
91+
# ________________________
92+
class Maze(Moves):
93+
def __init__(self, config: Dict[str, str], ref_matrix: List[List[int]]) -> None:
94+
super().__init__(config, ref_matrix)
95+
96+
def _create_paths(self, x, y, width, height):
97+
maze: List[List[int]] = self._maze
98+
obstacle = self._config["obstacle"]
99+
empyte = self._config["empty"]
100+
101+
maze[y][x] = empyte
102+
for dx, dy in random.sample([(0, 1), (1, 0), (0, -1), (-1, 0)], 4):
103+
nx, ny = x + dx * 2, y + dy * 2
104+
if 0 < nx < width - 1 and 0 < ny < height - 1 and maze[ny][nx] == obstacle:
105+
maze[y + dy][x + dx] = empyte
106+
self._create_paths(nx, ny, width, height)
107+
108+
def create(self) -> None:
109+
width = self._config["size"][0]
110+
height = self._config["size"][1]
111+
obstacle = self._config["obstacle"]
112+
113+
if not width % 2: width += 1
114+
if not height % 2: height += 1
115+
self._maze = [[obstacle] * width for _ in range(height)]
116+
117+
initial_x = random.randrange(1, width - 1, 2)
118+
initial_y = random.randrange(1, height - 1, 2)
119+
self._create_paths(initial_x, initial_y, width, height)
120+
121+
self._maze[0][1] = self._config["mouse"]
122+
self._maze[height - 1][width - 2] = self._config["exit"]
123+
self._position = (0, 1)
124+
self._exit = (height - 1, width - 2)
125+
126+
def veify_win(self) -> bool:
127+
y, x = self._exit
128+
if self._maze[y][x] == self._config["mouse"]:
129+
return True
130+
return False
131+
132+
# ________________________
133+
class Game:
134+
def __init__(self, config: Dict[str, str], instance_Maze) -> None:
135+
self._config: dict = config
136+
self._maze = instance_Maze
137+
138+
def _restart_or_exit(self) -> bool:
139+
while True:
140+
option: str = (input("Y/N: ")).lower()
141+
match option:
142+
case 'y': return True
143+
case 'n': return False
144+
case _ : print("❌Invalid key.❌")
145+
146+
def play(self):
147+
for k, v in self._config.items():
148+
print(f"{k}: {v}")
149+
150+
self._maze.create()
151+
while True:
152+
self._maze.print_maze()
153+
print("Use the keys: (W, S, A, D).\nTo restart: R. To exit: 9.")
154+
option: str = (input("\nTecla: ")).lower()
155+
match option:
156+
case 'w': self._maze.up()
157+
case 's': self._maze.down()
158+
case 'd': self._maze.right()
159+
case 'a': self._maze.left()
160+
case 'r':
161+
print("😮Do you want to restart?😮")
162+
if self._restart_or_exit():
163+
self._maze.create()
164+
165+
case '9':
166+
print("😮Do you want to exit?😮")
167+
if self._restart_or_exit():
168+
break
169+
170+
case _ : print("❌Invalid key.❌")
171+
172+
if self._maze.veify_win():
173+
print("🏆Congratulations, you managed to get me out.🏆")
174+
print("🤔Do you want to play again?🤔")
175+
if self._restart_or_exit():
176+
self._maze.create()
177+
else:
178+
print("Bye")
179+
break
180+
181+
# ________________________
182+
if __name__ == "__main__":
183+
# These are the default values. You can change them here.
184+
config: Dict[str, str] = {
185+
"title": "RESCUING MICKEY",
186+
"size": (6, 6),
187+
"empty": "⬜️",
188+
"obstacle": "⬛️",
189+
"mouse": "🐭",
190+
"exit": "🚪"
191+
}
192+
193+
ref_maze_matrix: List[List[int]] = []
194+
195+
_maze = Maze(config, ref_maze_matrix)
196+
_game = Game(config, _maze)
197+
_game.play()
198+

0 commit comments

Comments
 (0)