Mario_Backend / LevelGenerator.gd
Hazem42's picture
Upload 6 files
a0b04ff verified
Raw History Blame Contribute Delete
5.9 kB
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