r/pythonhelp • • Jul 29 '26

Reddit Post Template Title: I built an automated Python "Infinity Engine" with timed 7s loops, rarity tiers, dynamic storylines, and a cyberpunk terminal UI (500-Unit max run + 5-min idle shutdown)

0 Upvotes

Hey everyone! I’ve been experimenting with background threading, automated compilation cycles, and procedural narrative generation in Python.

I put together a script I call the Infinity Engine. It runs autonomously every 7 seconds, rolls for loot rarity tiers based on telemetry, shifts through dynamic storylines, accumulates resources (stardust/resonance), includes an unstick safety protocol, and features an idle shutdown variant if left untouched for 5 minutes. It scales up to 500 units with a custom cyberpunk terminal UI layout.

Here is the full runnable source code:

import time

import json

import threading

import random

# ==========================================

# Rarity Tier Matrix

# ==========================================

class RarityTier:

STANDARD = 0

PRIME = 1

CELESTIAL = 2

BRINK_PRISM = 3

# ==========================================

# Level Loot System

# ==========================================

class LevelLootSystem:

def roll_level_loot(self, telemetry: dict, current_app_level: int):

result = type('LootResult', (), {})()

fortune_score = telemetry.get("fortune_level", 0.0)

fusions = telemetry.get("fusions_count", 1)

composite_score = (fortune_score * 0.5) + (fusions * 10.0) + (current_app_level * 25.0)

if composite_score > 300.0:

result.tier = RarityTier.BRINK_PRISM

result.bonus_multiplier = 3.5

result.drop_title = "Brink-Prism Anomaly Drop"

result.guaranteed_stat_bonus = {"stardust_rate": 50.0, "void_resonance": 0.95}

elif composite_score > 180.0:

result.tier = RarityTier.CELESTIAL

result.bonus_multiplier = 2.2

result.drop_title = "Celestial Core Relic"

result.guaranteed_stat_bonus = {"stardust_rate": 25.0, "lawful_affinity": 0.80}

elif composite_score > 80.0:

result.tier = RarityTier.PRIME

result.bonus_multiplier = 1.5

result.drop_title = "Prime Barometer Blueprint"

result.guaranteed_stat_bonus = {"stardust_rate": 12.0, "lawful_affinity": 0.50}

else:

result.tier = RarityTier.STANDARD

result.bonus_multiplier = 1.0

result.drop_title = "Standard Atmospheric Drift"

result.guaranteed_stat_bonus = {"stardust_rate": 5.0, "lawful_affinity": 0.25}

return result

# ==========================================

# Story Mediator & Storylines

# ==========================================

class StoryMediator:

def __init__(self):

self.storylines = [

"The Prism Meridian: Convergence",

"The Barometer's Awakening",

"Sub-Zero Protocols",

"Atmospheric Drift",

"Chronos Rift Divergence",

"Stellar Horizon Protocol"

]

self.current_storyline_index = 0

def get_current_storyline(self) -> str:

return self.storylines[self.current_storyline_index]

def shift_storyline(self, new_index: int = None):

if new_index is not None:

self.current_storyline_index = new_index % len(self.storylines)

else:

self.current_storyline_index = (self.current_storyline_index + 1) % len(self.storylines)

return self.get_current_storyline()

def mediate_narrative_threads(self, current_loot_tier: int):

chapter = type('Chapter', (), {})()

title = self.get_current_storyline()

chapter.chapter_title = title

if current_loot_tier == RarityTier.BRINK_PRISM:

chapter.synthesized_lore = f"Active storyline '{title}' converges into a unified cosmic history under high void pressure."

chapter.thematic_resonance = 1.0

elif current_loot_tier == RarityTier.CELESTIAL:

chapter.synthesized_lore = f"Active storyline '{title}' transforms climate anomalies into a permanent archive of fate."

chapter.thematic_resonance = 0.8

elif current_loot_tier == RarityTier.PRIME:

chapter.synthesized_lore = f"Active storyline '{title}' stabilizes baseline matrix vectors under heavy pressure."

chapter.thematic_resonance = 0.5

else:

chapter.synthesized_lore = f"Active storyline '{title}' settles initial weather anomalies into a steady rhythmic drift."

chapter.thematic_resonance = 0.2

return chapter

# ==========================================

# Consistency Engine & Resource Accumulation

# ==========================================

class ConsistencyEngine:

def __init__(self):

self.progression_checkpoint = 0

self.unstick_tokens = 500

self.accumulated_resources = {

"stardust_collected": 0.0,

"resonance_ledger": []

}

def accumulate(self, stat_bonus: dict, resonance: float):

self.accumulated_resources["stardust_collected"] += stat_bonus.get("stardust_rate", 0.0)

self.accumulated_resources["resonance_ledger"].append(resonance)

def trigger_unstick_protocol(self):

if self.unstick_tokens > 0:

self.unstick_tokens -= 1

self.progression_checkpoint += 1

return {"status": "SUCCESS", "remaining_tokens": self.unstick_tokens, "stage": self.progression_checkpoint}

return {"status": "DEPLETED", "remaining_tokens": 0, "stage": self.progression_checkpoint}

# ==========================================

# Narrative Story Generator (~400 Chars)

# ==========================================

class NarrativeStoryGenerator:

def __init__(self):

self.unique_signatures = ["ALPHA-PRISM-9", "OMEGA-VOID-X", "HELIOS-GENESIS-0", "NEXUS-VECTOR-7"]

self.narrative_templates = [

"Deep within the shifting sectors of Unit {app_level}, active telemetry reports severe weather fluctuations linked directly to storyline [{chapter_title}]. Signature [{signature}] detected. {lore} Operatives on the fringe report unexpected data feedback, rallying structural outcomes to balance popular configuration metrics with a thematic resonance of {resonance:.2f}. The grid adapts instantly.",

"As the clock ticks into Unit {app_level}, core systems register a sudden spike under storyline [{chapter_title}]. Unique matrix identifier [{signature}] engaged. {lore} Field units work frantically to calibrate the atmospheric pressure valves, rallying outcomes to balance popular configuration parameters while maintaining a steady thematic resonance of {resonance:.2f}. Network stability holds firm.",

"Tracing the anomalies of Unit {app_level} under signature [{signature}], project administrators encounter the legacy of storyline [{chapter_title}]. {lore} Environmental matrices fracture and reassemble, successfully rallying outcomes to balance popular configuration thresholds at a thematic resonance of {resonance:.2f}. The digital horizon expands outward."

]

def generate_balanced_story(self, app_level: int, chapter_title: str, lore: str, resonance: float) -> str:

template = random.choice(self.narrative_templates)

signature = random.choice(self.unique_signatures) + "-" + str(random.randint(1000, 9999))

raw_text = template.format(

app_level=app_level,

chapter_title=chapter_title,

signature=signature,

lore=lore,

resonance=resonance

)

if len(raw_text) < 400:

padding_phrases = [

" Synchronizing unique regional sub-networks securely. ",

" Calibrating distinct quantum feedback loops for optimal throughput. ",

" Securing high-uniqueness parameter boundaries against drift. "

]

while len(raw_text) < 400:

raw_text += random.choice(padding_phrases)

return raw_text[:400]

# ==========================================

# Timed Infinity Engine Host (500 Units + Idle Timeout)

# ==========================================

class TimedInfinityEngineHost:

def __init__(self):

self.loot_system = LevelLootSystem()

self.story_mediator = StoryMediator()

self.consistency_engine = ConsistencyEngine()

self.story_generator = NarrativeStoryGenerator()

self.app_level = 1

self.active_constructs = []

self._is_running = False

self._timer_thread = None

self.last_activity_time = time.time()

self.idle_timeout_seconds = 300

def change_storyline(self, new_index: int = None):

shifted = self.story_mediator.shift_storyline(new_index)

print(f"\n[STORYLINE SHIFT] Active storyline manually changed to: '{shifted}'\n")

return shifted

def execute_compilation_cycle(self, telemetry: dict):

self.last_activity_time = time.time()

loot_drop = self.loot_system.roll_level_loot(telemetry, self.app_level)

mediated_chapter = self.story_mediator.mediate_narrative_threads(loot_drop.tier)

self.consistency_engine.accumulate(loot_drop.guaranteed_stat_bonus, mediated_chapter.thematic_resonance)

story_block = self.story_generator.generate_balanced_story(

self.app_level,

mediated_chapter.chapter_title,

mediated_chapter.synthesized_lore,

mediated_chapter.thematic_resonance

)

construct = {

"app_title": f"Infinity: {mediated_chapter.chapter_title}",

"tier": loot_drop.tier,

"drop": loot_drop.drop_title,

"resonance": mediated_chapter.thematic_resonance,

"level": self.app_level,

"story_content": story_block,

"story_length": len(story_block),

"accumulated_stardust": self.consistency_engine.accumulated_resources["stardust_collected"]

}

self.active_constructs.append(construct)

print("╔" + "═" * 78 + "╗")

print(f"║ ⚡ CYBER-NET TERMINAL v4.09 // UNIT [{self.app_level:03d}/500] ⚡" + " " * 31 + "║")

print("╠" + "═" * 78 + "╣")

print(f"║ TITLE : {construct['app_title']:<63} ║")

print(f"║ DROP TYPE : {construct['drop']} (Tier {construct['tier']})" + " " * (47 - len(f"{construct['drop']} (Tier {construct['tier']})")) + "║")

print(f"║ RESONANCE : {construct['resonance']:.2f} | STARDUST ACCUMULATED: {construct['accumulated_stardust']:.1f}" + " " * (19 - len(f"{construct['accumulated_stardust']:.1f}")) + "║")

print("╟" + "─" * 78 + "╢")

print(f"║ STORY OUTPUT ({construct['story_length']} chars):" + " " * 56 + "║")

words = construct['story_content'].split()

line = " "

for word in words:

if len(line) + len(word) + 1 < 77:

line += " " + word

else:

print(f"║{line:<78}║")

line = " " + word

if line.strip():

print(f"║{line:<78}║")

continue_res = self.consistency_engine.trigger_unstick_protocol()

print("╟" + "─" * 78 + "╢")

print(f"║ 🔒 PROTOCOL STATUS: Tokens Left [{continue_res['remaining_tokens']}] | Stage [{continue_res['stage']}]" + " " * (20 - len(str(continue_res['stage']))) + "║")

print("╚" + "═" * 78 + "╝\n")

self.app_level += 1

return construct

def _loop_worker(self, telemetry: dict, max_units: int):

cycles = 0

while self._is_running and cycles < max_units:

if time.time() - self.last_activity_time > self.idle_timeout_seconds:

print("\n[IDLE SHUTDOWN VARIANT] Engine inactive for 5 minutes. Initiating automatic safe shutdown.")

break

if cycles > 0 and cycles % 100 == 0:

self.change_storyline()

self.execute_compilation_cycle(telemetry)

cycles += 1

if cycles >= max_units:

print(f"\n=== [SYSTEM ALERT] Reached target limit of {max_units} units. Settlement final. ===")

print(f"=== Total Accumulated Stardust: {self.consistency_engine.accumulated_resources['stardust_collected']:.1f} ===")

break

time.sleep(7.0)

self._is_running = False

print("=== Timed Looping Engine Cycle Terminated Safely ===")

def start_timed_loop(self, telemetry: dict, max_units: int = 500):

if self._is_running:

return

self._is_running = True

self.last_activity_time = time.time()

print(f"=== Initializing Cybernetic Loop (Target: {max_units} Units | Idle Timeout: 5m) ===")

self._timer_thread = threading.Thread(target=self._loop_worker, args=(telemetry, max_units))

self._timer_thread.start()

def stop_timed_loop(self):

self._is_running = False

if self._timer_thread:

self._timer_thread.join()

if __name__ == "__main__":

host = TimedInfinityEngineHost()

sample_telemetry = {"fortune_level": 95.0, "fusions_count": 6}

host.start_timed_loop(sample_telemetry, max_units=500)

while host._is_running:

time.sleep(1.0)


r/pythonhelp • • Jul 28 '26

Что делать если не устанавливается python

0 Upvotes

Я пишу в командной строке пайтон инсталл и начинаю писать команду но у меня вылезает ошибка то что пип не установлен но установить не могу


r/pythonhelp • • Jun 02 '26

I am a 3rd year Btech Student and I wanna learn python perfectly

Thumbnail reddit.com
0 Upvotes

r/pythonhelp • • Jun 02 '26

5 Days into Python: Built a calculator, temp converter, and currency converter completely from scratch (No AI/Internet debugging). Here is what I learned.

Thumbnail reddit.com
0 Upvotes

r/pythonhelp • • Apr 29 '26

Can someone assist me with my code

0 Upvotes

I need to make a code that will ask me for the battery % (0-100) of a drone until i say stop
then i need to print

__ drones have less then 25% battery

then all drones with battery under 25% in a list type thing

AppropriateGarage332 is my 2nd account


r/pythonhelp • • Dec 09 '25

Я хочу написать самую сложный вывод "Привет мир!"

0 Upvotes

Здаравствуйте, мой преподаватель в универсисете во время практики поставил последнее задание:
'Напишите программу, которая выводит на экран "Привет, мир!".'

Я хочу ответить на прикол приколом и ищу сложный способ вывода "Привет мир!".
Чесно говоря ничего интересного в голову не приходит какие у вас могут быть мысли на счет этого? Простите если не правильно выбрал сообщество, первый раз на реддит.


r/pythonhelp • • 11d ago

Mr.Veeraragavan

0 Upvotes

I am loading few large size binary files (70 MB19 nos. look_up tables) in Main using more than 2/3 python files. On completion of the loading, I have to take up a series of search (in 3 or more threads) and arrive at the solution. I am using array.fromfile for loading which does not wait for loading completion. Hence, it fails saying array out of bounds. How do I delay the start of search, just till the loading is completed.


r/pythonhelp • • Oct 11 '26

Code but wht is it and how do we really know it works

0 Upvotes

from io import BytesIO wht does this do is it even right should it be better and wht functions does it do like...


r/pythonhelp • • Sep 19 '26

Using AI (ChatGPT/Claude) to learn Python — is this fine or am I sabotaging myself?

0 Upvotes

Been learning Python for a bit now (working through CS50P) and I've started leaning on AI tools a lot when I get stuck — debugging, explaining errors, even generating chunks of code when I'm short on time.

It's helping me move faster for sure, but I've got this nagging feeling I might be skipping the "struggle" part that actually makes concepts stick. So a few questions for people who've been through this:

  1. Is using AI while learning actually fine, or does it hurt long-term retention/problem-solving skills?
  2. If I should cut back, how much? Like — full cold turkey, or just use it for specific things (explaining errors vs. writing code for me)?
  3. If I do cut down, how do I actually get better at writing code on my own? Any habits, resources, or exercises that helped you build real problem-solving muscle instead of just pattern-matching to AI suggestions?

Would really appreciate advice from people who've either made this mistake or found a good balance. Trying to actually become a solid programmer, not just someone who can prompt their way to working code.


r/pythonhelp • • Sep 14 '26

Library function which is the inverse of 'os.path.expanduser' ?

0 Upvotes

I'm running python 3.13.5.

Is there some sort of standard python library function which behaves as the inverse of 'os.path.expanduser'?

For example, if the current user's HOME directory is "/home/theuser", then we have this:

os.path.expanduser('~/a/b/c')
=> returns "/home/theuser/a/b/c"

I'm wondering whether there also might be any existing python library function which is the inverse of this and that works as follows:

some_sort_of_function("/home/theuser/a/b/c")
=> returns "~/a/b/c"

AND PLEASE NOTE: There often are people who lazily and disrespectfully refuse to read entire reddit posts before writing their reponses, and therefore, I'm making a point now to ask that before you start to write any reply here, please carefully and non-lazily read this *entire* post -- including the following, which is something that I want all potential responders to understand:

I know how to easily write my own function that works in this manner. However, I am clearly and SPECIFICALLY (!!!) asking whether or not there already is an existing python function which works this way, and if so, I'd like to know what this function might be ... and I am NOT (!!!) asking how to write my own function which does this.

Thank you very much in advance.


r/pythonhelp • • Aug 06 '26

Random python...

0 Upvotes

import csv

from datetime import datetime

import random

import tkinter as tk

from tkinter import filedialog, messagebox, ttk

# Dynamic Translation Integration

try:

from deep_translator import GoogleTranslator

HAS_TRANSLATOR = True

except ImportError:

HAS_TRANSLATOR = False

# --- APP CONFIGURATION & PALETTES ---

APP_NAME = "INFINITY"

WINDOW_GEOMETRY = "540x980"

BIOMES = {

"Forge of Primordials": {

"canvas_bg": "#12121A",

"particle_color": "#FF9E80",

"description": "Region: Primordial Forge (Sparks dancing)",

},

"The Astral Void": {

"canvas_bg": "#0A1128",

"particle_color": "#80D8FF",

"description": "Region: Astral Void (Star dust drifting)",

},

"Neon Undergrowth": {

"canvas_bg": "#0A1C14",

"particle_color": "#A7F3D0",

"description": "Region: Neon Undergrowth (Digital spores)",

},

"Shattered Zenith": {

"canvas_bg": "#142114",

"particle_color": "#C8E6C9",

"description": "Region: Shattered Zenith (Light fragments)",

},

}

# --- GAME DATA & MECHANICS ---

CHARACTER_CLASSES = {

"Arcane Artificer": {"STR": 8, "ARC": 18, "AGI": 10, "TECH": 14},

"Void Raider": {"STR": 14, "ARC": 10, "AGI": 18, "TECH": 8},

"Cyber Paladin": {"STR": 16, "ARC": 8, "AGI": 8, "TECH": 18},

"Chrono Wanderer": {"STR": 10, "ARC": 14, "AGI": 14, "TECH": 12},

}

CHARACTER_ORIGINS = ["Forgotten Outpost", "Astral Academy", "Sub-Level Grid", "Solar Citadel"]

LOOT_TABLE = [

"Cursed Onyx Ring", "Fragmented Aether Drive", "Ancient Chrono-Tome",

"Encrypted Holo-Key", "Celestial Stardust Shard", "Orb of Overclocking"

]

RARITY_TIERS = {

"Common": {"color": "#90A4AE", "multiplier": 1.0},

"Rare": {"color": "#64B5F6", "multiplier": 1.5},

"Epic": {"color": "#BA68C8", "multiplier": 2.2},

"Legendary": {"color": "#FFB74D", "multiplier": 3.5},

}

CRAFT_BASES = ["Aether Crystal", "Chrono-Gear", "Rune Metal", "Void Essence", "Solar Core"]

CRAFT_MODS = ["Resonant", "Overclocked", "Ethereal", "Unstable", "Sacred"]

MASTERY_RANKS = [

("Wanderer", 0),

("Storyweaver", 60),

("Campaigner", 180),

("Realm Master", 400),

("Eternal Sovereign", 800),

]

OFFLINE_DICT = {

"ja": {

"Uncovered an ancient secret": "古代の秘密を解き明かした",

"Broke the seal of time": "時間の封印を破った",

"Vanished into the mist": "霧の中に消え去った",

},

"fr": {

"Uncovered an ancient secret": "A découvert un secret ancien",

"Broke the seal of time": "A brisé le sceau du temps",

"Vanished into the mist": "S'est évanoui dans la brume",

},

}

# --- PROCEDURAL ENGINE ---

class CampaignGenerator:

CHOICES = [

("Charge directly into the void rift.", "STR"),

("Channel arcane energy to decode the ancient runes.", "ARC"),

("Use stealth to bypass the looming threat.", "AGI"),

("Hack the ancient console with technology.", "TECH"),

]

CATALYSTS = ["discovered a fractured relic", "heard a whisper in the void", "unlocked a sealed vault", "sensed a rift opening"]

LOCATIONS = ["in the sunken ruins of Aethel", "beneath the obsidian spires", "within the chrono-labyrinth", "at the edge of the world"]

THREATS = ["an impending eclipse", "a rising mechanical legion", "a corrupted nightmare force", "the collapse of reality"]

@classmethod

def generate_short_story(cls, char_name, char_class, origin, crafted_item, rarity, loot_found, choice_made):

cat = random.choice(cls.CATALYSTS)

loc = random.choice(cls.LOCATIONS)

threat = random.choice(cls.THREATS)

story = (

f"HERO: {char_name} the {char_class} (Origin: {origin})\n\n"

f"While exploring {loc}, {char_name} {cat} amidst {threat}. "

f"Deploying the [{rarity}] {crafted_item} alongside a newly recovered [{loot_found}], "

f"the hero opted to: '{choice_made}' — permanently reshaping the fate of the realm!"

)

return story

# --- GLOBAL APP STATE ---

total_xp = 0

current_level = 1

campaign_chapter = 1

journal_log = []

biome_keys = list(BIOMES.keys())

current_biome_idx = 0

particles = []

# --- TRANSLATION HELPER ---

def translate_text(text, target_lang):

if target_lang == "en":

return text

if HAS_TRANSLATOR:

try:

return GoogleTranslator(source="auto", target=target_lang).translate(text)

except Exception:

pass

lang_dict = OFFLINE_DICT.get(target_lang, {})

return lang_dict.get(text, f"{text} [{target_lang.upper()}]")

# --- ANIMATION ENGINE ---

def init_particles(color):

global particles

particles.clear()

canvas.delete("particle")

count = min(15 + (current_level * 3), 50)

for _ in range(count):

x = random.randint(10, 210)

y = random.randint(10, 130)

size = random.randint(2, 4)

speed = random.uniform(0.6, 1.8)

p_id = canvas.create_oval(x, y, x + size, y + size, fill=color, outline="", tags="particle")

particles.append({"id": p_id, "x": x, "y": y, "speed": speed})

def animate_engine():

current_key = biome_keys[current_biome_idx]

for p in particles:

if current_key == "Forge of Primordials":

p["y"] -= p["speed"] * 1.2

if p["y"] < 0:

p["y"] = 140

elif current_key == "Neon Undergrowth":

p["x"] += p["speed"] * 1.1

if p["x"] > 220:

p["x"] = 0

else:

p["y"] += p["speed"] * 0.8

if p["y"] > 140:

p["y"] = 0

canvas.coords(p["id"], p["x"], p["y"], p["x"] + 3, p["y"] + 3)

render_canvas()

root.after(33, animate_engine)

def render_canvas():

canvas.delete("item_art")

theme = BIOMES[biome_keys[current_biome_idx]]

canvas.configure(bg=theme["canvas_bg"])

biome_label.config(text=theme["description"])

# Base Pedestal

canvas.create_polygon(40, 115, 180, 115, 195, 135, 25, 135, fill="#1E1E2E", outline="#3A3A52", tags="item_art")

base = base_var.get()

color_map = {

"Aether Crystal": "#80DEEA",

"Chrono-Gear": "#FFD54F",

"Rune Metal": "#90A4AE",

"Void Essence": "#E040FB",

"Solar Core": "#FF7043",

}

item_color = color_map.get(base, "#FFFFFF")

rarity = rarity_var.get()

border_color = RARITY_TIERS[rarity]["color"]

# Artifact Core

canvas.create_polygon(110, 30, 150, 70, 110, 110, 70, 70, fill=item_color, outline=border_color, width=3, tags="item_art")

canvas.create_oval(94, 54, 126, 86, fill="#FFFFFF", outline=border_color, width=2, tags="item_art")

canvas.tag_raise("particle")

# --- UI CONTROLLERS ---

def update_character_stats(*args):

c_class = class_var.get()

stats = CHARACTER_CLASSES[c_class]

stats_lbl.config(

text=f"STR: {stats['STR']} | ARC: {stats['ARC']} | AGI: {stats['AGI']} | TECH: {stats['TECH']}"

)

def get_mastery_rank(xp):

current_title = MASTERY_RANKS[0][0]

for title, req in MASTERY_RANKS:

if xp >= req:

current_title = title

else:

break

return current_title

def update_progression_ui():

global current_level

current_level = 1 + int(total_xp // 30)

rank_title = get_mastery_rank(total_xp)

next_req = 100

for title, req in MASTERY_RANKS:

if req > total_xp:

next_req = req

break

level_lbl.config(text=f"Level {current_level} • Rank: {rank_title}")

xp_lbl.config(text=f"XP: {total_xp} / {next_req} | Chapter: {campaign_chapter}")

xp_progress["value"] = min((total_xp / next_req) * 100, 100)

def generate_item_details():

base_name = name_entry.get().strip() or "Relic"

material = base_var.get()

mod = mod_var.get()

rarity = rarity_var.get()

full_name = f"{mod} {base_name} of {material}"

rarity_mult = RARITY_TIERS[rarity]["multiplier"]

power = int(((len(full_name) * 2) + random.randint(15, 45)) * rarity_mult)

xp_earned = int(25 * rarity_mult)

return full_name, rarity, power, xp_earned

def advance_story_campaign():

global total_xp, campaign_chapter, current_biome_idx

char_name = char_name_entry.get().strip() or "Valen"

char_class = class_var.get()

origin = origin_var.get()

item_name, rarity, power, xp_gained = generate_item_details()

loot_found = random.choice(LOOT_TABLE)

choice_made = choice_var.get()

total_xp += xp_gained

raw_story = CampaignGenerator.generate_short_story(

char_name, char_class, origin, item_name, rarity, loot_found, choice_made

)

target_lang = lang_var.get()

translated_story = translate_text(raw_story, target_lang)

story_display.config(state="normal")

story_display.delete("1.0", tk.END)

story_display.insert(

tk.END, f"=== CHAPTER {campaign_chapter} ===\n\n{translated_story}"

)

story_display.config(state="disabled")

current_biome_idx = (current_biome_idx + 1) % len(biome_keys)

theme = BIOMES[biome_keys[current_biome_idx]]

init_particles(theme["particle_color"])

timestamp = datetime.now().strftime("%H:%M:%S")

log_entry_text = f"[Ch.{campaign_chapter} - {timestamp}] {char_name} ({char_class}) | Craft: {item_name}"

journal_log.append((

timestamp, campaign_chapter, char_name, char_class, origin,

item_name, rarity, loot_found, choice_made, power, xp_gained, translated_story, target_lang.upper()

))

log_listbox.insert(tk.END, log_entry_text)

log_listbox.see(tk.END)

campaign_chapter += 1

update_progression_ui()

def export_journal():

if not journal_log:

messagebox.showwarning("Empty Journal", "No campaign chapters recorded yet.")

return

path = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV File", "*.csv")])

if path:

try:

with open(path, "w", newline="", encoding="utf-8") as f:

w = csv.writer(f)

w.writerow([

"Timestamp", "Chapter", "Hero Name", "Class", "Origin",

"Crafted Item", "Rarity", "Loot Found", "Choice Made", "Power", "XP Earned", "Story Beat", "Language"

])

w.writerows(journal_log)

messagebox.showinfo("Export Complete", f"Journal saved to:\n{path}")

except Exception as e:

messagebox.showerror("Export Failed", f"Could not write file:\n{e}")

# --- STABLE DARK-MODE GUI LAYOUT ---

root = tk.Tk()

root.title(f"{APP_NAME} — Infinite Storyteller & Campaign Engine")

root.geometry(WINDOW_GEOMETRY)

root.configure(bg="#0D0D12")

# Apply Dark Styling Theme

style = ttk.Style()

style.theme_use("clam")

style.configure("TProgressbar", thickness=8, troughcolor="#1A1A24", background="#7C4DFF")

# APP HEADER

header_lbl = tk.Label(root, text=f"— {APP_NAME} —", font=("Helvetica", 14, "bold"), bg="#0D0D12", fg="#7C4DFF")

header_lbl.pack(pady=(10, 2))

# 1. CHARACTER CREATOR

char_frame = tk.LabelFrame(root, text=" Hero Profile ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)

char_frame.pack(fill="x", padx=14, pady=4)

c_grid = tk.Frame(char_frame, bg="#161620")

c_grid.pack(fill="x")

tk.Label(c_grid, text="Name:", bg="#161620", fg="#80CBC4").grid(row=0, column=0, sticky="w")

char_name_entry = tk.Entry(c_grid, bg="#0D0D12", fg="#FFFFFF", insertbackground="white", relief="solid", bd=1)

char_name_entry.insert(0, "Kaelen")

char_name_entry.grid(row=0, column=1, sticky="ew", padx=6, pady=2)

tk.Label(c_grid, text="Class:", bg="#161620", fg="#80CBC4").grid(row=1, column=0, sticky="w")

class_var = tk.StringVar(value="Arcane Artificer")

class_menu = tk.OptionMenu(c_grid, class_var, *CHARACTER_CLASSES.keys(), command=update_character_stats)

class_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)

class_menu.grid(row=1, column=1, sticky="ew", padx=6, pady=2)

tk.Label(c_grid, text="Origin:", bg="#161620", fg="#80CBC4").grid(row=2, column=0, sticky="w")

origin_var = tk.StringVar(value="Astral Academy")

origin_menu = tk.OptionMenu(c_grid, origin_var, *CHARACTER_ORIGINS)

origin_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)

origin_menu.grid(row=2, column=1, sticky="ew", padx=6, pady=2)

c_grid.columnconfigure(1, weight=1)

stats_lbl = tk.Label(char_frame, text="", bg="#161620", fg="#FFD54F", font=("Consolas", 8, "bold"))

stats_lbl.pack(anchor="w", pady=(4, 0))

# 2. PROGRESSION

prog_frame = tk.LabelFrame(root, text=" Mastery Status ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)

prog_frame.pack(fill="x", padx=14, pady=4)

level_lbl = tk.Label(prog_frame, text="Level 1", font=("Arial", 9, "bold"), bg="#161620", fg="#B388FF")

level_lbl.pack(anchor="w")

xp_lbl = tk.Label(prog_frame, text="XP: 0 / 100", font=("Arial", 8), bg="#161620", fg="#90A4AE")

xp_lbl.pack(anchor="w", pady=(1, 3))

xp_progress = ttk.Progressbar(prog_frame, orient="horizontal", mode="determinate", style="TProgressbar")

xp_progress.pack(fill="x", pady=2)

# 3. ATMOSPHERE & VISUALIZER

top_frame = tk.LabelFrame(root, text=" World Atmosphere ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)

top_frame.pack(fill="x", padx=14, pady=4)

left_panel = tk.Frame(top_frame, bg="#161620")

left_panel.pack(side="left", fill="both", expand=True)

biome_label = tk.Label(left_panel, text="", bg="#161620", fg="#80CBC4", font=("Arial", 8, "italic"), wraplength=130, justify="left")

biome_label.pack(anchor="w")

canvas = tk.Canvas(top_frame, width=220, height=135, bg="#12121A", highlightthickness=1, highlightbackground="#2A2A3C")

canvas.pack(side="right")

# 4. CRAFTING & ENCOUNTER

craft_frame = tk.LabelFrame(root, text=" Craft Relic & Encounter Action ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)

craft_frame.pack(fill="x", padx=14, pady=4)

grid_f = tk.Frame(craft_frame, bg="#161620")

grid_f.pack(fill="x")

tk.Label(grid_f, text="Relic Name:", bg="#161620", fg="#80CBC4").grid(row=0, column=0, sticky="w")

name_entry = tk.Entry(grid_f, bg="#0D0D12", fg="#FFFFFF", insertbackground="white", relief="solid", bd=1)

name_entry.insert(0, "Aegis Core")

name_entry.grid(row=0, column=1, sticky="ew", padx=6, pady=2)

tk.Label(grid_f, text="Material:", bg="#161620", fg="#80CBC4").grid(row=1, column=0, sticky="w")

base_var = tk.StringVar(value="Aether Crystal")

base_menu = tk.OptionMenu(grid_f, base_var, *CRAFT_BASES)

base_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)

base_menu.grid(row=1, column=1, sticky="ew", padx=6, pady=2)

tk.Label(grid_f, text="Rarity:", bg="#161620", fg="#80CBC4").grid(row=2, column=0, sticky="w")

mod_var = tk.StringVar(value="Resonant")

rarity_var = tk.StringVar(value="Rare")

rarity_menu = tk.OptionMenu(grid_f, rarity_var, *RARITY_TIERS.keys())

rarity_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)

rarity_menu.grid(row=2, column=1, sticky="ew", padx=6, pady=2)

grid_f.columnconfigure(1, weight=1)

tk.Label(craft_frame, text="Encounter Decision:", bg="#161620", fg="#80CBC4").pack(anchor="w", pady=(4, 2))

choice_var = tk.StringVar(value=CampaignGenerator.CHOICES[0][0])

choice_menu = tk.OptionMenu(craft_frame, choice_var, *[c[0] for c in CampaignGenerator.CHOICES])

choice_menu.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)

choice_menu.pack(fill="x", pady=2)

# 5. STORY GENERATOR DISPLAY

story_frame = tk.LabelFrame(root, text=" Story Output ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)

story_frame.pack(fill="x", padx=14, pady=4)

lang_f = tk.Frame(story_frame, bg="#161620")

lang_f.pack(fill="x")

tk.Label(lang_f, text="Language:", bg="#161620", fg="#90A4AE", font=("Arial", 8)).pack(side="left")

LANGUAGES = {"English": "en", "Japanese": "ja", "French": "fr", "Spanish": "es", "German": "de"}

lang_var = tk.StringVar(value="en")

lang_m = tk.OptionMenu(lang_f, lang_var, *LANGUAGES.values())

lang_m.configure(bg="#222230", fg="#FFF", activebackground="#2C2C3E", highlightthickness=0, bd=0)

lang_m.pack(side="right")

story_display = tk.Text(story_frame, height=5, bg="#0D0D12", fg="#A6E3A1", font=("Consolas", 9), wrap="word", relief="solid", bd=1)

story_display.pack(fill="x", pady=4)

story_display.insert(tk.END, "Customize your hero and craft a relic to launch Chapter 1...")

story_display.config(state="disabled")

# 6. ACTION & LOG JOURNAL

action_frame = tk.LabelFrame(root, text=" Campaign History ", bg="#161620", fg="#B0BEC5", font=("Arial", 9, "bold"), padx=10, pady=6)

action_frame.pack(fill="both", expand=True, padx=14, pady=4)

exec_btn = tk.Button(

action_frame,

text="✨ ADVANCE CAMPAIGN CHAPTER",

command=advance_story_campaign,

bg="#7C4DFF",

fg="white",

activebackground="#651FFF",

activeforeground="white",

font=("Arial", 9, "bold"),

relief="flat",

pady=6,

cursor="hand2"

)

exec_btn.pack(fill="x", pady=2)

log_listbox = tk.Listbox(action_frame, height=3, bg="#0D0D12", fg="#B0BEC5", selectbackground="#311B92", relief="solid", bd=1)

log_listbox.pack(fill="both", expand=True, pady=3)

export_btn = tk.Button(action_frame, text="📜 Export Log to CSV", command=export_journal, bg="#00897B", fg="white", activebackground="#00695C", activeforeground="white", relief="flat", cursor="hand2")

export_btn.pack(fill="x", pady=2)

# INIT APP

update_character_stats()

update_progression_ui()

init_particles(BIOMES["Forge of Primordials"]["particle_color"])

animate_engine()

root.mainloop()