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.
Create the Lazy-Loaded Component. In the application, add a new component using the Angular CLI command, as shown below.
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]))
def find_exact_multiple_charts(): results = [] for h in range(10, 31): # Item #1 and #8 (>=10) for a in range(1, h): # Items #2, #4, #6 for b in range(1, a): # Item #3 for c in range(1, b): # Items #5 and #7 T = 2*h + 3*a + b + 2*c T_ex = T - b total = 3*T + 4*T_ex if total % 50 == 0: if total in {500, 550, 600, 650, 700}: # Exact matches only chart = { "Item #1": h, "Item #2": a, "Item #3": b, "Item #4": a, "Item #5": c, "Item #6": a, "Item #7": c, "Item #8": h, "Full Chart Total": T, "Combined Total (3 Full + 4 Partial)": total } results.append(chart) return results # Run it and display the results charts = find_exact_multiple_charts() for chart in charts: print(chart)
import pandas as pd # Step 1: Create a DataFrame data = { "Name": ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"], "Diameter": ["4,879 km", "12,104 km", "12,742 km", "6,779 km", "139,822 km", "116,464 km", "50,724 km", "49,244 km"], "Distance from Sun": [ "57,909,227 km", "108,209,475 km", "149,598,262 km", "227,943,824 km", "778,340,821 km", "1,426,666,422 km", "2,870,658,186 km", "4,498,396,441 km" ], "Length of Year": [ "88 Earth days", "225 Earth days", "365.24 days", "1.9 Earth years", "11.9 Earth years", "29.5 Earth years", "84.0 Earth years", "164.8 Earth years" ] } df = pd.DataFrame(data) # Step 2: Facts About Planets print("___________________________________________________________") print("FACTS ABOUT PLANETS\n") print("There are 8 planets in our solar system, they are Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus and Neptune.") print("Planets in our solar system can be divided into two main groups, Terrestrial Planets and Gas Giants.") print("Planets that orbit other stars are referred to as Exoplanets.") print("___________________________________________________________\n") # Step 3: Display numbered options for i, name in enumerate(df["Name"]): print(f"[{i}]-{name}", end=" ") print() # Step 4: Input prompt for selection try: choice = int(input("\nTo know see other details the planets,\ntype the letter assigned to each. >> ")) if 0 <= choice < len(df): print("\nPlanet Details") print("-" * 50) print(df.iloc[choice]) print(f"Name: {choice}, dtype: object\n") # Step 6: Conditional statements if df.iloc[choice]["Name"] == "Jupiter": print("Jupiter has more than double the mass of all the other planets combined.\n") # Step 7: Ask to show more info more = input("Do you want to know more about planets? Y/N >> ").lower() if more == 'y': print("\n" + "_" * 65) print("Planets are among the many worlds and smaller objects that orbit the Sun.") print("The formal definition of planet, as voted on by the International Astronomical Union in 2006, is as follows:") print("A planet is a celestial body that") print(" - is in orbit around the Sun") print(" - has sufficient mass for its self-gravity to overcome rigid body forces so that it assumes a hydrostatic") print(" equilibrium (nearly round) shape, and") print(" - has cleared the neighbourhood around its orbit.\n") # Step 8: Show full DataFrame see_all = input("Do you want to see all planet details? Y/N >> ").lower() if see_all == 'y': print("\n", df.to_string(index=True)) else: print("Invalid number. Please enter a number from 0 to 7.") except ValueError: print("Invalid input. Please enter a valid number.")
import pandas as pa dat = { "Country": [ "India", "China", "Indonesia", "Pakistan", "Bangladesh", "Japan", "Philippines", "Vietnam", "Iran", "Turkey", "Thailand", "Myanmar", "South Korea", "Iraq", "Afghanistan", "Russia", "Saudi Arabia", "Uzbekistan", "Yemen", "Malaysia", "Nepal", "North Korea", "Taiwan", "Syria", "Sri Lanka", "Kazakhstan", "Cambodia", "Jordan", "United Arab Emirates", "Tajikistan", "Israel", "Azerbaijan", "Laos", "Hong Kong (China)", "Kyrgyzstan", "Turkmenistan", "Singapore", "Palestine" ], "Capital": [ "New Delhi", "Beijing", "Jakarta", "Islamabad", "Dhaka", "Tokyo", "Manila", "Hanoi", "Tehran", "Ankara", "Bangkok", "Naypyidaw", "Seoul", "Baghdad", "Kabul", "Moscow", "Riyadh", "Tashkent", "Sana'a", "Kuala Lumpur", "Kathmandu", "Pyongyang", "Taipei", "Damascus", "Sri Jayawardenepura Kotte", "Astana", "Phnom Penh", "Amman", "Abu Dhabi", "Dushanbe", "Jerusalem", "Baku", "Vientiane", "Hong Kong", "Bishkek", "Ashgabat", "Singapore", "East Jerusalem" ], "Geographic Location": [ "South Asia", "East Asia", "Southeast Asia", "South Asia", "South Asia", "East Asia", "Southeast Asia", "Southeast Asia", "West Asia", "West Asia", "Southeast Asia", "Southeast Asia", "East Asia", "West Asia", "South Asia", "Northern Asia", "West Asia", "Central Asia", "West Asia", "Southeast Asia", "South Asia", "East Asia", "East Asia", "West Asia", "South Asia", "Central Asia", "Southeast Asia", "West Asia", "West Asia", "Central Asia", "West Asia", "West Asia", "Southeast Asia", "East Asia", "Central Asia", "Central Asia", "Southeast Asia", "West Asia" ] } da = pa.DataFrame(dat) #Entire DataFrame print("\n\tEntire DataFrame:") print(da) print('\n') #First 20 rows print("\n\tFirst 20 rows:") print(da.head(20)) print('\n') #Last 15 rows print("\n\tLast 15 rows:") print(da.tail(15)) print('\n') #Size of the DataFrame print("\n\tSize of the DataFrame:", da.size) print('\n') #Country and Capital only print("\n\tCountry and Capital columns:") print(da[['Country', 'Capital']]) print('\n') #Population population = [ 1428627000, 1408280000, 277534000, 240485000, 172954000, 123700000, 117337000, 100145000, 89172000, 85664944, 65950000, 55227000, 51751065, 46100000, 43486000, 143400000, 36947000, 36024000, 34449000, 34308000, 30896000, 26160000, 23893000, 23227000, 21893000, 19994000, 17168000, 11337000, 9516000, 10143000, 9364000, 10353000, 7749000, 7488000, 7174000, 6789000, 5637000, 5371000 ] da['Population'] = population print('\n') #Sort da_sorted = da.sort_values(by='Population', ascending=False) print("\n\tDataFrame sorted by Population in a Descending order:") print(da_sorted) print('\n') #Filter : Southeast Asia SA_da = da[da['Geographic Location'] == 'Southeast Asia'] print("\n\tSoutheast Asia countries:") print(SA_da) print('\n') #Filter : West Asia WA_da = da[da['Geographic Location'] == 'West Asia'] print("\n\tWest Asia countries:") print(WA_da) print('\n')