module 7 finished

This commit is contained in:
2026-03-05 15:21:29 +01:00
parent 516ef290a7
commit 6e6df73007
9 changed files with 232 additions and 9 deletions

15
07/ex4/Rankable.py Normal file
View File

@@ -0,0 +1,15 @@
from abc import ABC, abstractmethod
class Rankable(ABC):
@abstractmethod
def calculate_rating(self) -> int: ...
@abstractmethod
def update_wins(self, wins: int) -> None: ...
@abstractmethod
def update_losses(self, losses: int) -> None: ...
@abstractmethod
def get_rank_info(self) -> dict: ...

97
07/ex4/TournamentCard.py Normal file
View File

@@ -0,0 +1,97 @@
from ex0 import Card
from ex2 import Combatable
from .Rankable import Rankable
from typing import Union
class TournamentCard(Card, Combatable, Rankable):
def __init__(
self,
id: str,
name: str,
cost: int,
rarity: str,
damage: int,
health: int,
shield: int,
rank: int,
) -> None:
super().__init__(name, cost, rarity)
self.id = id
self.looses = 0
self.wins = 0
self.damage = damage
self.health = health
self.shield = shield
self.rank = rank
def play(self, game_state: dict) -> dict:
try:
res: dict[str, int | str] = {}
if game_state["mana"] < 2:
raise Exception("Not enough mana")
res["card_played"] = self.name
res["mana_used"] = 2
return res
except Exception as err:
print(err)
return {}
def attack(self, target: str) -> dict:
return {
"attacker": self.name,
"target": target,
"damage_dealt": self.damage,
"combat_type": "melee",
}
def defend(self, incoming_damage: int) -> dict:
res: dict[str, Union[str, int, bool]] = {}
res["defender"] = self.name
if incoming_damage <= self.shield:
res["damage_blocked"] = incoming_damage
res["damage_taken"] = 0
else:
res["damage_taken"] = incoming_damage - self.shield
res["damage_blocked"] = self.shield
self.health -= incoming_damage - self.shield
res["still_alive"] = self.health > 0
return res
def get_combate_stats(self) -> dict:
return {
"damage": self.damage,
"health": self.health,
"shield": self.shield,
}
def calculate_rating(self) -> int:
try:
if self.wins == 0:
return self.rank - self.looses * 10
return self.rank + (int(self.wins / self.looses) * 10)
except ZeroDivisionError:
return self.rank + self.wins * 10
except Exception as err:
print(err)
return self.rank
def get_tournament_stats(self) -> dict:
return {
"Interfaces": "[Card, Combatable, Rankable]",
"Rating": self.calculate_rating(),
"Record": f"{self.wins}-{self.looses}",
}
def update_wins(self, wins: int) -> None:
self.wins = wins
def update_losses(self, losses: int) -> None:
self.looses = losses
def get_rank_info(self) -> dict:
return {
"wins": self.wins,
"looses": self.looses,
"rank": self.rank,
}

View File

@@ -0,0 +1,65 @@
from .TournamentCard import TournamentCard
class TournamentPlatform:
def __init__(self) -> None:
self.cards: list[TournamentCard] = []
self.math_played = 0
def register_card(self, card: TournamentCard) -> str:
try:
stats = card.get_tournament_stats()
res = f"{card.name} (ID: {card.id}):\n\
- Interfaces: {stats['Interfaces']}\n\
- Rating: {stats['Rating']}\n\
- Record: {stats['Record']}\n"
self.cards += [card]
return res
except Exception:
print("Invalid card")
return "error"
def create_match(self, card1_id: str, card2_id: str) -> dict:
from random import shuffle
try:
cards = [
card
for card in self.cards
if card.id == card1_id or card.id == card2_id
]
if len(cards) != 2:
raise Exception(
"At least once of cards id provide isn't in platform"
)
shuffle(cards)
winner = cards.pop()
loser = cards.pop()
winner.update_wins(winner.wins + 1)
loser.update_losses(loser.looses + 1)
self.math_played += 1
return {
"winner": winner.id,
"loser": loser.id,
"winner_rating": winner.calculate_rating(),
"loser_rating": loser.calculate_rating(),
}
except Exception as err:
print(err)
return {}
def get_leaderboard(self) -> list:
return sorted(
self.cards, key=lambda x: x.calculate_rating(), reverse=True
)
def generate_tournament_report(self) -> dict:
return {
"total_cards": len(self.cards),
"mathes_played": self.math_played,
"avg_rating": int(
sum([card.calculate_rating() for card in self.cards])
/ len(self.cards)
),
"platform_status": "active",
}

7
07/ex4/__init__.py Normal file
View File

@@ -0,0 +1,7 @@
from .Rankable import Rankable
from .TournamentCard import TournamentCard
from .TournamentPlatform import TournamentPlatform
__version__ = "1.0.0"
__author__ = "dgaillet"
__all__ = ["Rankable", "TournamentCard", "TournamentPlatform"]

39
07/ex4/main.py Normal file
View File

@@ -0,0 +1,39 @@
from .TournamentCard import TournamentCard
from .TournamentPlatform import TournamentPlatform
def main() -> None:
print("=== DataDeck Tournament Platform ===\n")
print("Registering Tournament Cards...\n")
platform = TournamentPlatform()
print(
platform.register_card(
TournamentCard(
"dragon_001", "Fire Dragon", 20, "Rare", 15, 25, 5, 1200
)
)
)
print(
platform.register_card(
TournamentCard(
"wizard_001", "Ice Wizard", 15, "common", 10, 30, 4, 1150
)
)
)
print("Creating tournament match...")
match_res = platform.create_match("dragon_001", "wizard_001")
print(f"Math result: {match_res}\n")
print("Tournament Leaderboard:")
leaderboard = platform.get_leaderboard()
for i in range(len(leaderboard)):
print(f"{i + 1}. {leaderboard[i].name} - Rating:\
{leaderboard[i].calculate_rating()}\
({leaderboard[i].get_tournament_stats()['Record']})")
print("\nPlatform Report:")
print(platform.generate_tournament_report())
print("\n=== Tournament Platform Successfully Deployed! ===")
print("All abstract patterns working together harmoniously!")
if __name__ == "__main__":
main()