Introduction. Designing a Traffic Signal System may seem like a straightforward task at first glance, but it's a great problem for testing a candidate’s unde...
Gmail, one of the most popular email services in the world, supports millions of users, delivering robust performance, high availability, and strong security...
Introduction. Have you ever wondered how to build a scalable system like the one you use most for interview practice? Leetcode has become a cornerstone for s...
Google Docs is a powerful, web-based word processing application that allows multiple users to create, edit, and collaborate on documents in real time. Desig...
Introduction:. In today's mobile-first world, having a website that performs seamlessly on mobile devices is no longer optional—it's imperative. Mobile optim...
Basic Introduction. Nodejs is a JavaScript runtime build over Chrome's V8 JavaScript engine. Nodejs is generally used a backend tool to cater to client apis.
def listsum(a,b): print("Sum: ",(a+b)) listsum(10,20)
class BankAccount: def __init__(self, account_holder, balance=0): self.account_holder = account_holder self.balance = balance self.transaction_history = [] def deposit(self, amount): if amount > 0: self.balance += amount self.transaction_history.append(f"Deposited ₹{amount}") print(f"₹{amount} deposited successfully.") else: print("Invalid deposit amount.") def withdraw(self, amount): if amount <= 0: print("Invalid withdrawal amount.") elif amount > self.balance: print("Insufficient balance.") else: self.balance -= amount self.transaction_history.append(f"Withdrew ₹{amount}") print(f"₹{amount} withdrawn successfully.") def check_balance(self): print(f"Account Balance: ₹{self.balance}") return self.balance def show_transaction_history(self): print("Transaction History:") for txn in self.transaction_history: print("-", txn) # 🧪 Simple Demo if __name__ == "__main__": # Create a bank account for Ashutosh ashutosh_account = BankAccount("Ashutosh", 1000) # Do some transactions ashutosh_account.deposit(500) ashutosh_account.withdraw(200) ashutosh_account.check_balance() ashutosh_account.show_transaction_history()
<div> <span>Sum: <span id="total"></span></span> </div>
import re import time # Example image URL image_url = "https://example.com/image.jpg" # Example img tag with problematic src img_tag = '<img src="\'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">' # Vulnerable regex pattern (same as your original) regex = r"""\s*src=[\\'"][^\\'"]*[\\'"]""" new_regex = r"""\s*src=(["'])(.*?)\1""" # Start the performance test start = time.time() # Run 10 iterations and measure the time taken for re.sub for _ in range(100000): img_tag = re.sub( new_regex, f' src="{image_url}"', img_tag, ) end = time.time() print(img_tag) # Output the modified img_tag and total time taken print(f"Total time taken: {(end - start)*1000} ms")
version = "0.6.3" import platform import sys import time import shutil import subprocess import os print("Vérification de l'OS...") def install_wine_and_run(): # Demander à l'utilisateur print("Ce script fonctionne uniquement sur windows.") print("Vous pouvez essayer la version bêta avec risques de non-fonctionnements") print("Cependant, vous pouvez quand même éxécuter la version complète avec wine.") choix = input("Wine n'est pas installé. Voulez-vous l'installer ? (y/n) : ").strip().lower() if choix == "y": print("Installation de Wine...") os.system("sudo apt update && sudo apt install -y wine") if shutil.which("wine"): print("Wine a été installé avec succès.") relancer_avec_wine() else: print("Échec de l'installation. Veuillez installer Wine manuellement.") else: print("Wine ne sera pas installé.") def relancer_avec_wine(): print("Tentative de lancement avec Wine :") exe_path = os.path.abspath(sys.argv[0]) # Le chemin vers le script exe_converti = exe_path.replace(".py", ".exe") # Nom supposé de l'exécutable if os.path.exists(exe_converti): print(f"Relancement via Wine : {exe_converti}") subprocess.run(["wine", exe_converti]) else: print("Fichier .exe introuvable. Compilation nécessaire ?") # --- Détection de l'OS --- if platform.system() == "Linux": print("Système Linux détecté.") if shutil.which("wine") is None: install_wine_and_run() else: relancer_avec_wine() if platform.system() != "Windows": print("/!\️ Attention, jeu disponible uniquement sur Windows.\n") print("Le jeu ne sera peu-être pas disponible sur votre ", platform.system(), " dù à la librairie 'windsound'") choice = input("Souhaitez-vous quand-même essayer de lancer le logiciel ? (y / n) : ").strip().lower() if choice != 'y': print("Arrêt du programme.") time.sleep(2) sys.exit() else: if input("Shouaitez-vous tenter de lancer la bêta sans sauvegarde ni son ? (y/n)")=="n": print("Tentative de lancement version actuelle...") print("(Attention, certaines fonctionnalités peuvent ne pas fonctionner, voir crash du script...)") else : print("Tentative de lancement version bêta...") version= "0.3.1 - beta" time.sleep(2) print("Import des dépendances...") time.sleep(1) print("random") import random print("json") import json print("copy") import copy print("colorama...") from colorama import init, Fore, Style init(autoreset=True) if version != "0.3.1 - beta": print("winsound") import winsound print("threading") import threading print("importlib.util") import importlib.util print("ctypes") import ctypes # Lecture non-bloquante d’une touche if os.name == 'nt': print("msvcrt") import msvcrt else: print("select") import select if version != "0.3.1 - beta": print("Définition des sauvegardes") SAVE_FILE = "save_vael.json" MAP_SIZE = 7 print("Initialisation des positions clés") # Positions clés VILLAGE_POS = (0, 6) PORT_POS = (6, 6) FORGE_POS = VILLAGE_POS ISLAND_POS = (4, 4) print("Définition vael_logo") vael_logo = [ " .----------------. .----------------. .----------------. .----------------. ", "| .--------------. || .--------------. || .--------------. || .--------------. |", "| | ____ ____ | || | __ | || | _________ | || | _____ | |", "| ||_ _| |_ _| | || | / \\ | || | |_ ___ | | || | |_ _| | |", "| | \\ \\ / / | || | / /\\ \\ | || | | |_ \\_| | || | | | | |", "| | \\ \\ / / | || | / ____ \\ | || | | _| _ | || | | | _ | |", "| | \\ ' / | || | _/ / \\ \\_ | || | _| |___/ | | || | _| |__/ | | |", "| | \\_/ | || ||____| |____|| || | |_________| | || | |________| | |", "| | | || | | || | | || | | |", "| '--------------' || '--------------' || '--------------' || '--------------' |", " '----------------' '----------------' '----------------' '----------------' " ] if version != "0.3.1 - beta": print("Mise en plein écran...") time.sleep(2) kernel32 = ctypes.windll.kernel32 user32 = ctypes.windll.user32 hWnd = kernel32.GetConsoleWindow() if hWnd: user32.ShowWindow(hWnd, 3) # SW_MAXIMIZE ctypes.windll.kernel32.SetConsoleTitleW("Vael adventure \\ V" + version) time.sleep(1) print("Définition des fonctions... :") # ——— Utilitaires ——— print("clear") def clear(): os.system('cls' if os.name=='nt' else 'clear') print("pause") def pause(prompt="Appuyez sur Entrée pour continuer...", delay=None): if delay: time.sleep(min(delay, 2)) else: input(f"\n[{prompt}]") print("play_click") is_playing = False # global flag def play_click(): if version != "0.3.1 - beta": global is_playing if not is_playing: is_playing = True winsound.PlaySound(clic_path, winsound.SND_FILENAME) is_playing = False print("slow") def slow(text, color_name="WHITE", delay=0.02, clic=True): # Essaie de récupérer Fore.COLOR_NAME, sinon tombe sur Fore.WHITE color = getattr(Fore, color_name.upper(), Fore.WHITE) for c in text: sys.stdout.write(color + c) sys.stdout.flush() if version != "0.3.1 - beta": if clic and c not in [' ', '\n']: # ne clique pas sur les espaces ou sauts de ligne threading.Thread(target=play_click).start() # Joue le son sans bloquer if c != ' ': time.sleep(delay) # Restaure le style print(Style.RESET_ALL, end="") print() print("get_key") def get_key(timeout=1.0): if os.name=='nt': start = time.time() while time.time() - start < timeout: if msvcrt.kbhit(): return msvcrt.getwch().lower() return None else: r,_,_ = select.select([sys.stdin], [], [], timeout) if r: return sys.stdin.readline().strip().lower() return None print("print_v") def print_v(): print(Fore.YELLOW + "Vael ADVENTURE " + Style.RESET_ALL + version) print_v() print("Définition des variables globales... :") # ——— Données globales ——— print("player") player = { "nom":"", "vie":100, "max_vie":100, "magie":50, "max_magie":50, "defense":0, "argent":50, "bonus_atq":0, "arme":"Dague rouillée", "armor":{"name":"Torse nu","bonus_def":0,"durability":0}, "inventaire":[], "position":[0,0], } print(player) print("game") game = {"stage":"world", "apple_quest_done":False} print(game) print("savepoint") savepoint = {"player":None, "game":None} print(savepoint) print("intro_text") intro_text = [ "Depuis des siècles, la légende de Vael hante les esprits...", "On raconte qu'un Cœur ancien repose dans un sanctuaire oublié.", "Beaucoup sont partis à sa recherche, mais rares sont ceux qui sont revenus.", "Toi seul peux percer ces mystères et ramener la lumière.", ] # Vérifie si tu es dans l'exécutable (PyInstaller) if hasattr(sys, '_MEIPASS'): # Si oui, utilise le dossier temporaire extrait outro_path = os.path.join(sys._MEIPASS, 'Dépendances', 'Outro.wav') intro_path = os.path.join(sys._MEIPASS, 'Dépendances', 'Intro.wav') thx_path = os.path.join(sys._MEIPASS, 'Dépendances', 'thx.wav') clic_path = os.path.join(sys._MEIPASS, 'Dépendances', 'clic.wav') else: # Sinon, utilise le chemin normal pour le développement outro_path = os.path.join("Dépendances/Outro.wav") intro_path = os.path.join("Dépendances/Intro.wav") thx_path = os.path.join("Dépendances/thx.wav") clic_path = os.path.join("Dépendances/clic.wav") print("Définition des fonctions de sauvegarde") # ——— Sauvegarde / Chargement ——— print("save_game") def save_game(): if version != "0.3.1 - beta": with open(SAVE_FILE,"w") as f: json.dump((player, game, savepoint), f) slow("[Partie sauvegardée]", "GREEN") else : slow("[Impossible de sauvegarder la partie]", "RED") slow("Vous utilisez la mauvaise version de Vael pour effectuer cette action.") time.sleep(2) print("load_game") def load_game(): if version != "0.3.1 - beta": global player, game, savepoint try: with open(SAVE_FILE,"r") as f: player, game, savepoint = json.load(f) slow("[Partie chargée]", "GREEN") time.sleep(1) return True except: slow("[Aucune sauvegarde trouvée]") time.sleep(1) return False else : slow("[Impossible de charger une partie]", "RED") slow("Vous utilisez la mauvaise version de Vael pour effectuer cette action.") print("set_savepoint") def set_savepoint(): savepoint["player"] = copy.deepcopy(player) savepoint["game"] = copy.deepcopy(game) print("restore_savepoint") def restore_savepoint(): global player, game player = copy.deepcopy(savepoint["player"]) game = copy.deepcopy(savepoint["game"]) slow(f"Ne perds pas espoir, {player['nom']} !") def play_ascii_animation(frames, fps=10): delay = 1 / fps for frame in frames: clear() print(frame) time.sleep(delay) print("Initialisation de la carte...") # ——— Cartographie ——— def draw_map(): obj = "Trouver le sanctuaire !" if game["stage"]=="island" else "Atteindre le port" legend = "P=toi V=village F=forgeron ~=port !=sanctuaire" print_v() print(f"Objectif : {obj}\n{legend}\n") x0,y0 = player["position"] for y in range(MAP_SIZE-1,-1,-1): for x in range(MAP_SIZE): p=(x,y) if p==(x0,y0): sys.stdout.write("P ") elif p==VILLAGE_POS: sys.stdout.write("V ") elif p==FORGE_POS: sys.stdout.write("F ") elif p==PORT_POS and game["stage"]=="world": sys.stdout.write("~ ") elif p==ISLAND_POS and game["stage"]=="island": sys.stdout.write("! ") else: sys.stdout.write(". ") print() print() print("Initialisation des fonctions d'effets/équipements... :") # ——— Effets & équipement ——— print("heal") def heal(qty): old=player["vie"] player["vie"]=min(player["max_vie"], old+qty) slow(f"[Vie : {old} → {player['vie']}]") print("buff_magie") def buff_magie(qty): old=player["magie"] player["magie"]=min(player["max_magie"], old+qty) slow(f"[Mana : {old} → {player['magie']}]") print("equip_sword") def equip_sword(): player["arme"]="Épée d'acier"; player["bonus_atq"]=10 slow("[Arme équipée : Épée d'acier (+10 ATQ)]") print("equip_armor_light") def equip_armor_light(): player["armor"]={"name":"Armure légère","bonus_def":5,"durability":10} slow("[Armure équipée : Armure légère (+5 DEF, durabilité 10)]") print("equip_armor_cuir") def equip_armor_cuir(): player["armor"]={"name":"Armure de cuir","bonus_def":3,"durability":5} slow("[Armure équipée : Armure de cuir (+3 DEF, durabilité 5)]") print("heal_small") def heal_small(): heal(20) print("Définitions des variables de boutique... :") # ——— Boutique itinérante ——— print("items_shop") items_shop = { "Potion de vie (+30 HP)":20, "Baguette de mage (+20 MP)":30, "Armure légère":50, "Épée d'acier":60, } print("merchant_phrases") merchant_phrases = [ "Soldes sur les épées !", "Quel beau temps pour une aventure !", "Des potions fraîches, qui veut ?", "Bienvenue, voyageur !", "Le marché est plus animé que jamais !", "J'ai des ingrédients rares si tu as de l'or !", "Profite des soldes avant qu'il ne soit trop tard !", ] print("Définition des drops...") # ——— Drops de monstres ——— drops = [ ("Armure de cuir","equip_armor_cuir"), ("Steak rassasiant (+20 HP)","heal_small"), ] print("Fonction quitter") def Quitter(): if version != "0.3.1 - beta": save_game() else : slow("Vous ne pouvez pas sauvegarder dans cette version de Vael.", "RED") slow("Merci d'utiliser Windows pour faire des sauvegardes.") slow("Shouaitez-vous vraiment quitter le jeu et perdre tout votre avencement ?") if input("(y/n) >")=="n": return slow("A bientôt pour de nouvelles aventures dans le monde de Vael !", "MAGENTA", 0.02, False) Quit_animation() def Quit_animation(): if version!="0.3.1 - beta": winsound.PlaySound(None, winsound.SND_PURGE) threading.Thread(target=winsound.PlaySound, args=(outro_path, winsound.SND_FILENAME)).start() slow("Au revoir !", "WHITE", 0.1, False) time.sleep(6) clear() for line in vael_logo: sys.stdout.write(Fore.YELLOW + line) print(Style.RESET_ALL, end="") print() time.sleep(0.1) time.sleep(1.5) slow(" GOODBYE !", "GREEN", 0.2, False) sys.exit() print("Définition des mini-jeux... :") # ——— Quête pommes ——— print("Quête pomme") def mini_jeu_pommes(): slow("[Villageois] Rapportez 10 pommes, max 4 perdues.") pause("Entrée pour démarrer…") pos_j=MAP_SIZE//2 pommes=[] prises=0 manq=0 while prises<10 and manq<=4: if random.random()<0.3: pommes.append([0, random.randint(0,MAP_SIZE-1)]) grid=[[" "]*MAP_SIZE for _ in range(MAP_SIZE)] for y,x in pommes: grid[y][x]="o" grid[-1][pos_j]="U" clear() for r in grid[::-1]: print("".join(r)) print(f"Attrapées:{prises} Manquées:{manq}") print("Directions :") print("A) <-- D) -->") key=get_key(1.0) if key=="a" and pos_j>0: pos_j-=1 elif key=="d" and pos_j<MAP_SIZE-1: pos_j+=1 new=[] for y,x in pommes: if y+1==MAP_SIZE-1: if x==pos_j: prises+=1 else: manq+=1 else: new.append([y+1,x]) pommes=new clear() if prises>=10 and manq<=4: slow("Succès !", "GREEN") if random.random()<0.5: g=40; player["argent"]+=g; slow(f"Le villageois vous récompende ! +{g} or") else: itm,_=random.choice(drops); player["inventaire"].append(itm) slow(f"Le villageois vous félicite et vous donne un objet en récompense : {itm}") else: slow("Échec...", "RED", 0.3) slow("[Villageois] : Ah, tu n'as pas réussi à attrapper les pommes ?") time.sleep(2) slow(f"[Villageois] : Ne t'inquiète pas, je peux te donner {prises} or") g=prises player["argent"]+=g slow(f"Vous avez {player['argent']} or") pause() print("Définition des fonctionnalités de combat... :") # ——— Monstres & combat ——— print("Définition des types d'enemis") enemies=[{"nom":"Rôdeur des ombres","pv":(30,50),"atq":(8,15),"gain":25,"infos":["Silencieux comme les ombres...","Craint la lumière","Suspendu aux murs des cryptes", "Son souffle fait frissonner l'air"]}, {"nom":"Gobelin malicieux","pv":(20,35),"atq":(5,12),"gain":20,"infos":["Adore l'or","Préfère laisser les autres se charger des problèmes", "Détèste les humains"]}, {"nom":"Loup-garou","pv":(40,60),"atq":(10,18),"gain":30,"infos":["Hurle à l'aube","Son regard teinté de sang", "Possède un hurlement paralysant"]}] print("Fonction combat") def combat(m): nom, pv0 = m["nom"], random.randint(*m["pv"]) atq_rng, gain = m["atq"], m["gain"] info=random.choice(m["infos"]) slow(f"[COMBAT] {nom} – {info}") while pv0>0 and player["vie"]>0: td=player["defense"]+player["armor"]["bonus_def"] print(f"Vie:{player['vie']} Mana:{player['magie']} ATQ:{player['bonus_atq']} DEF:{td} Or:{player['argent']}") print(f"{nom} PV:{pv0} ATQ:{atq_rng}") print("1)Attaquer 2)Défendre 3)Magie 4)Fuir 5)Inventaire") c=input("> ") if c=="1": d=random.randint(*atq_rng)+player["bonus_atq"]; pv0-=d; slow(f"Dégâts:{d}") elif c=="2": player["defense"]+=5; slow("Déf +5") elif c=="3": cost,pw=10,random.randint(15,25) if player["magie"]>=cost: player["magie"]-=cost; pv0-=pw; slow(f"Sort:{pw}") else: slow("MP insuff"); continue elif c=="4": slow("Fuite -10 or"); player["argent"]=max(0,player["argent"]-10); pause(); return False elif c=="5": use_item_combat(); continue else: slow("Inv."); continue if 0<pv0<=m["pv"][1]//2: slow(f"{nom}: *Son visage se crispe de douleur*") if pv0>0: de=max(0,random.randint(*atq_rng)-td) player["vie"]-=de; slow(f"Reçu:{de}") arm=player["armor"] if arm["bonus_def"]>0: arm["durability"]-=1 if arm["durability"]<=0: slow(f"{arm['name']} brisée"); player["armor"]={"name":"Torse nu","bonus_def":0,"durability":0} if pv0<=0: slow(f"{nom}: Aargh") player["defense"]=max(0,player["defense"]-5) if player["vie"]<=0: slow("Tu es mort", "RED"); return death_sequence() slow(f"Tu obtient +{gain} d'or"); player["argent"]+=gain if random.random()<0.5: itm,_=random.choice(drops); player["inventaire"].append(itm); slow(f"{nom} a laissé tomber : {itm}") pause(); return True print("Utiliser un item en combat") def use_item_combat(): inv=player["inventaire"] if not inv: slow("Inv vide"); return print("Objets:"); [print(f"{i+1}){it}") for i,it in enumerate(inv)] print("0)Annuler"); ch=input("> ") if ch=="0": return try: itm=inv.pop(int(ch)-1); slow(f"Utilisé {itm}") if itm.startswith("Potion"): heal(30) elif itm.startswith("Baguette"): buff_magie(20) elif itm=="Armure de cuir": equip_armor_cuir() elif itm.startswith("Steak"): heal_small() else: slow("Rien") except: slow("Inv inval") pause() print("Définition des rencontres pacifistes") # ——— Pacifistes ——— print("variable pac") pac=[("Érudite","Autrefois, ce pays était un havre de paix…\n" "Mais depuis l'avènement, tous les villages ont commencé à disparaître…"), ("Voyageur","Il ne faut pas toujours combattre.\n" "Mais près des ruines de pierres, une toute autre loi sévit…"), ("Capitaine","Une île voisine abriterait le sanctuaire.\n" "N'y allez surtout pas ! Cet endroit est impitoyable, les monstres qui y sont n'ont aucune pitié !"), ("Sage ermite", "…le vrai trésor, c'est la connaissance."), ("Prêtresse", "…la lune guide les cœurs sincères."), ("Vieux barde", "…les chansons racontent ce que l'histoire oublie, et réchauffent les âmes."), ] print("fonction rencontre_pacifiste") def rencontre_pacifiste(): n,p=random.choice(pac); slow(f"{n}:{p}"); pause() print("Création des village") # ——— Interactions village ——— print("Initialisation des boutiques") def boutique(): phrase=random.choice(merchant_phrases); slow(f"[Marchand] {phrase}", "CYAN") while True: slow(f"Vie:{player['vie']} ATQ:{player['bonus_atq']} DEF:{player['defense']} Or:{player['argent']}") for i,(n,pr) in enumerate(items_shop.items(),1): slow(f"{i}){n}-{pr}or") slow("0)Partir"); ch=input("> ") if ch=="0": break try: nm,pr=list(items_shop.items())[int(ch)-1] if player["argent"]>=pr: player["argent"]-=pr player["inventaire"].append(nm) slow(f"{nm} ajouté") else: slow("Or insuffisant") except: slow("Invalide") pause() clear() slow("[Marchand] : À bientôt") pause() print("Initialisation des auberges") def auberge(): slow("[Auberge] Vous passez la nuit pour 10 d'or"); if player["argent"]>=10: player["argent"]-=10 player["vie"]=player["max_vie"] slow("Repos complet", "WHITE", 0.2) set_savepoint() else: slow("Or insuffisant") pause() print("Création de la forge") def forge(): arm=player["armor"] slow("[Forgeron] Rép:5or") if arm["bonus_def"]>0 and player["argent"]>=5: player["argent"]-=5 arm["durability"]+=5 slow(f"Durabilité : {arm['durability']}") else: slow("Rien") pause() print("Définition des séquances de mort") # ——— Mort & revive ——— def death_sequence(): while True: print("1)Continuer 2)Sauvegarder et quitter") ch=input("> ").lower() if ch=="1": restore_savepoint() return False if ch=="2": if version != "0.3.1 - beta": Quitter() else : slow("Inpossible de sauvegarder") slow("Etes-vous sur de vouloir quitter sans enregistrer ?") if input("(y/n) >")=="y": Quitter() return False else : restore_savepoint() return False slow("Commande invalide") print("Création d'un inventaire") # Dictionnaire des effets des objets effets = { "Potion de vie (+30 HP)": lambda: heal(30), "Baguette de mage (+20 MP)": lambda: buff_magie(20), "Armure légère": equip_armor_light, "Armure de cuir": equip_armor_cuir, "Épée d'acier": equip_sword, "Steak rassasiant (+20 HP)": lambda: heal(20) } # Dictionnaire des messages associés messages = { "Potion de vie (+30 HP)": "Vous avez utilisé une potion et avez récupéré 30 HP", "Baguette de mage (+20 MP)": "Vous avez équipé une baguette et gagné 20 MP", "Armure légère": "Vous avez équipé une armure légère (+5 DEF)", "Armure de cuir": "Vous avez équipé une armure de cuir (+3 DEF)", "Épée d'acier": "Vous avez équipé une épée d'acier (+10 ATK)", "Steak rassasiant (+20 HP)": "Vous avez mangé un steak et récupéré 20 HP" } # ——— Ouvrir l’inventaire ——— def ouvrir_inventaire(): slow("[Inventaire]") inv = player["inventaire"] if not inv: slow("(Inventaire vide)") pause() return # Affichage des objets slow("Sélectionnez un objet à consulter ou 0 pour revenir :") for idx, item in enumerate(inv, 1): print(f"{idx}) {item}") print("0) Retour") # Boucle de saisie sécurisée while True: choix = input("> ").strip() if choix == "0": return if choix.isdigit(): i = int(choix) - 1 if 0 <= i < len(inv): objet = inv[i] action = effets.get(objet) if action: action() # applique l'effet slow(messages.get(objet, f"Vous avez utilisé {objet}")) del inv[i] else: slow("[ERREUR]", "RED") slow("Item inconnu !") pause() return slow("Choix invalide, réessayez.") print("Définition des mouvements sur la carte") # ——— Exploration ——— def explorer(): draw_map() print("n/s/e/o = Déplacer I = Inventaire C = Sauvegarder Q = Sauvegarder et quitter") cmd = input("> ").strip().lower() x, y = player["position"] if cmd == "i": clear() ouvrir_inventaire() return # on retourne directement sans tenter autre chose elif cmd == "n" and y < MAP_SIZE - 1: y += 1 elif cmd == "s" and y > 0: y -= 1 elif cmd == "e" and x < MAP_SIZE - 1: x += 1 elif cmd == "o" and x > 0: x -= 1 elif cmd == "c": save_game() pause() return elif cmd == "q": Quitter() else: slow("Commande invalide") pause() return player["position"] = [x, y] clear() player["position"]=[x,y] clear() pos=(x,y) c="1" if pos==VILLAGE_POS: while c !="0": slow("[Village] Bienvenue !") if not game["apple_quest_done"]: slow("Aux abords du village, un villageois vous aborde : Sais-tu aller me chercher 10 pommes ? Je sais te payer."); print("1)Oui (Lancer le mini-jeu) 2)Non"); if input("> ")=="1": game["apple_quest_done"]=True mini_jeu_pommes() else: slow("C'est dommage... Bon, merci quand même !") pause() clear() slow("[Village] Bienvenue !") print("1)Marché 2)Auberge(10 or la nuit) 3)Forge(Réparez votre armure) 0)Partir") c=input("> ") if c=="1": boutique() if c=="2": auberge() if c=="3": forge() return if pos==PORT_POS and game["stage"]=="world": slow("[Port] Navire prêt à partir") print("1)Traverser 0)Annuler") if input("> ")=="1": game["stage"]="island" player["position"]=[0,0] slow("Levez l'ancre !\nEn avant vers l'île !") set_savepoint() pause() return if pos==ISLAND_POS and game["stage"]=="island": slow("[Sanctuaire] Ici") pause() return ev=random.choices(["combat","shop","pacifiste","rien"],[4,1,1,2])[0] if ev=="combat": combat(random.choice(enemies)) elif ev=="shop": boutique() elif ev=="pacifiste": rencontre_pacifiste() else: slow("...Rien d'intéressant ici.") pause() print("Initialisation de la partie...") def main(): if version!="0.3.1 - beta": ascii_path = "Dépendances/ascii_frames.py" if not os.path.exists(ascii_path): print("Le fichier ascii_frames.py est introuvable. L'animation ne sera pas jouée.") time.sleep(2) else: # Charger le module dynamiquement spec = importlib.util.spec_from_file_location("ascii_frames", ascii_path) ascii_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(ascii_module) frames = ascii_module.frames threading.Thread(target=winsound.PlaySound, args=(intro_path, winsound.SND_FILENAME)).start() play_ascii_animation(frames, fps=10) time.sleep(4) clear() for l in intro_text: slow(l) time.sleep(0.5) pause() clear() if version!="0.3.1 - beta": # Lancer l'audio dans un thread pour la synchro threading.Thread(target=winsound.PlaySound, args=(thx_path, winsound.SND_FILENAME | winsound.SND_ASYNC)).start() choix_principal = "3" while choix_principal not in ["0", "1", "2"]: for line in vael_logo: slow(line, "YELLOW", 0.01, False) time.sleep(1) print_v() slow("1)Nouvelle partie 2)Charger une partie 0)Quitter le jeu", "WHITE", 0.02, False) choix_principal = input("> ") if choix_principal=="2" and load_game(): print("Lancement...") elif choix_principal=="1": clear() slow("Quel est ton nom, aventurier ?") player["nom"]=input("> ").strip() clear() slow(f"{player['nom']}, ton aventure commence ici, dans le monde de Vael !") set_savepoint() pause() elif choix_principal!="2" and choix_principal!="1": Quit_animation() while True: clear() explorer() print("C'est parti !") time.sleep(1) if __name__=="__main__": main()
def ArrayCouples(arr): temp = {} result = [] for i in range(0,len(arr),2): pair = (arr[i], arr[i+1]) temp[pair] = temp.get(pair,0) + 1 for pair, count in temp.items(): r_pair = (pair[1], pair[0]) # print(f'pair {pair} - r_pair {r_pair}') if pair == r_pair and count % 2 != 0: result.extend(pair) elif r_pair not in temp: result.extend(pair) # print(f'same pair {pair} - r_pair {r_pair}') print(f'result {result}') return ",".join(str(pair) for pair in result) if len(result) > 0 else "yes" print(ArrayCouples([2,1,1,2,3,3,3,4]))