Hazem42 commited on
Commit
a0b04ff
ยท
verified ยท
1 Parent(s): f5606b7

Upload 6 files

Browse files
Files changed (6) hide show
  1. .gitignore +1 -0
  2. LevelGenerator.gd +210 -0
  3. main.py +144 -0
  4. mario_dual_model_generator.py +1376 -0
  5. requirements.txt +8 -0
  6. start_server.bat +5 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .venv/
LevelGenerator.gd ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+
3
+ class_name LevelGenerator
4
+
5
+ # Configuration
6
+ @export var api_url: String = "http://127.0.0.1:8000/api/generate"
7
+ @export var difficulty: float = 0.3
8
+ @export var seed: int = 0
9
+
10
+ # Loading screen
11
+ var loading_instance
12
+ var LoadingScene = preload("res://Scenes/UI/LoadingScreen.tscn")
13
+
14
+ # MiniMap Preview
15
+ var MiniMapScene = preload("res://Scenes/UI/MiniMapPreview.tscn")
16
+ var minimap_instance
17
+
18
+ # Must map exactly to the text symbols returned by the model to your Godot TileSet IDs
19
+ # e.g., if ground is Tile ID 1 and coin is Tile ID 2
20
+ @export var tile_map_mapping: Dictionary = {
21
+ "-": -1, # Air (empty)
22
+ "X": 0, # Ground
23
+ "S": 1, # Breakable
24
+ "?": 2, # Question block
25
+ "Q": 2, # Question block
26
+ "o": 3, # Coin
27
+ "E": 4, # Enemy
28
+ "<": 5, # Tube top left
29
+ ">": 6, # Tube top right
30
+ "[": 7, # Tube lower left
31
+ "]": 8, # Tube lower right
32
+ "x": -1 # Generated Path (usually empty space in game)
33
+ }
34
+
35
+ @onready var tile_map: TileMap = $TileMap
36
+ @onready var http_request: HTTPRequest = $HTTPRequest
37
+
38
+ const GRID_COLS = 50
39
+ const GRID_ROWS = 16
40
+
41
+ var is_generating = false
42
+
43
+ func _ready():
44
+ randomize()
45
+ # Ensure the HTTPRequest node exists
46
+ if not http_request:
47
+ http_request = HTTPRequest.new()
48
+ add_child(http_request)
49
+
50
+ http_request.request_completed.connect(_on_level_generated)
51
+
52
+ # Start generation on load
53
+ generate_level()
54
+
55
+ func generate_level():
56
+ # Prevent multiple simultaneous requests
57
+ if is_generating:
58
+ print("[WARNING] Already generating a level, skipping request")
59
+ return
60
+
61
+ is_generating = true
62
+ print("\n[LEVEL] Starting Level Generation...")
63
+
64
+ # Clean up old loading screen
65
+ if loading_instance:
66
+ loading_instance.queue_free()
67
+ if minimap_instance:
68
+ minimap_instance.queue_free()
69
+
70
+ # Create new loading screen
71
+ loading_instance = LoadingScene.instantiate()
72
+ get_tree().current_scene.add_child(loading_instance)
73
+
74
+ # Generate NEW random seed every time if seed is 0
75
+ if seed == 0:
76
+ seed = randi() % 1000000000
77
+
78
+ print(f"[LEVEL] Using difficulty: {difficulty:.2f}, seed: {seed}")
79
+
80
+ var request_data = {
81
+ "difficulty": difficulty,
82
+ "seed": seed,
83
+ "use_auto_path": true,
84
+ "slot_name": "A",
85
+ "patch_enemy_bias": {}
86
+ }
87
+
88
+ var json_payload = JSON.stringify(request_data)
89
+ var headers = ["Content-Type: application/json"]
90
+
91
+ # Make the request to the FastAPI application
92
+ var error = http_request.request(api_url, headers, HTTPClient.METHOD_POST, json_payload)
93
+
94
+ if loading_instance:
95
+ loading_instance.set_progress(0.3)
96
+
97
+ if error != OK:
98
+ print("[ERROR] HTTP request failed with error code:", error)
99
+ is_generating = false
100
+ if loading_instance:
101
+ loading_instance.queue_free()
102
+
103
+ func _on_level_generated(result, response_code, headers, body):
104
+ if response_code != 200:
105
+ print(f"[ERROR] Failed to fetch level. Response code: {response_code}")
106
+ print(f"[ERROR] Response: {body.get_string_from_utf8()}")
107
+ is_generating = false
108
+ if loading_instance:
109
+ loading_instance.queue_free()
110
+ return
111
+
112
+ var json = JSON.new()
113
+ var parse_result = json.parse(body.get_string_from_utf8())
114
+ if parse_result != OK:
115
+ print("[ERROR] Failed to parse JSON response.")
116
+ is_generating = false
117
+ if loading_instance:
118
+ loading_instance.queue_free()
119
+ return
120
+
121
+ var response_data = json.data
122
+
123
+ if loading_instance:
124
+ loading_instance.set_progress(0.6)
125
+
126
+ if not response_data.has("grid_string"):
127
+ print("[ERROR] Grid data not found in response.")
128
+ is_generating = false
129
+ if loading_instance:
130
+ loading_instance.queue_free()
131
+ return
132
+
133
+ var grid_string = response_data["grid_string"]
134
+ var difficulty_label = response_data.get("difficulty_label", "Unknown")
135
+
136
+ print(f"[LEVEL] Received grid_string ({GRID_COLS}x{GRID_ROWS})")
137
+ print(f"[LEVEL] Difficulty label: {difficulty_label}")
138
+
139
+ # Show mini map preview
140
+ if minimap_instance:
141
+ minimap_instance.queue_free()
142
+
143
+ minimap_instance = MiniMapScene.instantiate()
144
+ get_tree().current_scene.add_child(minimap_instance)
145
+ minimap_instance.generate_preview(grid_string)
146
+
147
+ if loading_instance:
148
+ loading_instance.set_progress(0.9)
149
+
150
+ # Wait 2 seconds for preview
151
+ await get_tree().create_timer(2.0).timeout
152
+
153
+ # Clean up minimap
154
+ if minimap_instance:
155
+ minimap_instance.queue_free()
156
+ minimap_instance = null
157
+
158
+ # Hide loading screen
159
+ if loading_instance:
160
+ loading_instance.queue_free()
161
+ loading_instance = null
162
+
163
+ print("[LEVEL] Rendering level to TileMap...")
164
+ render_level(grid_string.split("\n"))
165
+
166
+ is_generating = false
167
+ print("[LEVEL] Level generation complete!\n")
168
+
169
+ func render_level(grid_rows: Array):
170
+ tile_map.clear()
171
+
172
+ var row_idx = 0
173
+ for row_str in grid_rows:
174
+ for col_idx in range(row_str.length()):
175
+ var char_symbol = row_str.substr(col_idx, 1)
176
+
177
+ if tile_map_mapping.has(char_symbol):
178
+ var tile_id = tile_map_mapping[char_symbol]
179
+ if tile_id != -1:
180
+ tile_map.set_cell(0, Vector2i(col_idx, row_idx), tile_id, Vector2i(0, 0))
181
+ row_idx += 1
182
+
183
+ print("[LEVEL] Level rendering complete.")
184
+
185
+ func regenerate_level(new_difficulty: float):
186
+ print(f"\n[LEVEL] Regenerate requested with difficulty: {new_difficulty}")
187
+ difficulty = clamp(new_difficulty, 0.0, 1.0)
188
+ seed = 0 # Reset seed to generate a new one
189
+ generate_level()
190
+
191
+ func get_tile_color(char: String) -> Color:
192
+ match char:
193
+ "-", "x":
194
+ return Color("#12121f") # air/path โ€” dark
195
+ "X":
196
+ return Color("#4a3728") # ground โ€” brown
197
+ "S":
198
+ return Color("#8b6914") # breakable โ€” gold
199
+ "?", "Q":
200
+ return Color("#f5c518") # question โ€” yellow
201
+ "E":
202
+ return Color("#c0392b") # enemy โ€” red
203
+ "<", ">":
204
+ return Color("#27ae60") # pipe top โ€” green
205
+ "[", "]":
206
+ return Color("#1e8449") # pipe bottom โ€” dark green
207
+ "o":
208
+ return Color("#f39c12") # coin โ€” orange
209
+ _:
210
+ return Color("#000000") # unknown โ€” black
main.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import math
5
+ import random
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ try:
10
+ from mario_dual_model_generator import (
11
+ load_checkpoint, build_model_from_checkpoint, run_generation, decode_patch, build_alpha_bar,
12
+ DEVICE, GRID_COLS, GRID_ROWS, PATCH_SIZE, AIR_TILE, generate_seeded_path
13
+ )
14
+ except ImportError as e:
15
+ raise RuntimeError(f"Could not import generation logic: {e}")
16
+
17
+ app = FastAPI(title="Mario GPT Backend API")
18
+
19
+ app.add_middleware(
20
+ CORSMiddleware,
21
+ allow_origins=["*"],
22
+ allow_credentials=True,
23
+ allow_methods=["*"],
24
+ allow_headers=["*"],
25
+ )
26
+
27
+ loaded_models = {}
28
+
29
+ class LoadModelRequest(BaseModel):
30
+ model_path: str
31
+ slot_name: str = "A"
32
+
33
+ DIFFICULTY_LABELS = [
34
+ "0 โ€” Flat & Peaceful", "1 โ€” Very Gentle Waves", "2 โ€” Smooth & Sweeping",
35
+ "3 โ€” Rolling Hills", "4 โ€” Moderate Waves", "5 โ€” Pronounced Hills",
36
+ "6 โ€” Steep Waves", "7 โ€” Aggressive Terrain", "8 โ€” Sharp Spikes",
37
+ "9 โ€” Maximum Chaos",
38
+ ]
39
+
40
+ class GenerateRequest(BaseModel):
41
+ difficulty: float = 0.3
42
+ seed: int = 0
43
+ use_auto_path: bool = True
44
+ path_grid: list[list[bool]] | None = None
45
+ slot_name: str = "A"
46
+ patch_enemy_bias: dict[str, float] = {}
47
+
48
+ @app.get("/")
49
+ def home():
50
+ return {"message": "Backend Running"}
51
+
52
+ @app.post("/api/load_model")
53
+ def api_load_model(req: LoadModelRequest):
54
+ try:
55
+ ckpt = load_checkpoint(req.model_path)
56
+ tile_to_index = ckpt["tile_to_index"]
57
+ index_to_tile = ckpt["index_to_tile"]
58
+ num_tile_types = ckpt["num_tile_types"]
59
+ diffusion_steps = ckpt["diffusion_steps"]
60
+ model, arch = build_model_from_checkpoint(ckpt)
61
+ model.to(DEVICE)
62
+ alpha_bar = build_alpha_bar(diffusion_steps).to(DEVICE)
63
+
64
+ loaded_models[req.slot_name] = {
65
+ "model": model, "alpha_bar": alpha_bar, "tile_to_index": tile_to_index,
66
+ "index_to_tile": index_to_tile, "num_tile_types": num_tile_types,
67
+ "diffusion_steps": diffusion_steps, "arch": arch
68
+ }
69
+ return {"status": "success", "arch": arch}
70
+ except Exception as e:
71
+ raise HTTPException(status_code=500, detail=str(e))
72
+
73
+ @app.post("/api/generate")
74
+ def api_generate(req: GenerateRequest):
75
+ if req.slot_name not in loaded_models:
76
+ raise HTTPException(status_code=400, detail=f"Model slot '{req.slot_name}' not loaded.")
77
+
78
+ slot = loaded_models[req.slot_name]
79
+
80
+ # Convert game difficulty (0.0 โ†’ 1.0) to model difficulty (0 โ†’ 9)
81
+ game_diff = max(0.0, min(1.0, req.difficulty))
82
+ difficulty = int(round(game_diff * 9))
83
+
84
+ used_seed = req.seed if req.seed > 0 else random.randint(1, 99999)
85
+
86
+ print(f"\n[API] /generate REQUEST RECEIVED ===")
87
+ print(f" game_difficulty: {game_diff:.2f} (0.0-1.0)")
88
+ print(f" model_difficulty: {difficulty} (0-9)")
89
+ print(f" seed: {used_seed}")
90
+ print(f" auto_path: {req.use_auto_path}")
91
+
92
+ if req.use_auto_path or not req.path_grid:
93
+ path_grid = generate_seeded_path(difficulty, used_seed, GRID_ROWS, GRID_COLS)
94
+ print(f" [โœ“] Generated auto path with difficulty {difficulty}")
95
+ else:
96
+ path_grid = req.path_grid
97
+ print(f" [โœ“] Using manual path_grid")
98
+
99
+ num_patches = math.ceil(GRID_COLS / PATCH_SIZE)
100
+ result = [[AIR_TILE] * (num_patches * PATCH_SIZE) for _ in range(GRID_ROWS)]
101
+
102
+ try:
103
+ for p in range(num_patches):
104
+ col_start = p * PATCH_SIZE
105
+ path_mask = torch.zeros(PATCH_SIZE, PATCH_SIZE)
106
+ for r in range(PATCH_SIZE):
107
+ for c in range(PATCH_SIZE):
108
+ sc = col_start + c
109
+ if sc < GRID_COLS and path_grid[r][sc]:
110
+ path_mask[r][c] = 1.0
111
+
112
+ bias = req.patch_enemy_bias.get(str(p), 0.0)
113
+ tile_ids, path_flags = run_generation(
114
+ path_mask, slot["model"], slot["alpha_bar"],
115
+ slot["tile_to_index"], slot["num_tile_types"],
116
+ slot["diffusion_steps"], enemy_bias=bias,
117
+ num_inference_steps=200
118
+ )
119
+ patch_grid_decoded = decode_patch(tile_ids, path_flags, slot["index_to_tile"])
120
+ for r in range(PATCH_SIZE):
121
+ for c in range(PATCH_SIZE):
122
+ result[r][col_start + c] = patch_grid_decoded[r][c]
123
+
124
+ generated_grid = [row[:GRID_COLS] for row in result]
125
+
126
+ # Format as string grid for Godot Level_1.gd parsing (joined with \n)
127
+ level_as_strings = ["".join(row) for row in generated_grid]
128
+ grid_string = "\n".join(level_as_strings)
129
+
130
+ print(f" [โœ“] Level generation complete")
131
+ print(f"[API] /generate RESPONSE SENT ===\n")
132
+
133
+ return {
134
+ "status": "success",
135
+ "grid_string": grid_string,
136
+ "difficulty": game_diff,
137
+ "difficulty_label": DIFFICULTY_LABELS[difficulty],
138
+ "model_difficulty": difficulty,
139
+ "seed": used_seed,
140
+ }
141
+
142
+ except Exception as e:
143
+ print(f" [โœ—] ERROR: {str(e)}")
144
+ raise HTTPException(status_code=500, detail=str(e))
mario_dual_model_generator.py ADDED
@@ -0,0 +1,1376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import math
3
+ import random
4
+ import pathlib
5
+ import pickle
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ import tkinter as tk
10
+ from tkinter import filedialog, messagebox
11
+ from PIL import Image, ImageTk
12
+
13
+ try:
14
+ from mambapy.mamba import Mamba, MambaConfig
15
+ MAMBA_AVAILABLE = True
16
+ except ImportError:
17
+ MAMBA_AVAILABLE = False
18
+
19
+ try:
20
+ from mario_gpt.utils import convert_level_to_png
21
+ MARIOGPT_AVAILABLE = True
22
+ except ImportError:
23
+ MARIOGPT_AVAILABLE = False
24
+
25
+
26
+ # โ”€โ”€ Constants โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
27
+ GRID_ROWS = 16
28
+ GRID_COLS = 200
29
+ CELL_SIZE = 22
30
+ PATCH_SIZE = 16
31
+ NUM_PATCHES = math.ceil(GRID_COLS / PATCH_SIZE)
32
+ PATH_TILE = "x"
33
+ AIR_TILE = "-"
34
+
35
+ TILE_COLOR_MAP = {
36
+ "-": "#12121f", "X": "#4a3728", "S": "#8b6914",
37
+ "?": "#f5c518", "Q": "#e8a000", "E": "#c0392b",
38
+ "<": "#27ae60", ">": "#27ae60", "[": "#1e8449",
39
+ "]": "#1e8449", "o": "#f39c12", "x": "#00d4ff",
40
+ }
41
+ DEFAULT_COLOR = "#555566"
42
+ PATH_COLOR = "#00d4ff"
43
+ AIR_COLOR = "#12121f"
44
+ GRID_LINE = "#1e1e35"
45
+ PATCH_SEL_COLOR = "#ff5555"
46
+ PATCH_IDLE_COLOR = "#1e1e35"
47
+
48
+ # Colors for each model slot
49
+ MODEL_A_COLOR = "#00d4ff" # cyan
50
+ MODEL_B_COLOR = "#bd93f9" # purple
51
+
52
+ # โ”€โ”€ Difficulty colours for the seed dialog preview โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
53
+ DIFF_COLORS = [
54
+ "#1a6b2a", # 0 โ€“ easy green
55
+ "#1a6b2a",
56
+ "#2a7a1a",
57
+ "#6b8b1a",
58
+ "#8b7b1a",
59
+ "#8b5a1a",
60
+ "#8b3a1a",
61
+ "#8b1a1a",
62
+ "#7a0a0a",
63
+ "#6a0000", # 9 โ€“ brutal red
64
+ ]
65
+
66
+
67
+ # โ”€โ”€ Seeded Path Generator (Continuous Wave) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
68
+ def generate_seeded_path(difficulty: int, seed: int,
69
+ rows: int = GRID_ROWS,
70
+ cols: int = GRID_COLS) -> list:
71
+ """
72
+ Returns a rowsร—cols grid of booleans (True = path cell).
73
+
74
+ The path is ALWAYS connected (no gaps).
75
+ It is generated as a continuous mathematical wave.
76
+ Difficulty directly controls the Amplitude and Wavelength.
77
+ Mario physics constraints (max 3 tiles vertical jump per step) are strictly enforced.
78
+ """
79
+ rng = random.Random(seed * 1234567 + difficulty * 777 + 1)
80
+ grid = [[False] * cols for _ in range(rows)]
81
+
82
+ # Map difficulty (0 to 9) to a 0.0 - 1.0 scale
83
+ d = difficulty / 9.0
84
+
85
+ # Base Y position (lower on screen for easy, centered for hard)
86
+ # rows = 16. Safe Y range is ~3 to 13.
87
+ base_y = 8 + int((1.0 - d) * 3)
88
+
89
+ # Amplitude: how high/low the wave goes from base_y
90
+ # diff 0 -> amp 0 (flat)
91
+ # diff 9 -> amp 5 (sweeps from Y=3 to Y=13)
92
+ amplitude = d * 5.0
93
+
94
+ # Wave length: horizontal stretching of the wave
95
+ # diff 0 -> long, smooth (length 30)
96
+ # diff 9 -> more varied (length 8)
97
+ wave_length = 30.0 - (d * 22.0)
98
+
99
+ # Randomize phase shifts for seed variance
100
+ phase1 = rng.random() * math.pi * 2
101
+ phase2 = rng.random() * math.pi * 2
102
+
103
+ prev_y = base_y
104
+
105
+ for c in range(cols):
106
+ if amplitude == 0:
107
+ target_y = base_y
108
+ else:
109
+ # Composite sine wave for a natural organic look
110
+ w1 = math.sin(c / wave_length + phase1)
111
+ w2 = 0.5 * math.sin(c / (wave_length * 0.5) + phase2)
112
+ combined = (w1 + w2) / 1.5 # normalize roughly to [-1, 1]
113
+
114
+ target_y = round(base_y + combined * amplitude)
115
+
116
+ # Absolute limits within the grid
117
+ target_y = max(3, min(13, target_y))
118
+
119
+ # Enforce physical constraints (max 3 tiles vertical jump per column)
120
+ # dy is change in Y (negative is UP in screen coordinates)
121
+ dy = target_y - prev_y
122
+
123
+ max_up = 2 # Mario can comfortably jump 2 blocks; 3 is the extreme limit
124
+ max_down = 2 # Keep falls safe for continuous platforms
125
+
126
+ if dy < -max_up:
127
+ dy = -max_up
128
+ elif dy > max_down:
129
+ dy = max_down
130
+
131
+ actual_y = prev_y + dy
132
+ actual_y = max(3, min(13, actual_y))
133
+
134
+ # Paint 3 tiles thick for solid connectivity and fewer gaps
135
+ grid[actual_y][c] = True
136
+ grid[actual_y + 1][c] = True
137
+ grid[actual_y + 2][c] = True
138
+
139
+ prev_y = actual_y
140
+
141
+ return grid
142
+
143
+
144
+ # โ”€โ”€ Seed Dialog โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
145
+ class SeedDialog(tk.Toplevel):
146
+ """
147
+ Modal dialog for entering difficulty (0-9) and RNG seed.
148
+ Shows a live minimap preview of the path as the user adjusts sliders.
149
+ """
150
+
151
+ MINI_CELL = 4
152
+ MINI_W = GRID_COLS * 4
153
+ MINI_H = GRID_ROWS * 4
154
+
155
+ def __init__(self, parent):
156
+ super().__init__(parent)
157
+ self.title("Auto-Draw Seeded Path")
158
+ self.configure(bg="#0b0b18")
159
+ self.resizable(False, False)
160
+ self.grab_set() # modal
161
+
162
+ self.result_grid = None # filled on OK
163
+ self.difficulty = tk.IntVar(value=3)
164
+ self.seed = tk.IntVar(value=42)
165
+
166
+ self._build()
167
+ self._preview()
168
+
169
+ # Centre over parent
170
+ self.update_idletasks()
171
+ px = parent.winfo_rootx() + (parent.winfo_width() - self.winfo_width()) // 2
172
+ py = parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 2
173
+ self.geometry(f"+{px}+{py}")
174
+
175
+ def _build(self):
176
+ BG = "#0b0b18"
177
+ FG = "#9999cc"
178
+ FG2 = "#555577"
179
+ FONT_N = ("Courier", 9)
180
+
181
+ pad = dict(padx=18, pady=6)
182
+
183
+ tk.Label(self, text="SEEDED PATH GENERATOR",
184
+ bg=BG, fg="#00d4ff", font=("Courier", 12, "bold"),
185
+ pady=14).pack(fill=tk.X)
186
+
187
+ # โ”€โ”€ Difficulty โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
188
+ diff_frame = tk.Frame(self, bg=BG)
189
+ diff_frame.pack(fill=tk.X, **pad)
190
+
191
+ tk.Label(diff_frame, text="Difficulty (0 = easy ยท 9 = brutal)",
192
+ bg=BG, fg=FG2, font=FONT_N).pack(anchor=tk.W)
193
+
194
+ row = tk.Frame(diff_frame, bg=BG)
195
+ row.pack(fill=tk.X, pady=(4, 0))
196
+
197
+ self.diff_scale = tk.Scale(
198
+ row, variable=self.difficulty,
199
+ from_=0, to=9, orient=tk.HORIZONTAL, length=320,
200
+ command=self._on_diff_change,
201
+ bg=BG, fg=FG, troughcolor="#1e1e35",
202
+ highlightthickness=0, showvalue=False, resolution=1,
203
+ )
204
+ self.diff_scale.pack(side=tk.LEFT)
205
+
206
+ self.diff_badge = tk.Label(row, text="3",
207
+ bg=DIFF_COLORS[3], fg="#ffffff",
208
+ font=("Courier", 16, "bold"),
209
+ width=3, anchor=tk.CENTER)
210
+ self.diff_badge.pack(side=tk.LEFT, padx=(10, 0))
211
+
212
+ self.diff_desc = tk.Label(diff_frame, text=self._diff_label(3),
213
+ bg=BG, fg=FG2, font=FONT_N, anchor=tk.W)
214
+ self.diff_desc.pack(anchor=tk.W, pady=(2, 0))
215
+
216
+ # โ”€โ”€ Seed โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
217
+ seed_frame = tk.Frame(self, bg=BG)
218
+ seed_frame.pack(fill=tk.X, **pad)
219
+
220
+ tk.Label(seed_frame, text="RNG seed (any integer)",
221
+ bg=BG, fg=FG2, font=FONT_N).pack(anchor=tk.W)
222
+
223
+ seed_row = tk.Frame(seed_frame, bg=BG)
224
+ seed_row.pack(fill=tk.X, pady=(4, 0))
225
+
226
+ self.seed_entry = tk.Entry(
227
+ seed_row, textvariable=self.seed,
228
+ width=10, bg="#1e1e35", fg="#00d4ff",
229
+ insertbackground="#00d4ff",
230
+ relief=tk.FLAT, font=("Courier", 13, "bold"),
231
+ justify=tk.CENTER,
232
+ )
233
+ self.seed_entry.pack(side=tk.LEFT, ipady=5)
234
+ self.seed_entry.bind("<Return>", lambda _: self._preview())
235
+ self.seed_entry.bind("<FocusOut>", lambda _: self._preview())
236
+
237
+ tk.Button(seed_row, text="โš„ Random seed",
238
+ command=self._random_seed,
239
+ bg="#1e1e35", fg=FG2,
240
+ relief=tk.FLAT, padx=10, pady=5,
241
+ font=FONT_N, cursor="hand2",
242
+ activeforeground="#ffffff", activebackground="#2a2a5a",
243
+ ).pack(side=tk.LEFT, padx=(10, 0))
244
+
245
+ # โ”€โ”€ Mini preview canvas โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
246
+ tk.Label(self, text="PREVIEW",
247
+ bg=BG, fg=FG2, font=FONT_N, anchor=tk.W,
248
+ padx=18).pack(anchor=tk.W)
249
+
250
+ self.mini = tk.Canvas(
251
+ self, width=self.MINI_W, height=self.MINI_H,
252
+ bg=AIR_COLOR, highlightthickness=1,
253
+ highlightbackground="#1e1e35",
254
+ )
255
+ self.mini.pack(padx=18, pady=(2, 10))
256
+
257
+ self.stats_var = tk.StringVar(value="")
258
+ tk.Label(self, textvariable=self.stats_var,
259
+ bg=BG, fg=FG2, font=FONT_N, anchor=tk.W,
260
+ padx=18).pack(anchor=tk.W, pady=(0, 6))
261
+
262
+ # โ”€โ”€ Buttons โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
263
+ btn_row = tk.Frame(self, bg=BG)
264
+ btn_row.pack(fill=tk.X, padx=18, pady=(4, 16))
265
+
266
+ tk.Button(btn_row, text="โœ• Cancel",
267
+ command=self.destroy,
268
+ bg="#1e1e35", fg=FG2,
269
+ relief=tk.FLAT, padx=14, pady=8,
270
+ font=FONT_N, cursor="hand2",
271
+ activeforeground="#ffffff", activebackground="#2a2a5a",
272
+ ).pack(side=tk.LEFT)
273
+
274
+ tk.Button(btn_row, text="โœ“ Apply path",
275
+ command=self._apply,
276
+ bg="#0e4a28", fg="#00ff88",
277
+ relief=tk.FLAT, padx=14, pady=8,
278
+ font=("Courier", 11, "bold"), cursor="hand2",
279
+ activeforeground="#ffffff", activebackground="#166638",
280
+ ).pack(side=tk.RIGHT)
281
+
282
+ @staticmethod
283
+ def _diff_label(d):
284
+ labels = [
285
+ "0 โ€” perfectly flat connected path",
286
+ "1 โ€” very gentle long ripples",
287
+ "2 โ€” smooth, sweeping waves",
288
+ "3 โ€” noticeable rolling hills",
289
+ "4 โ€” moderate amplitude, shorter waves",
290
+ "5 โ€” pronounced hills and valleys",
291
+ "6 โ€” steep waves, frequent up/down",
292
+ "7 โ€” aggressive continuous terrain",
293
+ "8 โ€” sharp, high-amplitude spikes",
294
+ "9 โ€” maximum chaos, continuous 3-tile staircases",
295
+ ]
296
+ return labels[d]
297
+
298
+ def _on_diff_change(self, _=None):
299
+ d = self.difficulty.get()
300
+ self.diff_badge.config(text=str(d), bg=DIFF_COLORS[d])
301
+ self.diff_desc.config(text=self._diff_label(d))
302
+ self._preview()
303
+
304
+ def _random_seed(self):
305
+ self.seed.set(random.randint(0, 99999))
306
+ self._preview()
307
+
308
+ def _preview(self):
309
+ try:
310
+ d = self.difficulty.get()
311
+ s = self.seed.get()
312
+ except tk.TclError:
313
+ return
314
+
315
+ grid = generate_seeded_path(d, s)
316
+ self._draw_mini(grid)
317
+
318
+ cells = sum(grid[r][c] for r in range(GRID_ROWS) for c in range(GRID_COLS))
319
+ col_heights = []
320
+ for c in range(GRID_COLS):
321
+ for r in range(GRID_ROWS):
322
+ if grid[r][c]:
323
+ col_heights.append(r)
324
+ break
325
+ span = (max(col_heights) - min(col_heights)) if col_heights else 0
326
+
327
+ self.stats_var.set(
328
+ f"cells: {cells} vertical span: {span} rows "
329
+ f"difficulty: {d}/9 seed: {s}"
330
+ )
331
+ self.result_grid = grid
332
+
333
+ def _draw_mini(self, grid):
334
+ mc = self.MINI_CELL
335
+ self.mini.delete("all")
336
+ self.mini.config(bg=AIR_COLOR)
337
+
338
+ for r in range(GRID_ROWS):
339
+ for c in range(GRID_COLS):
340
+ if grid[r][c]:
341
+ x0 = c * mc
342
+ y0 = r * mc
343
+ self.mini.create_rectangle(
344
+ x0, y0, x0 + mc, y0 + mc,
345
+ fill=PATH_COLOR, outline="",
346
+ )
347
+
348
+ for p in range(1, NUM_PATCHES):
349
+ x = p * PATCH_SIZE * mc
350
+ self.mini.create_line(x, 0, x, GRID_ROWS * mc,
351
+ fill="#334466", width=1)
352
+
353
+ def _apply(self):
354
+ self._preview()
355
+ self.destroy()
356
+
357
+
358
+ # โ”€โ”€ Shared blocks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
359
+ class SinusoidalTimestepEmbedding(nn.Module):
360
+ def __init__(self, embedding_dim):
361
+ super().__init__()
362
+ self.embedding_dim = embedding_dim
363
+ self.projection = nn.Sequential(
364
+ nn.Linear(embedding_dim, embedding_dim * 2), nn.SiLU(),
365
+ nn.Linear(embedding_dim * 2, embedding_dim),
366
+ )
367
+
368
+ def forward(self, timesteps):
369
+ half_dim = self.embedding_dim // 2
370
+ freqs = torch.exp(
371
+ -torch.arange(half_dim, device=timesteps.device).float() *
372
+ (torch.log(torch.tensor(10000.0)) / (half_dim - 1))
373
+ )
374
+ angles = timesteps.float().unsqueeze(1) * freqs.unsqueeze(0)
375
+ raw_emb = torch.cat([angles.sin(), angles.cos()], dim=-1)
376
+ return self.projection(raw_emb)
377
+
378
+
379
+ class ResidualBlock(nn.Module):
380
+ def __init__(self, in_channels, out_channels, time_dim):
381
+ super().__init__()
382
+ self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(time_dim, out_channels))
383
+ self.block1 = nn.Sequential(
384
+ nn.GroupNorm(min(8, in_channels), in_channels), nn.SiLU(),
385
+ nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
386
+ )
387
+ self.block2 = nn.Sequential(
388
+ nn.GroupNorm(min(8, out_channels), out_channels), nn.SiLU(),
389
+ nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
390
+ )
391
+ self.residual_conv = (
392
+ nn.Conv2d(in_channels, out_channels, kernel_size=1)
393
+ if in_channels != out_channels else nn.Identity()
394
+ )
395
+
396
+ def forward(self, x, time_embedding):
397
+ h = self.block1(x) + self.time_projection(time_embedding).unsqueeze(-1).unsqueeze(-1)
398
+ return self.block2(h) + self.residual_conv(x)
399
+
400
+
401
+ # โ”€โ”€ Legacy Mamba bottleneck (single-direction, matches old checkpoints) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
402
+ class MambaBottleneckBlockLegacy(nn.Module):
403
+ def __init__(self, channels, d_state: int = 16):
404
+ super().__init__()
405
+ self.norm = nn.GroupNorm(min(8, channels), channels)
406
+ cfg = MambaConfig(d_model=channels, n_layers=1, d_state=d_state)
407
+ self.mamba = Mamba(cfg)
408
+
409
+ def forward(self, x):
410
+ B, C, H, W = x.shape
411
+ h = self.norm(x)
412
+ seq = h.view(B, C, H * W).transpose(1, 2)
413
+ out = self.mamba(seq)
414
+ out = out.transpose(1, 2).view(B, C, H, W)
415
+ return x + out
416
+
417
+
418
+ # โ”€โ”€ Legacy Attention bottleneck โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
419
+ class AttentionBottleneckBlockLegacy(nn.Module):
420
+ def __init__(self, channels, num_heads: int = 4):
421
+ super().__init__()
422
+ self.norm = nn.GroupNorm(min(8, channels), channels)
423
+ self.attention = nn.MultiheadAttention(channels, num_heads, batch_first=True)
424
+
425
+ def forward(self, x):
426
+ B, C, H, W = x.shape
427
+ h = self.norm(x)
428
+ seq = h.view(B, C, H * W).transpose(1, 2)
429
+ out, _ = self.attention(seq, seq, seq)
430
+ out = out.transpose(1, 2).view(B, C, H, W)
431
+ return x + out
432
+
433
+
434
+ # โ”€โ”€ Mamba bottleneck (4-direction bidirectional scan) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
435
+ class MambaBottleneckBlock(nn.Module):
436
+ def __init__(self, channels, d_state: int = 16):
437
+ super().__init__()
438
+ self.norm = nn.GroupNorm(min(8, channels), channels)
439
+ cfg = MambaConfig(d_model=channels, n_layers=1, d_state=d_state)
440
+ self.mamba_row_fwd = Mamba(cfg)
441
+ self.mamba_row_bwd = Mamba(cfg)
442
+ self.mamba_col_fwd = Mamba(cfg)
443
+ self.mamba_col_bwd = Mamba(cfg)
444
+ self.merge = nn.Linear(channels * 4, channels)
445
+
446
+ def forward(self, x):
447
+ B, C, H, W = x.shape
448
+ h = self.norm(x)
449
+ seq_row = h.view(B, C, H * W).transpose(1, 2)
450
+ out_rf = self.mamba_row_fwd(seq_row)
451
+ out_rb = self.mamba_row_bwd(seq_row.flip(1)).flip(1)
452
+ seq_col = h.permute(0, 1, 3, 2).contiguous().view(B, C, H * W).transpose(1, 2)
453
+ out_cf = self.mamba_col_fwd(seq_col)
454
+ out_cb = self.mamba_col_bwd(seq_col.flip(1)).flip(1)
455
+ merged = torch.cat([out_rf, out_rb, out_cf, out_cb], dim=-1)
456
+ merged = self.merge(merged).transpose(1, 2).view(B, C, H, W)
457
+ return x + merged
458
+
459
+
460
+ # โ”€โ”€ Attention bottleneck โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
461
+ class AttentionBottleneckBlock(nn.Module):
462
+ def __init__(self, channels, num_heads: int = 4):
463
+ super().__init__()
464
+ self.norm = nn.GroupNorm(min(8, channels), channels)
465
+ self.attn = nn.MultiheadAttention(channels, num_heads, batch_first=True)
466
+ self.proj = nn.Linear(channels, channels)
467
+
468
+ def forward(self, x):
469
+ B, C, H, W = x.shape
470
+ h = self.norm(x)
471
+ seq = h.view(B, C, H * W).transpose(1, 2)
472
+ out, _ = self.attn(seq, seq, seq)
473
+ out = self.proj(out)
474
+ out = out.transpose(1, 2).view(B, C, H, W)
475
+ return x + out
476
+
477
+
478
+ # โ”€โ”€ UNet โ€” Legacy Mamba variant โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
479
+ class UNetDenoiserMambaLegacy(nn.Module):
480
+ def __init__(self, in_channels, base_channels, time_dim):
481
+ super().__init__()
482
+ ch = base_channels
483
+ self.timestep_embedder = SinusoidalTimestepEmbedding(time_dim)
484
+ self.input_conv = nn.Conv2d(in_channels, ch, kernel_size=3, padding=1)
485
+ self.down1 = ResidualBlock(ch, ch * 2, time_dim)
486
+ self.down2 = ResidualBlock(ch * 2, ch * 4, time_dim)
487
+ self.pool = nn.MaxPool2d(2)
488
+ self.bottleneck1 = ResidualBlock(ch * 4, ch * 4, time_dim)
489
+ self.bottleneck_block = MambaBottleneckBlockLegacy(ch * 4, d_state=16)
490
+ self.bottleneck2 = ResidualBlock(ch * 4, ch * 4, time_dim)
491
+ self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
492
+ self.up2 = ResidualBlock(ch * 4 + ch * 4, ch * 2, time_dim)
493
+ self.up1 = ResidualBlock(ch * 2 + ch * 2, ch, time_dim)
494
+ self.output_conv = nn.Sequential(
495
+ nn.GroupNorm(min(8, ch), ch), nn.SiLU(),
496
+ nn.Conv2d(ch, in_channels, kernel_size=1),
497
+ )
498
+
499
+ def forward(self, noisy_patch, timesteps):
500
+ time_emb = self.timestep_embedder(timesteps)
501
+ x = self.input_conv(noisy_patch)
502
+ d1 = self.down1(x, time_emb); d1p = self.pool(d1)
503
+ d2 = self.down2(d1p, time_emb); d2p = self.pool(d2)
504
+ b = self.bottleneck1(d2p, time_emb)
505
+ b = self.bottleneck_block(b)
506
+ b = self.bottleneck2(b, time_emb)
507
+ u2 = self.up2(torch.cat([self.upsample(b), d2], dim=1), time_emb)
508
+ u1 = self.up1(torch.cat([self.upsample(u2), d1], dim=1), time_emb)
509
+ return self.output_conv(u1)
510
+
511
+
512
+ # โ”€โ”€ UNet โ€” Legacy Attention variant โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
513
+ class UNetDenoiserAttentionLegacy(nn.Module):
514
+ def __init__(self, in_channels, base_channels, time_dim):
515
+ super().__init__()
516
+ ch = base_channels
517
+ self.timestep_embedder = SinusoidalTimestepEmbedding(time_dim)
518
+ self.input_conv = nn.Conv2d(in_channels, ch, kernel_size=3, padding=1)
519
+ self.down1 = ResidualBlock(ch, ch * 2, time_dim)
520
+ self.down2 = ResidualBlock(ch * 2, ch * 4, time_dim)
521
+ self.pool = nn.MaxPool2d(2)
522
+ self.bottleneck1 = ResidualBlock(ch * 4, ch * 4, time_dim)
523
+ self.bottleneck_block = AttentionBottleneckBlockLegacy(ch * 4, num_heads=4)
524
+ self.bottleneck2 = ResidualBlock(ch * 4, ch * 4, time_dim)
525
+ self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
526
+ self.up2 = ResidualBlock(ch * 4 + ch * 4, ch * 2, time_dim)
527
+ self.up1 = ResidualBlock(ch * 2 + ch * 2, ch, time_dim)
528
+ self.output_conv = nn.Sequential(
529
+ nn.GroupNorm(min(8, ch), ch), nn.SiLU(),
530
+ nn.Conv2d(ch, in_channels, kernel_size=1),
531
+ )
532
+
533
+ def forward(self, noisy_patch, timesteps):
534
+ time_emb = self.timestep_embedder(timesteps)
535
+ x = self.input_conv(noisy_patch)
536
+ d1 = self.down1(x, time_emb); d1p = self.pool(d1)
537
+ d2 = self.down2(d1p, time_emb); d2p = self.pool(d2)
538
+ b = self.bottleneck1(d2p, time_emb)
539
+ b = self.bottleneck_block(b)
540
+ b = self.bottleneck2(b, time_emb)
541
+ u2 = self.up2(torch.cat([self.upsample(b), d2], dim=1), time_emb)
542
+ u1 = self.up1(torch.cat([self.upsample(u2), d1], dim=1), time_emb)
543
+ return self.output_conv(u1)
544
+
545
+
546
+ # โ”€โ”€ UNet โ€” Mamba variant โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
547
+ class UNetDenoiserMamba(nn.Module):
548
+ def __init__(self, in_channels, base_channels, time_dim):
549
+ super().__init__()
550
+ ch = base_channels
551
+ self.timestep_embedder = SinusoidalTimestepEmbedding(time_dim)
552
+ self.input_conv = nn.Conv2d(in_channels, ch, kernel_size=3, padding=1)
553
+ self.down1 = ResidualBlock(ch, ch * 2, time_dim)
554
+ self.down2 = ResidualBlock(ch * 2, ch * 4, time_dim)
555
+ self.pool = nn.MaxPool2d(2)
556
+ self.bottleneck1 = ResidualBlock(ch * 4, ch * 4, time_dim)
557
+ self.bottleneck_mamba = MambaBottleneckBlock(ch * 4, d_state=16)
558
+ self.bottleneck2 = ResidualBlock(ch * 4, ch * 4, time_dim)
559
+ self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
560
+ self.up2 = ResidualBlock(ch * 4 + ch * 4, ch * 2, time_dim)
561
+ self.up1 = ResidualBlock(ch * 2 + ch * 2, ch, time_dim)
562
+ self.output_conv = nn.Sequential(
563
+ nn.GroupNorm(min(8, ch), ch), nn.SiLU(),
564
+ nn.Conv2d(ch, in_channels, kernel_size=1),
565
+ )
566
+
567
+ def forward(self, noisy_patch, timesteps):
568
+ time_emb = self.timestep_embedder(timesteps)
569
+ x = self.input_conv(noisy_patch)
570
+ d1 = self.down1(x, time_emb); d1p = self.pool(d1)
571
+ d2 = self.down2(d1p, time_emb); d2p = self.pool(d2)
572
+ b = self.bottleneck1(d2p, time_emb)
573
+ b = self.bottleneck_mamba(b)
574
+ b = self.bottleneck2(b, time_emb)
575
+ u2 = self.up2(torch.cat([self.upsample(b), d2], dim=1), time_emb)
576
+ u1 = self.up1(torch.cat([self.upsample(u2), d1], dim=1), time_emb)
577
+ return self.output_conv(u1)
578
+
579
+
580
+ # โ”€โ”€ UNet โ€” Attention variant โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
581
+ class UNetDenoiserAttention(nn.Module):
582
+ def __init__(self, in_channels, base_channels, time_dim):
583
+ super().__init__()
584
+ ch = base_channels
585
+ self.timestep_embedder = SinusoidalTimestepEmbedding(time_dim)
586
+ self.input_conv = nn.Conv2d(in_channels, ch, kernel_size=3, padding=1)
587
+ self.down1 = ResidualBlock(ch, ch * 2, time_dim)
588
+ self.down2 = ResidualBlock(ch * 2, ch * 4, time_dim)
589
+ self.pool = nn.MaxPool2d(2)
590
+ self.bottleneck1 = ResidualBlock(ch * 4, ch * 4, time_dim)
591
+ self.bottleneck_attn = AttentionBottleneckBlock(ch * 4, num_heads=4)
592
+ self.bottleneck2 = ResidualBlock(ch * 4, ch * 4, time_dim)
593
+ self.upsample = nn.Upsample(scale_factor=2, mode="nearest")
594
+ self.up2 = ResidualBlock(ch * 4 + ch * 4, ch * 2, time_dim)
595
+ self.up1 = ResidualBlock(ch * 2 + ch * 2, ch, time_dim)
596
+ self.output_conv = nn.Sequential(
597
+ nn.GroupNorm(min(8, ch), ch), nn.SiLU(),
598
+ nn.Conv2d(ch, in_channels, kernel_size=1),
599
+ )
600
+
601
+ def forward(self, noisy_patch, timesteps):
602
+ time_emb = self.timestep_embedder(timesteps)
603
+ x = self.input_conv(noisy_patch)
604
+ d1 = self.down1(x, time_emb); d1p = self.pool(d1)
605
+ d2 = self.down2(d1p, time_emb); d2p = self.pool(d2)
606
+ b = self.bottleneck1(d2p, time_emb)
607
+ b = self.bottleneck_attn(b)
608
+ b = self.bottleneck2(b, time_emb)
609
+ u2 = self.up2(torch.cat([self.upsample(b), d2], dim=1), time_emb)
610
+ u1 = self.up1(torch.cat([self.upsample(u2), d1], dim=1), time_emb)
611
+ return self.output_conv(u1)
612
+
613
+
614
+ # โ”€โ”€ Auto-detect architecture from checkpoint state dict keys โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
615
+ def detect_arch_from_checkpoint(state_dict_keys):
616
+ for key in state_dict_keys:
617
+ if "bottleneck_block.mamba" in key: return "mamba_legacy"
618
+ if "bottleneck_block.attention" in key: return "attention_legacy"
619
+ if "bottleneck_mamba" in key: return "mamba"
620
+ if "bottleneck_attn" in key: return "attention"
621
+ return "mamba_legacy"
622
+
623
+
624
+ def build_model_from_checkpoint(ckpt):
625
+ arch = detect_arch_from_checkpoint(ckpt["model_state_dict"].keys())
626
+ CLASS_MAP = {
627
+ "mamba_legacy": UNetDenoiserMambaLegacy,
628
+ "attention_legacy": UNetDenoiserAttentionLegacy,
629
+ "mamba": UNetDenoiserMamba,
630
+ "attention": UNetDenoiserAttention,
631
+ }
632
+ model = CLASS_MAP[arch](
633
+ in_channels = ckpt["num_tile_types"],
634
+ base_channels = ckpt["base_channels"],
635
+ time_dim = ckpt["time_dim"],
636
+ )
637
+ model.load_state_dict(ckpt["model_state_dict"])
638
+ model.eval()
639
+ return model, arch.replace("_", "-")
640
+
641
+
642
+ def load_checkpoint(path):
643
+ path = pathlib.Path(path)
644
+ if path.is_dir():
645
+ root_dir = path
646
+ if not (root_dir / "data.pkl").exists():
647
+ subdirs = [d for d in root_dir.iterdir() if d.is_dir()]
648
+ if len(subdirs) == 1 and (subdirs[0] / "data.pkl").exists():
649
+ root_dir = subdirs[0]
650
+ else:
651
+ raise ValueError(
652
+ "Directory checkpoint must contain data.pkl or a single subdirectory with data.pkl"
653
+ )
654
+
655
+ data_path = root_dir / "data.pkl"
656
+ with open(data_path, "rb") as f:
657
+ class CheckpointUnpickler(pickle.Unpickler):
658
+ def persistent_load(self, saved_id):
659
+ if saved_id[0] != "storage":
660
+ raise RuntimeError(f"Unexpected persistent id: {saved_id}")
661
+ storage_type, key, location, numel = saved_id[1:]
662
+ storage_file = root_dir / "data" / key
663
+ return storage_type.from_file(str(storage_file), False, numel)
664
+
665
+ return CheckpointUnpickler(f).load()
666
+
667
+ return torch.load(str(path), map_location=DEVICE, weights_only=False)
668
+
669
+
670
+ # โ”€โ”€ Diffusion helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
671
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
672
+
673
+
674
+ def build_alpha_bar(num_steps):
675
+ steps = torch.arange(num_steps + 1, dtype=torch.float)
676
+ alpha_bar = torch.cos(((steps / num_steps) + 0.008) / 1.008 * torch.pi * 0.5) ** 2
677
+ alpha_bar = alpha_bar / alpha_bar[0]
678
+ return alpha_bar[1:]
679
+
680
+
681
+ @torch.no_grad()
682
+ def run_generation(path_mask_2d, model, alpha_bar, tile_to_index,
683
+ num_tile_types, diffusion_steps,
684
+ enemy_bias=0.0, num_inference_steps=200):
685
+ model.eval()
686
+ path_mask_2d = path_mask_2d.to(DEVICE)
687
+ enemy_idx = tile_to_index.get("E", None)
688
+ path_idx = tile_to_index.get(PATH_TILE, 0)
689
+
690
+ path_onehot = torch.zeros(1, num_tile_types, PATCH_SIZE, PATCH_SIZE, device=DEVICE)
691
+ path_onehot[0, path_idx] = path_mask_2d
692
+
693
+ noisy_x = torch.randn(1, num_tile_types, PATCH_SIZE, PATCH_SIZE, device=DEVICE)
694
+ frozen = path_mask_2d.unsqueeze(0).unsqueeze(0).expand_as(noisy_x)
695
+ noisy_x = frozen * path_onehot + (1 - frozen) * noisy_x
696
+
697
+ steps = torch.linspace(diffusion_steps - 1, 0, num_inference_steps).long().to(DEVICE)
698
+
699
+ for timestep in steps:
700
+ t_batch = timestep.unsqueeze(0)
701
+ pred = model(noisy_x, t_batch)
702
+
703
+ if enemy_bias != 0.0 and enemy_idx is not None:
704
+ pred[:, enemy_idx] += enemy_bias
705
+
706
+ ab_prev = alpha_bar[timestep - 1] if timestep > 0 else torch.tensor(1.0, device=DEVICE)
707
+ if timestep > 0:
708
+ noise = torch.randn_like(noisy_x)
709
+ noisy_x = torch.sqrt(ab_prev) * pred + torch.sqrt(1 - ab_prev) * noise * 0.1
710
+ else:
711
+ noisy_x = pred
712
+ noisy_x = frozen * path_onehot + (1 - frozen) * noisy_x
713
+
714
+ tile_ids = noisy_x[0].argmax(dim=0).cpu().numpy()
715
+ path_flags = path_mask_2d.cpu().numpy()
716
+ return tile_ids, path_flags
717
+
718
+
719
+ def decode_patch(tile_ids, path_flags, index_to_tile):
720
+ return [
721
+ [
722
+ PATH_TILE if path_flags[r][c] == 1.0
723
+ else index_to_tile.get(int(tile_ids[r][c]), AIR_TILE)
724
+ for c in range(PATCH_SIZE)
725
+ ]
726
+ for r in range(PATCH_SIZE)
727
+ ]
728
+
729
+
730
+ # โ”€โ”€ Sprite viewer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
731
+ def open_sprite_viewer(parent, level_grid):
732
+ level_as_strings = ["".join(row) for row in level_grid]
733
+ result = convert_level_to_png(level_as_strings)
734
+ sprite_image = result[0]
735
+
736
+ viewer = tk.Toplevel(parent)
737
+ viewer.title("Generated Level โ€” Real Mario Tile Sprites")
738
+ viewer.configure(bg="#0b0b18")
739
+
740
+ img_width, img_height = sprite_image.size
741
+ screen_width = viewer.winfo_screenwidth()
742
+ scale_factor = max(1, min(4, screen_width // img_width))
743
+ display_image = sprite_image.resize(
744
+ (img_width * scale_factor, img_height * scale_factor), Image.NEAREST
745
+ )
746
+ photo = ImageTk.PhotoImage(display_image)
747
+
748
+ tk.Label(viewer, text="Real Mario Tile Sprites (via mario-gpt)",
749
+ bg="#0b0b18", fg="#9999cc", font=("Courier", 10, "bold"), pady=8
750
+ ).pack(side=tk.TOP, fill=tk.X)
751
+
752
+ canvas_frame = tk.Frame(viewer, bg="#0b0b18")
753
+ canvas_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
754
+
755
+ h_scroll = tk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL,
756
+ bg="#111128", troughcolor="#0b0b18", activebackground="#2a2a50")
757
+ h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
758
+ v_scroll = tk.Scrollbar(canvas_frame, orient=tk.VERTICAL,
759
+ bg="#111128", troughcolor="#0b0b18", activebackground="#2a2a50")
760
+ v_scroll.pack(side=tk.RIGHT, fill=tk.Y)
761
+
762
+ canvas_w = min(display_image.width, screen_width - 60)
763
+ canvas_h = min(display_image.height, viewer.winfo_screenheight() - 160)
764
+ sprite_canvas = tk.Canvas(
765
+ canvas_frame, width=canvas_w, height=canvas_h,
766
+ scrollregion=(0, 0, display_image.width, display_image.height),
767
+ bg="#0b0b18", highlightthickness=0,
768
+ xscrollcommand=h_scroll.set, yscrollcommand=v_scroll.set,
769
+ )
770
+ sprite_canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
771
+ h_scroll.config(command=sprite_canvas.xview)
772
+ v_scroll.config(command=sprite_canvas.yview)
773
+ sprite_canvas.create_image(0, 0, anchor=tk.NW, image=photo)
774
+ sprite_canvas.image = photo
775
+
776
+ tk.Button(viewer, text="๐Ÿ’พ Save Sprite Image",
777
+ command=lambda: _save_sprite(sprite_image),
778
+ bg="#1e1e40", fg="#9999cc", relief=tk.FLAT, padx=12, pady=6,
779
+ font=("Courier", 10, "bold"), cursor="hand2",
780
+ activeforeground="#ffffff", activebackground="#2a2a5a"
781
+ ).pack(side=tk.BOTTOM, pady=(0, 10))
782
+
783
+
784
+ def _save_sprite(pil_image):
785
+ save_path = filedialog.asksaveasfilename(
786
+ title="Save sprite image", defaultextension=".png",
787
+ filetypes=[("PNG image", "*.png"), ("All files", "*.*")]
788
+ )
789
+ if save_path:
790
+ pil_image.save(save_path)
791
+ messagebox.showinfo("Saved", f"Sprite image saved to:\n{save_path}")
792
+
793
+
794
+ # โ”€โ”€ Model slot dataclass โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
795
+ class ModelSlot:
796
+ def __init__(self):
797
+ self.model = None
798
+ self.alpha_bar = None
799
+ self.tile_to_index = None
800
+ self.index_to_tile = None
801
+ self.num_tile_types = None
802
+ self.diffusion_steps = None
803
+ self.arch = None
804
+ self.filename = None
805
+
806
+ @property
807
+ def is_loaded(self):
808
+ return self.model is not None
809
+
810
+ def load(self, path):
811
+ ckpt = load_checkpoint(path)
812
+ self.tile_to_index = ckpt["tile_to_index"]
813
+ self.index_to_tile = ckpt["index_to_tile"]
814
+ self.num_tile_types = ckpt["num_tile_types"]
815
+ self.diffusion_steps = ckpt["diffusion_steps"]
816
+ self.model, self.arch = build_model_from_checkpoint(ckpt)
817
+ self.model.to(DEVICE)
818
+ self.alpha_bar = build_alpha_bar(self.diffusion_steps).to(DEVICE)
819
+ self.filename = pathlib.Path(path).name
820
+
821
+
822
+ # โ”€โ”€ Main application โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
823
+ class App:
824
+ def __init__(self, root):
825
+ self.root = root
826
+ self.root.title("Mario Path โ†’ Level Generator [Dual Model โ€” Mamba vs Attention]")
827
+ self.root.configure(bg="#0b0b18")
828
+
829
+ self.slot_a = ModelSlot()
830
+ self.slot_b = ModelSlot()
831
+ self.active_slot_var = tk.StringVar(value="A")
832
+
833
+ self.path_grid = [[False] * GRID_COLS for _ in range(GRID_ROWS)]
834
+ self.generated_grid = None
835
+ self.is_generated = False
836
+ self.drawing = False
837
+ self.patch_enemy_bias = {i: 0.0 for i in range(NUM_PATCHES)}
838
+ self.selected_patch = 0
839
+
840
+ # Track last used seed/difficulty for status display
841
+ self._last_seed = None
842
+ self._last_difficulty = None
843
+
844
+ self.cell_rects = [[None] * GRID_COLS for _ in range(GRID_ROWS)]
845
+ self.patch_overlays = [None] * NUM_PATCHES
846
+
847
+ self._build_ui()
848
+ self._build_cells()
849
+ self._build_patch_overlays()
850
+ self._refresh_patch_ui()
851
+ self._refresh_model_ui()
852
+
853
+ @property
854
+ def active_slot(self) -> ModelSlot:
855
+ return self.slot_a if self.active_slot_var.get() == "A" else self.slot_b
856
+
857
+ def _build_ui(self):
858
+ BG = "#0b0b18"
859
+ btn = dict(relief=tk.FLAT, padx=10, pady=6,
860
+ font=("Courier", 10, "bold"), cursor="hand2",
861
+ activeforeground="#ffffff")
862
+
863
+ # โ”€โ”€ Model selector bar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
864
+ model_bar = tk.Frame(self.root, bg="#0d0d22", pady=8, padx=14)
865
+ model_bar.pack(side=tk.TOP, fill=tk.X)
866
+
867
+ tk.Label(model_bar, text="MODELS",
868
+ bg="#0d0d22", fg="#555577",
869
+ font=("Courier", 8, "bold"), padx=6).pack(side=tk.LEFT)
870
+
871
+ self.slot_a_frame = tk.Frame(model_bar, bg="#0a1a2a",
872
+ highlightbackground=MODEL_A_COLOR,
873
+ highlightthickness=1, padx=8, pady=4)
874
+ self.slot_a_frame.pack(side=tk.LEFT, padx=(8, 4))
875
+
876
+ self.radio_a = tk.Radiobutton(
877
+ self.slot_a_frame, text="Model A",
878
+ variable=self.active_slot_var, value="A",
879
+ command=self._refresh_model_ui,
880
+ bg="#0a1a2a", fg=MODEL_A_COLOR, selectcolor="#0a1a2a",
881
+ activebackground="#0a1a2a", activeforeground=MODEL_A_COLOR,
882
+ font=("Courier", 10, "bold"),
883
+ )
884
+ self.radio_a.pack(side=tk.LEFT)
885
+
886
+ tk.Button(self.slot_a_frame, text="๐Ÿ“‚ Load",
887
+ command=lambda: self.load_model("A"),
888
+ bg="#0a1a2a", fg=MODEL_A_COLOR,
889
+ activebackground="#102030", **btn).pack(side=tk.LEFT, padx=(6, 0))
890
+
891
+ self.label_a = tk.Label(self.slot_a_frame, text="โ€” not loaded",
892
+ bg="#0a1a2a", fg="#2a3a4a",
893
+ font=("Courier", 9), padx=6)
894
+ self.label_a.pack(side=tk.LEFT)
895
+
896
+ tk.Label(model_bar, text=" VS ",
897
+ bg="#0d0d22", fg="#333355",
898
+ font=("Courier", 11, "bold")).pack(side=tk.LEFT, padx=4)
899
+
900
+ self.slot_b_frame = tk.Frame(model_bar, bg="#1a0a2a",
901
+ highlightbackground=MODEL_B_COLOR,
902
+ highlightthickness=1, padx=8, pady=4)
903
+ self.slot_b_frame.pack(side=tk.LEFT, padx=(4, 16))
904
+
905
+ self.radio_b = tk.Radiobutton(
906
+ self.slot_b_frame, text="Model B",
907
+ variable=self.active_slot_var, value="B",
908
+ command=self._refresh_model_ui,
909
+ bg="#1a0a2a", fg=MODEL_B_COLOR, selectcolor="#1a0a2a",
910
+ activebackground="#1a0a2a", activeforeground=MODEL_B_COLOR,
911
+ font=("Courier", 10, "bold"),
912
+ )
913
+ self.radio_b.pack(side=tk.LEFT)
914
+
915
+ tk.Button(self.slot_b_frame, text="๐Ÿ“‚ Load",
916
+ command=lambda: self.load_model("B"),
917
+ bg="#1a0a2a", fg=MODEL_B_COLOR,
918
+ activebackground="#200a3a", **btn).pack(side=tk.LEFT, padx=(6, 0))
919
+
920
+ self.label_b = tk.Label(self.slot_b_frame, text="โ€” not loaded",
921
+ bg="#1a0a2a", fg="#3a2a4a",
922
+ font=("Courier", 9), padx=6)
923
+ self.label_b.pack(side=tk.LEFT)
924
+
925
+ # โ”€โ”€ Action buttons โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
926
+ top = tk.Frame(self.root, bg=BG, pady=8)
927
+ top.pack(side=tk.TOP, fill=tk.X, padx=14)
928
+
929
+ tk.Button(top, text="๐Ÿ—‘ Clear", command=self.clear,
930
+ bg="#1e1e40", fg="#9999cc", activebackground="#2a2a5a",
931
+ **btn).pack(side=tk.LEFT, padx=(0, 8))
932
+
933
+ # โ”€โ”€ Auto Path button โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
934
+ tk.Button(top, text="๐ŸŽฒ Auto Path",
935
+ command=self.open_seed_dialog,
936
+ bg="#1a1a00", fg="#ffdd55",
937
+ activebackground="#2a2a00",
938
+ **btn).pack(side=tk.LEFT, padx=(0, 8))
939
+
940
+ self.reset_btn = tk.Button(top, text="โ†ฉ Draw Again", command=self.reset_to_draw,
941
+ bg="#3a2200", fg="#ffaa33",
942
+ activebackground="#553300", **btn)
943
+ self.sprite_btn = tk.Button(top, text="๐ŸŽฎ Show Sprites", command=self.show_sprites,
944
+ bg="#1a0a3a", fg="#bd93f9",
945
+ activebackground="#2a1060", **btn)
946
+
947
+ tk.Button(top, text="โšก Generate Level", command=self.generate,
948
+ bg="#0e4a28", fg="#00ff88", activebackground="#166638",
949
+ **btn).pack(side=tk.RIGHT)
950
+ tk.Label(top, text="Left-drag: paint path Right-drag: erase",
951
+ bg=BG, fg="#2a2a44", font=("Courier", 8)).pack(side=tk.RIGHT, padx=14)
952
+
953
+ # โ”€โ”€ Legend โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
954
+ legend_frame = tk.Frame(self.root, bg=BG)
955
+ legend_frame.pack(side=tk.TOP, fill=tk.X, padx=14, pady=(0, 4))
956
+ for label, color in [
957
+ ("path (x)", "#00d4ff"), ("ground (X)", "#4a3728"),
958
+ ("brick (S)", "#8b6914"), ("? block", "#f5c518"),
959
+ ("Q block", "#e8a000"), ("enemy (E)", "#c0392b"),
960
+ ("pipe", "#27ae60"), ("coin (o)", "#f39c12"),
961
+ ("air (-)", "#1a1a2e"),
962
+ ]:
963
+ tk.Label(legend_frame, text=" ", bg=color, width=2).pack(side=tk.LEFT, padx=(0, 2), pady=2)
964
+ tk.Label(legend_frame, text=label + " ", bg=BG, fg="#555577",
965
+ font=("Courier", 8)).pack(side=tk.LEFT)
966
+
967
+ # โ”€โ”€ Difficulty indicator โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
968
+ self.diff_indicator_var = tk.StringVar(value="")
969
+ tk.Label(legend_frame, textvariable=self.diff_indicator_var,
970
+ bg=BG, fg="#ffdd55", font=("Courier", 8, "bold"), padx=12,
971
+ ).pack(side=tk.RIGHT)
972
+
973
+ # โ”€โ”€ Canvas โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
974
+ canvas_frame = tk.Frame(self.root, bg=BG)
975
+ canvas_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True, padx=14, pady=(0, 0))
976
+
977
+ h_scroll = tk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL,
978
+ bg="#111128", troughcolor="#0b0b18", activebackground="#2a2a50")
979
+ h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
980
+
981
+ screen_w = self.root.winfo_screenwidth()
982
+ canvas_w = min(GRID_COLS * CELL_SIZE, screen_w - 60)
983
+ canvas_h = GRID_ROWS * CELL_SIZE
984
+
985
+ self.canvas = tk.Canvas(
986
+ canvas_frame, width=canvas_w, height=canvas_h,
987
+ scrollregion=(0, 0, GRID_COLS * CELL_SIZE, canvas_h),
988
+ bg=AIR_COLOR, highlightthickness=0,
989
+ xscrollcommand=h_scroll.set,
990
+ )
991
+ self.canvas.pack(side=tk.TOP)
992
+ h_scroll.config(command=self.canvas.xview)
993
+
994
+ self.canvas.bind("<ButtonPress-1>", self._on_canvas_press)
995
+ self.canvas.bind("<B1-Motion>", self._draw_move)
996
+ self.canvas.bind("<ButtonRelease-1>", self._draw_stop)
997
+ self.canvas.bind("<ButtonPress-3>", self._erase_start)
998
+ self.canvas.bind("<B3-Motion>", self._erase_move)
999
+
1000
+ # โ”€โ”€ Patch enemy bias bar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1001
+ bias_bar = tk.Frame(self.root, bg="#0d0d20", pady=6)
1002
+ bias_bar.pack(side=tk.TOP, fill=tk.X, padx=14, pady=(4, 0))
1003
+
1004
+ tk.Label(bias_bar, text="PATCH ENEMY BIAS",
1005
+ bg="#0d0d20", fg="#c0392b",
1006
+ font=("Courier", 8, "bold"), padx=8).pack(side=tk.LEFT)
1007
+ tk.Label(bias_bar, text="click patch to select โ†’",
1008
+ bg="#0d0d20", fg="#2a2a44",
1009
+ font=("Courier", 8), padx=4).pack(side=tk.LEFT)
1010
+
1011
+ self.patch_btns = []
1012
+ for i in range(NUM_PATCHES):
1013
+ col_start = i * PATCH_SIZE
1014
+ col_end = min(col_start + PATCH_SIZE - 1, GRID_COLS - 1)
1015
+ b = tk.Button(
1016
+ bias_bar,
1017
+ text=f"P{i+1}\n{col_start}โ€“{col_end}",
1018
+ command=lambda idx=i: self.select_patch(idx),
1019
+ bg="#1e1e35", fg="#555577",
1020
+ relief=tk.FLAT, padx=8, pady=4,
1021
+ font=("Courier", 8, "bold"), cursor="hand2",
1022
+ activeforeground="#ffffff", activebackground="#2a0010",
1023
+ )
1024
+ b.pack(side=tk.LEFT, padx=(0, 4))
1025
+ self.patch_btns.append(b)
1026
+
1027
+ tk.Label(bias_bar, text=" enemy bias:",
1028
+ bg="#0d0d20", fg="#888899",
1029
+ font=("Courier", 9), padx=6).pack(side=tk.LEFT)
1030
+
1031
+ self.bias_var = tk.StringVar(value="0.0")
1032
+ self.bias_entry = tk.Entry(
1033
+ bias_bar, textvariable=self.bias_var,
1034
+ width=7, bg="#1e1e35", fg="#c0392b",
1035
+ insertbackground="#c0392b",
1036
+ relief=tk.FLAT, font=("Courier", 12, "bold"),
1037
+ justify=tk.CENTER,
1038
+ )
1039
+ self.bias_entry.pack(side=tk.LEFT, padx=(0, 6), ipady=4)
1040
+ self.bias_entry.bind("<Return>", self._on_bias_changed)
1041
+ self.bias_entry.bind("<FocusOut>", self._on_bias_changed)
1042
+
1043
+ tk.Label(bias_bar,
1044
+ text=" (0 = neutral | positive = more enemies | negative = suppress โ€” press Enter to apply)",
1045
+ bg="#0d0d20", fg="#2a2a44", font=("Courier", 7)
1046
+ ).pack(side=tk.LEFT, padx=8)
1047
+
1048
+ # โ”€โ”€ Status bar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1049
+ self.status_var = tk.StringVar(value="Load models A and/or B, draw a path (or use ๐ŸŽฒ Auto Path), then hit Generate.")
1050
+ tk.Label(self.root, textvariable=self.status_var,
1051
+ bg="#070710", fg="#44446a",
1052
+ font=("Courier", 9), anchor=tk.W, padx=14, pady=5
1053
+ ).pack(side=tk.BOTTOM, fill=tk.X)
1054
+
1055
+ def _build_cells(self):
1056
+ for row in range(GRID_ROWS):
1057
+ for col in range(GRID_COLS):
1058
+ x0 = col * CELL_SIZE
1059
+ y0 = row * CELL_SIZE
1060
+ rid = self.canvas.create_rectangle(
1061
+ x0, y0, x0 + CELL_SIZE, y0 + CELL_SIZE,
1062
+ fill=AIR_COLOR, outline=GRID_LINE, width=1,
1063
+ )
1064
+ self.cell_rects[row][col] = rid
1065
+
1066
+ def _build_patch_overlays(self):
1067
+ canvas_h = GRID_ROWS * CELL_SIZE
1068
+ for i in range(NUM_PATCHES):
1069
+ x0 = i * PATCH_SIZE * CELL_SIZE
1070
+ x1 = min((i + 1) * PATCH_SIZE * CELL_SIZE, GRID_COLS * CELL_SIZE)
1071
+ oid = self.canvas.create_rectangle(
1072
+ x0, 0, x1, canvas_h,
1073
+ fill="", outline=PATCH_IDLE_COLOR, width=2,
1074
+ )
1075
+ self.patch_overlays[i] = oid
1076
+ self.canvas.tag_raise(oid)
1077
+
1078
+ def _refresh_model_ui(self):
1079
+ is_a_active = self.active_slot_var.get() == "A"
1080
+ self.slot_a_frame.config(
1081
+ highlightbackground=MODEL_A_COLOR if is_a_active else "#1a1a30",
1082
+ highlightthickness=2 if is_a_active else 1,
1083
+ )
1084
+ self.slot_b_frame.config(
1085
+ highlightbackground=MODEL_B_COLOR if not is_a_active else "#1a1a30",
1086
+ highlightthickness=2 if not is_a_active else 1,
1087
+ )
1088
+
1089
+ def _update_slot_label(self, slot_name: str):
1090
+ slot = self.slot_a if slot_name == "A" else self.slot_b
1091
+ label = self.label_a if slot_name == "A" else self.label_b
1092
+ color = MODEL_A_COLOR if slot_name == "A" else MODEL_B_COLOR
1093
+ bg = "#0a1a2a" if slot_name == "A" else "#1a0a2a"
1094
+ arch_tag = f"[{slot.arch}]" if slot.arch else ""
1095
+ label.config(text=f"โœ“ {slot.filename} {arch_tag}", fg=color, bg=bg)
1096
+
1097
+ def select_patch(self, idx):
1098
+ self.selected_patch = idx
1099
+ self._refresh_patch_ui()
1100
+
1101
+ def _refresh_patch_ui(self):
1102
+ for i, btn in enumerate(self.patch_btns):
1103
+ if i == self.selected_patch:
1104
+ btn.config(bg="#3a0010", fg="#ff5555")
1105
+ else:
1106
+ btn.config(bg="#1e1e35", fg="#555577")
1107
+
1108
+ for i, oid in enumerate(self.patch_overlays):
1109
+ if i == self.selected_patch:
1110
+ self.canvas.itemconfig(oid, outline=PATCH_SEL_COLOR, width=2,
1111
+ fill="#ff0000", stipple="gray12")
1112
+ elif self.patch_enemy_bias.get(i, 0.0) != 0.0:
1113
+ self.canvas.itemconfig(oid, outline="#883333", width=1,
1114
+ fill="#ff0000", stipple="gray12")
1115
+ else:
1116
+ self.canvas.itemconfig(oid, outline=PATCH_IDLE_COLOR, width=2,
1117
+ fill="", stipple="")
1118
+
1119
+ self.bias_var.set(str(self.patch_enemy_bias.get(self.selected_patch, 0.0)))
1120
+ self._update_bias_color()
1121
+
1122
+ def _on_bias_changed(self, _=None):
1123
+ try:
1124
+ val = float(self.bias_var.get())
1125
+ except ValueError:
1126
+ val = 0.0
1127
+ self.bias_var.set(str(val))
1128
+ self.patch_enemy_bias[self.selected_patch] = val
1129
+ self._refresh_patch_ui()
1130
+
1131
+ def _update_bias_color(self):
1132
+ val = self.patch_enemy_bias.get(self.selected_patch, 0.0)
1133
+ color = "#c0392b" if val > 0 else ("#5599ff" if val < 0 else "#888899")
1134
+ self.bias_entry.config(fg=color)
1135
+
1136
+ def _color_for(self, row, col):
1137
+ if self.is_generated:
1138
+ return TILE_COLOR_MAP.get(self.generated_grid[row][col], DEFAULT_COLOR)
1139
+ return PATH_COLOR if self.path_grid[row][col] else AIR_COLOR
1140
+
1141
+ def _repaint_cell(self, row, col):
1142
+ self.canvas.itemconfig(self.cell_rects[row][col], fill=self._color_for(row, col))
1143
+
1144
+ def _repaint_all(self):
1145
+ for r in range(GRID_ROWS):
1146
+ for c in range(GRID_COLS):
1147
+ self._repaint_cell(r, c)
1148
+
1149
+ def _to_cell(self, event):
1150
+ cx = self.canvas.canvasx(event.x)
1151
+ col = max(0, min(GRID_COLS - 1, int(cx // CELL_SIZE)))
1152
+ row = max(0, min(GRID_ROWS - 1, int(event.y // CELL_SIZE)))
1153
+ return row, col
1154
+
1155
+ def _set_path(self, row, col, value):
1156
+ if self.is_generated or self.path_grid[row][col] == value:
1157
+ return
1158
+ self.path_grid[row][col] = value
1159
+ self._repaint_cell(row, col)
1160
+
1161
+ def _on_canvas_press(self, e):
1162
+ cx = self.canvas.canvasx(e.x)
1163
+ patch_clicked = max(0, min(NUM_PATCHES - 1, int(cx // (PATCH_SIZE * CELL_SIZE))))
1164
+ self.select_patch(patch_clicked)
1165
+ self.drawing = True
1166
+ self._set_path(*self._to_cell(e), True)
1167
+
1168
+ def _draw_move(self, e):
1169
+ if self.drawing:
1170
+ self._set_path(*self._to_cell(e), True)
1171
+
1172
+ def _draw_stop(self, e):
1173
+ self.drawing = False
1174
+
1175
+ def _erase_start(self, e): self._set_path(*self._to_cell(e), False)
1176
+ def _erase_move(self, e): self._set_path(*self._to_cell(e), False)
1177
+
1178
+ # โ”€โ”€ NEW: Seeded path dialog โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1179
+ def open_seed_dialog(self):
1180
+ if self.is_generated:
1181
+ if not messagebox.askyesno(
1182
+ "Auto Path",
1183
+ "A level has already been generated.\n"
1184
+ "Opening Auto Path will let you redraw.\n\nContinue?"
1185
+ ):
1186
+ return
1187
+ self.reset_to_draw()
1188
+
1189
+ dialog = SeedDialog(self.root)
1190
+ self.root.wait_window(dialog)
1191
+
1192
+ if dialog.result_grid is not None:
1193
+ self.path_grid = dialog.result_grid
1194
+ d = dialog.difficulty.get()
1195
+ s = dialog.seed.get()
1196
+ self._last_difficulty = d
1197
+ self._last_seed = s
1198
+ self.diff_indicator_var.set(f"๐ŸŽฒ diff={d}/9 seed={s}")
1199
+ self._repaint_all()
1200
+ cells = sum(
1201
+ self.path_grid[r][c]
1202
+ for r in range(GRID_ROWS) for c in range(GRID_COLS)
1203
+ )
1204
+ self.status_var.set(
1205
+ f"Auto path applied โ€” difficulty {d}/9 ยท seed {s} ยท "
1206
+ f"{cells} path cells. Hit โšก Generate Level to continue."
1207
+ )
1208
+ else:
1209
+ self.status_var.set("Auto path cancelled.")
1210
+
1211
+ # โ”€โ”€ Actions โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1212
+ def clear(self):
1213
+ self.path_grid = [[False] * GRID_COLS for _ in range(GRID_ROWS)]
1214
+ self.generated_grid = None
1215
+ self.is_generated = False
1216
+ self.patch_enemy_bias = {i: 0.0 for i in range(NUM_PATCHES)}
1217
+ self._last_seed = None
1218
+ self._last_difficulty = None
1219
+ self.diff_indicator_var.set("")
1220
+ self.reset_btn.pack_forget()
1221
+ self.sprite_btn.pack_forget()
1222
+ self._repaint_all()
1223
+ self._refresh_patch_ui()
1224
+ self.status_var.set("Cleared.")
1225
+
1226
+ def reset_to_draw(self):
1227
+ self.generated_grid = None
1228
+ self.is_generated = False
1229
+ self.reset_btn.pack_forget()
1230
+ self.sprite_btn.pack_forget()
1231
+ self._repaint_all()
1232
+ self.status_var.set("Back to drawing mode โ€” path and biases preserved.")
1233
+
1234
+ def load_model(self, slot_name: str):
1235
+ if not MAMBA_AVAILABLE:
1236
+ messagebox.showerror("mambapy not installed",
1237
+ "Install it first:\n\npip install mambapy")
1238
+ return
1239
+
1240
+ path = filedialog.askdirectory(
1241
+ title=f"Select checkpoint directory for Model {slot_name}"
1242
+ )
1243
+ if not path:
1244
+ path = filedialog.askopenfilename(
1245
+ title=f"Select checkpoint file for Model {slot_name}",
1246
+ filetypes=[("PyTorch checkpoint", "*.pt *.pth"), ("All files", "*.*")]
1247
+ )
1248
+ if not path:
1249
+ return
1250
+
1251
+ slot = self.slot_a if slot_name == "A" else self.slot_b
1252
+
1253
+ try:
1254
+ self.status_var.set(f"Loading Model {slot_name}โ€ฆ")
1255
+ self.root.update()
1256
+ slot.load(path)
1257
+ slot.model.to(DEVICE)
1258
+ self._update_slot_label(slot_name)
1259
+
1260
+ has_enemy = "E" in slot.tile_to_index
1261
+ self.status_var.set(
1262
+ f"Model {slot_name} ready โ€” arch: {slot.arch} | "
1263
+ f"{slot.num_tile_types} tile types | {DEVICE} | "
1264
+ f"enemy tile {'โœ“' if has_enemy else 'โœ— (bias inactive)'} | "
1265
+ f"tiles: {list(slot.tile_to_index.keys())}"
1266
+ )
1267
+
1268
+ if slot_name == "A" and not self.slot_b.is_loaded:
1269
+ self.active_slot_var.set("A")
1270
+ elif slot_name == "B" and not self.slot_a.is_loaded:
1271
+ self.active_slot_var.set("B")
1272
+
1273
+ self._refresh_model_ui()
1274
+
1275
+ except Exception as exc:
1276
+ messagebox.showerror(f"Load failed (Model {slot_name})", str(exc))
1277
+ self.status_var.set(f"Failed to load Model {slot_name}.")
1278
+
1279
+ def generate(self):
1280
+ slot = self.active_slot
1281
+ slot_name = self.active_slot_var.get()
1282
+
1283
+ if not slot.is_loaded:
1284
+ messagebox.showwarning(
1285
+ "No model selected",
1286
+ f"Model {slot_name} is not loaded yet.\n"
1287
+ "Load it via the model bar at the top, or switch to the other slot."
1288
+ )
1289
+ return
1290
+
1291
+ if not any(self.path_grid[r][c] for r in range(GRID_ROWS) for c in range(GRID_COLS)):
1292
+ messagebox.showwarning("No path", "Draw a path first (or use ๐ŸŽฒ Auto Path).")
1293
+ return
1294
+
1295
+ num_patches = math.ceil(GRID_COLS / PATCH_SIZE)
1296
+ result = [[AIR_TILE] * (num_patches * PATCH_SIZE) for _ in range(GRID_ROWS)]
1297
+
1298
+ try:
1299
+ for p in range(num_patches):
1300
+ col_start = p * PATCH_SIZE
1301
+ path_mask = torch.zeros(PATCH_SIZE, PATCH_SIZE)
1302
+ for r in range(PATCH_SIZE):
1303
+ for c in range(PATCH_SIZE):
1304
+ sc = col_start + c
1305
+ if sc < GRID_COLS and self.path_grid[r][sc]:
1306
+ path_mask[r][c] = 1.0
1307
+
1308
+ bias = self.patch_enemy_bias.get(p, 0.0)
1309
+ self.status_var.set(
1310
+ f"[Model {slot_name} / {slot.arch}] "
1311
+ f"Generating patch {p+1}/{num_patches} (enemy bias={bias:+.1f})"
1312
+ )
1313
+ self.root.update()
1314
+
1315
+ tile_ids, path_flags = run_generation(
1316
+ path_mask, slot.model, slot.alpha_bar,
1317
+ slot.tile_to_index, slot.num_tile_types,
1318
+ slot.diffusion_steps, enemy_bias=bias,
1319
+ )
1320
+ patch_grid = decode_patch(tile_ids, path_flags, slot.index_to_tile)
1321
+ for r in range(PATCH_SIZE):
1322
+ for c in range(PATCH_SIZE):
1323
+ result[r][col_start + c] = patch_grid[r][c]
1324
+
1325
+ self.generated_grid = [row[:GRID_COLS] for row in result]
1326
+ self.is_generated = True
1327
+ self._repaint_all()
1328
+ self.reset_btn.pack(side=tk.LEFT, padx=(0, 8))
1329
+
1330
+ bias_summary = " ".join(
1331
+ f"P{i+1}:{self.patch_enemy_bias[i]:+.1f}" for i in range(num_patches)
1332
+ )
1333
+ seed_info = ""
1334
+ if self._last_difficulty is not None:
1335
+ seed_info = f" | diff={self._last_difficulty} seed={self._last_seed}"
1336
+ done_msg = (
1337
+ f"Generated with Model {slot_name} [{slot.arch}]! "
1338
+ f"[{bias_summary}]{seed_info}"
1339
+ )
1340
+
1341
+ if MARIOGPT_AVAILABLE:
1342
+ self.sprite_btn.pack(side=tk.LEFT, padx=(0, 8))
1343
+ self.status_var.set(done_msg + " Hit ๐ŸŽฎ Show Sprites to render with real tiles.")
1344
+ self.show_sprites()
1345
+ else:
1346
+ self.status_var.set(done_msg)
1347
+
1348
+ except Exception as exc:
1349
+ messagebox.showerror("Generation failed", str(exc))
1350
+ self.status_var.set("Generation failed.")
1351
+
1352
+ def show_sprites(self):
1353
+ if not MARIOGPT_AVAILABLE:
1354
+ messagebox.showwarning("mario-gpt not installed",
1355
+ "Install it with:\n\npip install mario-gpt")
1356
+ return
1357
+ if self.generated_grid is None:
1358
+ messagebox.showwarning("No level", "Generate a level first.")
1359
+ return
1360
+ try:
1361
+ self.status_var.set("Rendering spritesโ€ฆ")
1362
+ self.root.update()
1363
+ open_sprite_viewer(self.root, self.generated_grid)
1364
+ self.status_var.set("Sprite viewer opened.")
1365
+ except Exception as exc:
1366
+ messagebox.showerror("Sprite render failed", str(exc))
1367
+ self.status_var.set("Sprite rendering failed.")
1368
+
1369
+
1370
+ # โ”€โ”€ Run โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
1371
+ if __name__ == "__main__":
1372
+ root = tk.Tk()
1373
+ root.geometry("1280x620")
1374
+ root.resizable(True, True)
1375
+ App(root)
1376
+ root.mainloop()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.109.2
2
+ uvicorn[standard]==0.27.1
3
+ pydantic==2.6.1
4
+ torch==2.1.2+cpu --extra-index-url https://download.pytorch.org/whl/cpu
5
+ pillow==10.2.0
6
+ mario-gpt==0.1.3
7
+ mambapy==1.2.0
8
+ transformers==4.40.0
start_server.bat ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ @echo off
2
+ echo Starting Mario GPT FastAPI Server...
3
+ cd /d "%~dp0"
4
+ .\.venv\Scripts\python.exe -m uvicorn main:app --port 8000 --host 0.0.0.0
5
+ pause