File size: 5,897 Bytes
a0b04ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
extends Node2D

class_name LevelGenerator

# Configuration
@export var api_url: String = "http://127.0.0.1:8000/api/generate"
@export var difficulty: float = 0.3
@export var seed: int = 0

# Loading screen
var loading_instance
var LoadingScene = preload("res://Scenes/UI/LoadingScreen.tscn")

# MiniMap Preview
var MiniMapScene = preload("res://Scenes/UI/MiniMapPreview.tscn")
var minimap_instance

# Must map exactly to the text symbols returned by the model to your Godot TileSet IDs
# e.g., if ground is Tile ID 1 and coin is Tile ID 2
@export var tile_map_mapping: Dictionary = {
	"-": -1, # Air (empty)
	"X": 0,  # Ground
	"S": 1,  # Breakable
	"?": 2,  # Question block
	"Q": 2,  # Question block
	"o": 3,  # Coin
	"E": 4,  # Enemy
	"<": 5,  # Tube top left
	">": 6,  # Tube top right
	"[": 7,  # Tube lower left
	"]": 8,  # Tube lower right
	"x": -1  # Generated Path (usually empty space in game)
}

@onready var tile_map: TileMap = $TileMap
@onready var http_request: HTTPRequest = $HTTPRequest

const GRID_COLS = 50
const GRID_ROWS = 16

var is_generating = false

func _ready():
	randomize()
	# Ensure the HTTPRequest node exists
	if not http_request:
		http_request = HTTPRequest.new()
		add_child(http_request)
	
	http_request.request_completed.connect(_on_level_generated)
	
	# Start generation on load
	generate_level()

func generate_level():
	# Prevent multiple simultaneous requests
	if is_generating:
		print("[WARNING] Already generating a level, skipping request")
		return
	
	is_generating = true
	print("\n[LEVEL] Starting Level Generation...")

	# Clean up old loading screen
	if loading_instance:
		loading_instance.queue_free()
	if minimap_instance:
		minimap_instance.queue_free()

	# Create new loading screen
	loading_instance = LoadingScene.instantiate()
	get_tree().current_scene.add_child(loading_instance)

	# Generate NEW random seed every time if seed is 0
	if seed == 0:
		seed = randi() % 1000000000
	
	print(f"[LEVEL] Using difficulty: {difficulty:.2f}, seed: {seed}")
	
	var request_data = {
		"difficulty": difficulty,
		"seed": seed,
		"use_auto_path": true,
		"slot_name": "A",
		"patch_enemy_bias": {}
	}
	
	var json_payload = JSON.stringify(request_data)
	var headers = ["Content-Type: application/json"]
	
	# Make the request to the FastAPI application
	var error = http_request.request(api_url, headers, HTTPClient.METHOD_POST, json_payload)
	
	if loading_instance:
		loading_instance.set_progress(0.3)
	
	if error != OK:
		print("[ERROR] HTTP request failed with error code:", error)
		is_generating = false
		if loading_instance:
			loading_instance.queue_free()

func _on_level_generated(result, response_code, headers, body):
	if response_code != 200:
		print(f"[ERROR] Failed to fetch level. Response code: {response_code}")
		print(f"[ERROR] Response: {body.get_string_from_utf8()}")
		is_generating = false
		if loading_instance:
			loading_instance.queue_free()
		return

	var json = JSON.new()
	var parse_result = json.parse(body.get_string_from_utf8())
	if parse_result != OK:
		print("[ERROR] Failed to parse JSON response.")
		is_generating = false
		if loading_instance:
			loading_instance.queue_free()
		return

	var response_data = json.data
	
	if loading_instance:
		loading_instance.set_progress(0.6)
	
	if not response_data.has("grid_string"):
		print("[ERROR] Grid data not found in response.")
		is_generating = false
		if loading_instance:
			loading_instance.queue_free()
		return

	var grid_string = response_data["grid_string"]
	var difficulty_label = response_data.get("difficulty_label", "Unknown")

	print(f"[LEVEL] Received grid_string ({GRID_COLS}x{GRID_ROWS})")
	print(f"[LEVEL] Difficulty label: {difficulty_label}")

	# Show mini map preview
	if minimap_instance:
		minimap_instance.queue_free()
	
	minimap_instance = MiniMapScene.instantiate()
	get_tree().current_scene.add_child(minimap_instance)
	minimap_instance.generate_preview(grid_string)

	if loading_instance:
		loading_instance.set_progress(0.9)

	# Wait 2 seconds for preview
	await get_tree().create_timer(2.0).timeout
	
	# Clean up minimap
	if minimap_instance:
		minimap_instance.queue_free()
		minimap_instance = null

	# Hide loading screen
	if loading_instance:
		loading_instance.queue_free()
		loading_instance = null
	
	print("[LEVEL] Rendering level to TileMap...")
	render_level(grid_string.split("\n"))
	
	is_generating = false
	print("[LEVEL] Level generation complete!\n")
	
func render_level(grid_rows: Array):
	tile_map.clear()
	
	var row_idx = 0
	for row_str in grid_rows:
		for col_idx in range(row_str.length()):
			var char_symbol = row_str.substr(col_idx, 1)
			
			if tile_map_mapping.has(char_symbol):
				var tile_id = tile_map_mapping[char_symbol]
				if tile_id != -1:
					tile_map.set_cell(0, Vector2i(col_idx, row_idx), tile_id, Vector2i(0, 0))
		row_idx += 1
		
	print("[LEVEL] Level rendering complete.")

func regenerate_level(new_difficulty: float):
	print(f"\n[LEVEL] Regenerate requested with difficulty: {new_difficulty}")
	difficulty = clamp(new_difficulty, 0.0, 1.0)
	seed = 0  # Reset seed to generate a new one
	generate_level()

func get_tile_color(char: String) -> Color:
	match char:
		"-", "x":
			return Color("#12121f")  # air/path β€” dark
		"X":
			return Color("#4a3728")  # ground β€” brown
		"S":
			return Color("#8b6914")  # breakable β€” gold
		"?", "Q":
			return Color("#f5c518")  # question β€” yellow
		"E":
			return Color("#c0392b")  # enemy β€” red
		"<", ">":
			return Color("#27ae60")  # pipe top β€” green
		"[", "]":
			return Color("#1e8449")  # pipe bottom β€” dark green
		"o":
			return Color("#f39c12")  # coin β€” orange
		_:
			return Color("#000000")  # unknown β€” black