Skip to content

Commit

Permalink
Merge pull request #5872 from KevinED11/main
Browse files Browse the repository at this point in the history
reto #45 - python
  • Loading branch information
kontroldev authored Nov 26, 2023
2 parents 54bf055 + c187a6d commit 0921ba2
Show file tree
Hide file tree
Showing 2 changed files with 249 additions and 0 deletions.
127 changes: 127 additions & 0 deletions Retos/Reto #44 - ADIVINANZAS MATEMÁTICAS [Media]/python/KevinED11.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from typing import Protocol, Iterable
import time
import functools
import random
import dataclasses


type Number = float | int


def pause_game(seconds: Number = 3) -> None:
time.sleep(seconds)


pause_game_by_3_seconds = functools.partial(pause_game, seconds=3)


class MathOperationFn(Protocol[Number]):
def __call__[T: Number](self, a: T, b: T) -> T:
...


def add[T: Number](a: T, b: T) -> T:
return a + b


def subtract[T: Number](a: T, b: T) -> T:
return a - b


def multiply[T: Number](a: T, b: T) -> T:
return a * b


def divide[T: Number](a: T, b: T) -> T:
try:
return a / b
except ZeroDivisionError as err:
print(f"No se puede dividir por cero: {err}")


@functools.lru_cache
def math_operations() -> list[MathOperationFn]:
return [add, subtract, multiply, divide]


class MathOPerationSelectorStrategyFn(Protocol):
def __call__(self, operations: Iterable[MathOperationFn]) -> MathOperationFn:
...


def math_operation_random_selector(
operations: Iterable[MathOperationFn],
) -> MathOperationFn:
return random.choice(operations)


class IGame(Protocol):
def play(self) -> None:
...


class GameNotRunningExeption(Exception):
pass


class GameAlreadyRunningExeption(Exception):
pass


class MathRiddleGame:
def __init__(self, selector_strategy: MathOPerationSelectorStrategyFn) -> None:
self.selector_strategy = selector_strategy
self.__runnning = False
self.__score = 0

def __request_answer(self) -> str:
user_input = input("Ingrese la respuesta: ")

def __pause_game(self) -> str | None:
while True:
user_input = input("Presione enter para continuar")
if user_input == "":
break

def __choice_operation(self) -> MathOperationFn:
return self.selector_strategy()

def __stop_game(self) -> None:
if not self.__runnning:
raise GameNotRunningExeption("El juego no está corriendo")

self.__runnning = False
print("El juego ha finalizado")

def __show_score(self) -> None:
print(f"Tu puntuación es: {self.__score} aciertos")

def __prepare_game(self) -> None:
while True:
operation = self.__choice_operation()
user_input = self.__request_question()
self.__stop_game()
self.__show_score()

self.__show_score()
self.__stop_game()

def play(self) -> None:
if self.__runnning:
raise GameAlreadyRunningError("El juego ya está corriendo")

self.__runnning = True
self.__prepare_game()


def main(game: IGame) -> None:
try:
game.play()
except (GameAlreadyRunningError, GameNotRunningExeption) as err:
print(err)


if __name__ == "__main__":
selector_strategy = math_operation_random_selector
game = MathRiddleGame(selector_strategy=selector_strategy)
main(game=game)
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
from dataclasses import dataclass, field
from typing import Protocol
from random import randint
import time


class ParticipationMecanism(Protocol):
participants: list[str] = []
running: bool = False

def add(self, participant: str) -> None:
...

def delete(self, participant: str) -> None:
...

def show(self) -> None:
...

def run_giveaway(self) -> str:
...

def run(self) -> None:
...


def user_input(prompt: str) -> str:
return input(prompt).lower()


@dataclass
class AdevientoParticipationMecanism:
participants: list[str] = field(default_factory=list)
running: bool = field(default=False)

def add(self, participant: str) -> None:
if participant in self.participants:
print(f"El participante '{participant}' ya existe en la lista.")
return

self.participants += [participant]
print(f"El participante '{participant}' ha sido añadido con éxito.")

def delete(self, participant: str) -> None:
if participant not in self.participants:
print(f"El participante '{participant}' no existe en la lista.")
return

print(f"El participante '{participant}' ha sido eliminado con éxito.")
self.participants.remove(participant)

def show(self) -> None:
print("Lista de participantes:")
if not self.participants:
print("No hay participantes registrados.")
return

for participant in self.participants:
print(participant)

def run_giveaway(self) -> str:
time.sleep(3)
giveaway_winner = self.participants[randint(0, len(self.participants) - 1)]

self.delete(giveaway_winner)
print(f"El ganador del sorteo es: {giveaway_winner}")
return giveaway_winner

def get_options(self) -> dict[str, callable]:
add_option = lambda: self.add(
user_input("Introduce el nombre del participante a añadir: ")
)
delete_option = lambda: self.delete(
user_input("Introduce el nombre del participante a eliminar: ")
)
return {
"1": add_option,
"2": delete_option,
"3": self.show,
"4": self.run_giveaway,
"5": self.exit,
}

def run(self) -> None:
self.running = True
options = self.get_options()
while self.running:
print(
"1. Añadir participante, 2. Eliminar participante, 3. Mostrar participantes, 4. Realizar sorteo, 5. Salir"
)
option = user_input("Opcion: ")
if option not in options:
print("Opcion no valida")
continue

result = options[option]()
if isinstance(result, bool) and result:
self.running = False
break

def exit(self) -> bool:
self.running = False
print("¡Que tengas un buen dia, hasta luego!")
return True


@dataclass
class Program:
participation_mechanism: ParticipationMecanism

def run(self) -> None:
self.participation_mechanism.run()


def main(participation_mechanism: ParticipationMecanism) -> None:
program = Program(participation_mechanism=participation_mechanism)
program.run()


if __name__ == "__main__":
participation_mechanism = AdevientoParticipationMecanism()
main(participation_mechanism=participation_mechanism)

0 comments on commit 0921ba2

Please sign in to comment.