975 lines
32 KiB
GDScript
975 lines
32 KiB
GDScript
extends Node
|
|
|
|
signal state_changed(new_state: String)
|
|
signal character_updated
|
|
signal dungeon_entered
|
|
signal dungeon_state_updated
|
|
signal dungeon_cleared
|
|
signal escaped
|
|
signal inventory_updated
|
|
signal chat_message_received(sender: String, message: String, type: String)
|
|
signal loot_received(items: Array)
|
|
signal player_died
|
|
signal loot_chest_spawned(chest_data: Dictionary)
|
|
signal loot_chest_state_received(chest_data: Dictionary)
|
|
signal mob_loot_state_received(mob_data: Dictionary)
|
|
signal death_loot_lost(data: Dictionary)
|
|
signal dungeon_list_received(data: Dictionary)
|
|
signal crafting_skills_updated(skills: Dictionary)
|
|
signal crafting_recipes_updated(recipes: Array)
|
|
signal crafting_result_received(result: Dictionary)
|
|
signal recipe_discovered(recipe: Dictionary)
|
|
signal stash_updated(stash_data: Dictionary)
|
|
signal stash_result(result: Dictionary)
|
|
signal dungeon_tiles_updated(tiles: Array)
|
|
signal projectile_spawned(projectile_data: Dictionary)
|
|
signal projectile_hit(hit_data: Dictionary)
|
|
signal projectile_expired(expired_data: Dictionary)
|
|
signal damage_number(damage_data: Dictionary)
|
|
|
|
# Use constants instead of enum to avoid type issues
|
|
const STATE_AUTH = 0
|
|
const STATE_HUB = 1
|
|
const STATE_PLAYING = 2
|
|
const STATE_DEAD = 3
|
|
const STATE_PORTALUSED = 4
|
|
const STATE_DUNGEONCLEARED = 5
|
|
|
|
const STATE_NAMES = ["AUTH", "HUB", "PLAYING", "DEAD", "PORTALUSED","DUNGEONCLEARED"]
|
|
|
|
var current_state: int = STATE_AUTH
|
|
var account_id: int = 0
|
|
var _hub_fallback_timer: SceneTreeTimer = null
|
|
|
|
# Character data
|
|
var character: Dictionary = {
|
|
"id": 0,
|
|
"name": "",
|
|
"level": 1,
|
|
"xp": 0,
|
|
"xp_next": 100,
|
|
"unspent_points": 5,
|
|
"strength": 1,
|
|
"intelligence": 1,
|
|
"wisdom": 1,
|
|
"endurance": 1,
|
|
"dexterity": 1,
|
|
"max_health": 60,
|
|
"max_mana": 28,
|
|
"max_stamina": 55,
|
|
"gold": 0
|
|
}
|
|
|
|
# Dungeon data
|
|
var dungeon: Dictionary = {
|
|
"id": null,
|
|
"tier": 1,
|
|
"width": 0,
|
|
"height": 0,
|
|
"tiles": [],
|
|
"phase": "active",
|
|
"visual_tiles": {}, # Visual tile data from V2 generator
|
|
"has_visual_tiles": false
|
|
}
|
|
|
|
# Player in dungeon
|
|
var self_player: Dictionary = {}
|
|
var players: Dictionary = {}
|
|
var mobs: Dictionary = {}
|
|
var mob_catalog: Dictionary = {} # Cached static mob render metadata (id -> {definitionId, name, spriteConfig, tintColor, scale})
|
|
var chests: Dictionary = {}
|
|
var dropped_items: Dictionary = {}
|
|
var portals: Dictionary = {}
|
|
var loot_chests: Dictionary = {}
|
|
var active_projectiles: Dictionary = {} # Projectiles from DUNGEON_STATE spatial tick
|
|
var hazards: Dictionary = {} # Active hazard zones from DUNGEON_STATE
|
|
|
|
# Inventory
|
|
var inventory: Array = []
|
|
var equipment: Dictionary = {}
|
|
var hotbar: Array = [null, null, null, null, null, null, null, null]
|
|
|
|
# Stash (VIP Feature)
|
|
var stash: Dictionary = {"slots": 0, "items": []}
|
|
var is_vip: bool = false
|
|
|
|
# Escape
|
|
var is_escaping: bool = false
|
|
var escape_start_time: int = 0
|
|
|
|
# Chat
|
|
var chat_messages: Array = []
|
|
|
|
var _network_connected: bool = false
|
|
|
|
func _ready():
|
|
call_deferred("_connect_to_network")
|
|
Network.disconnected.connect(_on_disconnected)
|
|
|
|
|
|
func _connect_to_network():
|
|
if Network:
|
|
Network.message_received.connect(_on_message_received)
|
|
_network_connected = true
|
|
|
|
func _on_disconnected():
|
|
set_state(0)
|
|
|
|
func set_state(new_state: int):
|
|
current_state = new_state
|
|
var state_name = STATE_NAMES[new_state] if new_state < STATE_NAMES.size() else "UNKNOWN"
|
|
print("[GameState] State changed to: ", state_name)
|
|
state_changed.emit(state_name)
|
|
|
|
func get_state_name() -> String:
|
|
return STATE_NAMES[current_state] if current_state < STATE_NAMES.size() else "UNKNOWN"
|
|
|
|
func _on_message_received(opcode: int, data: Dictionary):
|
|
# Debug: log projectile-related opcodes
|
|
if opcode == 504 or opcode == 505 or opcode == 506:
|
|
print("[GameState] !!!!! Received projectile opcode: ", opcode, " !!!!!")
|
|
|
|
match opcode:
|
|
OpCodes.AUTH_LOGIN_RESULT, OpCodes.AUTH_REGISTER_RESULT:
|
|
_handle_auth_result(data)
|
|
OpCodes.HUB_STATE:
|
|
_handle_hub_state(data)
|
|
OpCodes.DUNGEON_ENTER_RESULT:
|
|
_handle_dungeon_enter(data)
|
|
OpCodes.DUNGEON_STATE:
|
|
_handle_dungeon_state(data)
|
|
OpCodes.DUNGEON_TILE_UPDATE:
|
|
_handle_tile_update(data)
|
|
OpCodes.INVENTORY_STATE:
|
|
_handle_inventory_state(data)
|
|
OpCodes.LOOT_RECEIVED:
|
|
print("[GameState] >>> LOOT_RECEIVED opcode matched! <<<")
|
|
_handle_loot_received(data)
|
|
OpCodes.CHAT_MESSAGE:
|
|
_handle_chat_message(data)
|
|
OpCodes.SERVER_BROADCAST:
|
|
_handle_server_broadcast(data)
|
|
OpCodes.ESCAPE_INTERRUPTED:
|
|
print("[OpCodes]PlayerEscape] Interrupted.")
|
|
is_escaping = false
|
|
OpCodes.ESCAPE_SUCCESS:
|
|
print("[GameState] >>> ESCAPE_SUCCESS - Returning to hub <<<")
|
|
_handle_escape_success(data)
|
|
OpCodes.PORTAL_USED:
|
|
print("[GameState] >>> PORTAL_USED - Extracting via portal <<<")
|
|
_handle_portal_used(data)
|
|
OpCodes.EVENT_DAMAGE:
|
|
_handle_damage(data)
|
|
OpCodes.EVENT_DEATH:
|
|
_handle_death(data)
|
|
OpCodes.EVENT_LEVELUP:
|
|
_handle_levelup(data)
|
|
OpCodes.LOOT_CHEST_SPAWNED:
|
|
_handle_loot_chest_spawned(data)
|
|
OpCodes.LOOT_CHEST_STATE:
|
|
_handle_loot_chest_state(data)
|
|
OpCodes.MOB_LOOT_STATE:
|
|
_handle_mob_loot_state(data)
|
|
OpCodes.PLAYER_DEATH_LOOT_LOST:
|
|
_handle_death_loot_lost(data)
|
|
OpCodes.DUNGEON_LIST_RESPONSE:
|
|
_handle_dungeon_list(data)
|
|
OpCodes.ASSET_MANIFEST_RESPONSE:
|
|
_handle_asset_manifest(data)
|
|
OpCodes.CRAFTING_SKILLS_STATE:
|
|
_handle_crafting_skills(data)
|
|
OpCodes.CRAFTING_RECIPES_STATE:
|
|
_handle_crafting_recipes(data)
|
|
OpCodes.CRAFTING_RESULT:
|
|
_handle_crafting_result(data)
|
|
OpCodes.RECIPE_DISCOVERED:
|
|
_handle_recipe_discovered(data)
|
|
OpCodes.CRAFTING_SKILL_LEVELUP:
|
|
_handle_crafting_skill_levelup(data)
|
|
OpCodes.STASH_STATE:
|
|
_handle_stash_state(data)
|
|
OpCodes.STASH_RESULT:
|
|
_handle_stash_result(data)
|
|
OpCodes.EVENT_PROJECTILE_SPAWNED:
|
|
_handle_projectile_spawned(data)
|
|
OpCodes.EVENT_PROJECTILE_HIT:
|
|
_handle_projectile_hit(data)
|
|
OpCodes.EVENT_PROJECTILE_EXPIRED:
|
|
_handle_projectile_expired(data)
|
|
OpCodes.EVENT_DAMAGE_NUMBER:
|
|
_handle_damage_number(data)
|
|
OpCodes.ERROR:
|
|
_handle_error(data)
|
|
_:
|
|
print("[GameState] Unhandled opcode: ", opcode)
|
|
|
|
func _handle_asset_manifest(data: Dictionary):
|
|
print("[GameState] Received asset manifest")
|
|
if UpdateManager:
|
|
UpdateManager.on_manifest_received(data)
|
|
|
|
func _handle_auth_result(data: Dictionary):
|
|
var ok = data.get("ok", data.get("Ok", false))
|
|
if ok:
|
|
account_id = int(data.get("accountId", data.get("AccountId", 0)))
|
|
Network.send_message(OpCodes.HUB_STATE, {})
|
|
|
|
func _handle_hub_state(data: Dictionary):
|
|
var c = data.get("character", data.get("Character", data))
|
|
if c:
|
|
character = {
|
|
"id": int(c.get("id", c.get("Id", 0))),
|
|
"name": c.get("name", c.get("Name", "")),
|
|
"level": int(c.get("level", c.get("Level", 1))),
|
|
"xp": int(c.get("xp", c.get("Xp", 0))),
|
|
"xp_next": int(c.get("xpNext", c.get("XpNext", 100))),
|
|
"unspent_points": int(c.get("unspentPoints", c.get("UnspentPoints", 0))),
|
|
"strength": int(c.get("strength", c.get("Strength", 1))),
|
|
"intelligence": int(c.get("intelligence", c.get("Intelligence", 1))),
|
|
"wisdom": int(c.get("wisdom", c.get("Wisdom", 1))),
|
|
"endurance": int(c.get("endurance", c.get("Endurance", 1))),
|
|
"dexterity": int(c.get("dexterity", c.get("Dexterity", 1))),
|
|
"max_health": int(c.get("maxHealth", c.get("MaxHealth", 60))),
|
|
"max_mana": int(c.get("maxMana", c.get("MaxMana", 28))),
|
|
"max_stamina": int(c.get("maxStamina", c.get("MaxStamina", 55))),
|
|
"gold": int(c.get("gold", c.get("Gold", 0)))
|
|
}
|
|
if current_state != STATE_PLAYING and current_state != STATE_DEAD:
|
|
# Cancel the fallback timer — server responded in time
|
|
_hub_fallback_timer = null
|
|
set_state(STATE_HUB)
|
|
character_updated.emit()
|
|
|
|
func _handle_dungeon_enter(data: Dictionary):
|
|
var ok = data.get("ok", data.get("Ok", false))
|
|
if not ok:
|
|
return
|
|
|
|
dungeon.id = data.get("dungeonId", data.get("DungeonId"))
|
|
dungeon.tier = int(data.get("tier", data.get("Tier", 1)))
|
|
dungeon.width = int(data.get("width", data.get("Width", 0)))
|
|
dungeon.height = int(data.get("height", data.get("Height", 0)))
|
|
|
|
# Check for RLE tiles first, fallback to legacy format
|
|
var tiles_rle = data.get("tilesRLE", data.get("TilesRLE", ""))
|
|
if not tiles_rle.is_empty():
|
|
_parse_tiles_rle(tiles_rle)
|
|
else:
|
|
var tiles_data = data.get("tiles", data.get("Tiles", ""))
|
|
_parse_tiles(tiles_data)
|
|
|
|
# Parse visual tile data (V2 generator)
|
|
var tile_sheets = data.get("tileSheets", data.get("TileSheets", []))
|
|
var visual_tiles = data.get("visualTiles", data.get("VisualTiles", []))
|
|
|
|
# Debug: print all keys in data
|
|
print("[GameState] DUNGEON_ENTER keys: ", data.keys())
|
|
print("[GameState] tileSheets type: %s, value: %s" % [typeof(tile_sheets), tile_sheets])
|
|
print("[GameState] visualTiles type: %s, size: %s" % [typeof(visual_tiles), visual_tiles.size() if visual_tiles is Array else "not array"])
|
|
|
|
if tile_sheets is Array and visual_tiles is Array and tile_sheets.size() > 0 and visual_tiles.size() > 0:
|
|
dungeon.visual_tiles = {
|
|
"sheets": tile_sheets,
|
|
"tiles": visual_tiles
|
|
}
|
|
dungeon.has_visual_tiles = true
|
|
print("[GameState] Received %d visual tiles from %d sheets" % [visual_tiles.size(), tile_sheets.size()])
|
|
else:
|
|
dungeon.visual_tiles = {}
|
|
dungeon.has_visual_tiles = false
|
|
print("[GameState] No visual tiles - sheets: %s, tiles: %s" % [tile_sheets, typeof(visual_tiles)])
|
|
|
|
var spawn = data.get("spawn", data.get("Spawn", {}))
|
|
self_player = {
|
|
"x": spawn.get("x", spawn.get("X", 0)),
|
|
"y": spawn.get("y", spawn.get("Y", 0)),
|
|
"health": character.max_health,
|
|
"max_health": character.max_health,
|
|
"mana": character.max_mana,
|
|
"max_mana": character.max_mana,
|
|
"stamina": character.max_stamina,
|
|
"max_stamina": character.max_stamina,
|
|
"is_alive": true
|
|
}
|
|
|
|
players.clear()
|
|
mobs.clear()
|
|
mob_catalog.clear()
|
|
chests.clear()
|
|
dropped_items.clear()
|
|
portals.clear()
|
|
|
|
# Parse initial portals
|
|
var portal_list = data.get("portals", data.get("Portals", []))
|
|
for p in portal_list:
|
|
var pid = p.get("id", p.get("Id"))
|
|
portals[pid] = p
|
|
|
|
# Parse mob catalog if included in the dungeon-enter response
|
|
var catalog = data.get("mobCatalog", data.get("MobCatalog", []))
|
|
if catalog is Array and catalog.size() > 0:
|
|
for entry in catalog:
|
|
var cid = entry.get("id", entry.get("Id"))
|
|
if cid != null:
|
|
mob_catalog[cid] = entry
|
|
print("[GameState] Mob catalog from enter: %d entries" % catalog.size())
|
|
_prefetch_mob_textures_from_list(catalog)
|
|
|
|
# Prefetch mob textures early on web (mobs list is included in enter payload)
|
|
var mobs_list = data.get("mobs", data.get("Mobs", []))
|
|
_prefetch_mob_textures_from_list(mobs_list)
|
|
|
|
set_state(STATE_PLAYING)
|
|
dungeon_entered.emit()
|
|
|
|
func _prefetch_mob_textures_from_list(mobs_list: Array) -> void:
|
|
if mobs_list.is_empty():
|
|
return
|
|
if not UpdateManager or not UpdateManager._is_web:
|
|
return
|
|
|
|
var paths: Array = []
|
|
for mob in mobs_list:
|
|
if not (mob is Dictionary):
|
|
continue
|
|
var sprite_config = mob.get("spriteConfig", mob.get("SpriteConfig", null))
|
|
if sprite_config == null or not (sprite_config is Dictionary):
|
|
continue
|
|
|
|
# New format (sheets)
|
|
if sprite_config.has("sheets"):
|
|
var sheets = sprite_config.get("sheets", {})
|
|
for sheet_key in sheets:
|
|
var sheet_info = sheets[sheet_key]
|
|
var path = sheet_info.get("path", "")
|
|
if path != "" and not paths.has(path):
|
|
paths.append(path)
|
|
continue
|
|
|
|
# Legacy format (sprites)
|
|
var sprites = sprite_config.get("sprites", {})
|
|
for anim_name in sprites:
|
|
var sprite_path = sprites[anim_name]
|
|
if sprite_path != "" and not paths.has(sprite_path):
|
|
paths.append(sprite_path)
|
|
|
|
if not paths.is_empty():
|
|
UpdateManager.prefetch_files(paths, true, false)
|
|
|
|
func _parse_tiles(tiles_string: String):
|
|
dungeon.tiles = []
|
|
if tiles_string.is_empty():
|
|
return
|
|
|
|
var rows = tiles_string.split("\n")
|
|
|
|
for x in range(dungeon.width):
|
|
dungeon.tiles.append([])
|
|
for y in range(dungeon.height):
|
|
dungeon.tiles[x].append(0)
|
|
|
|
for y in range(rows.size()):
|
|
if y >= dungeon.height:
|
|
break
|
|
var row = rows[y]
|
|
for x in range(row.length()):
|
|
if x >= dungeon.width:
|
|
break
|
|
dungeon.tiles[x][y] = 0 if row[x] == "." else 1
|
|
func _parse_tiles_rle(rle_string: String):
|
|
# RLE format: "tile,count;tile,count;..."
|
|
# Decode into a flat array first, then reshape to 2D
|
|
dungeon.tiles = []
|
|
if rle_string.is_empty():
|
|
return
|
|
|
|
# Initialize 2D array
|
|
for x in range(dungeon.width):
|
|
dungeon.tiles.append([])
|
|
for y in range(dungeon.height):
|
|
dungeon.tiles[x].append(0)
|
|
|
|
# Decode RLE
|
|
var flat_tiles: Array[int] = []
|
|
var runs = rle_string.split(";")
|
|
|
|
for run in runs:
|
|
if run.is_empty():
|
|
continue
|
|
var parts = run.split(",")
|
|
if parts.size() != 2:
|
|
continue
|
|
var tile_value = int(parts[0])
|
|
var count = int(parts[1])
|
|
for i in range(count):
|
|
flat_tiles.append(tile_value)
|
|
|
|
# Convert flat array to 2D (row-major order: y then x)
|
|
var idx = 0
|
|
for y in range(dungeon.height):
|
|
for x in range(dungeon.width):
|
|
if idx < flat_tiles.size():
|
|
dungeon.tiles[x][y] = flat_tiles[idx]
|
|
idx += 1
|
|
|
|
print("[GameState] Parsed RLE tiles: %d values for %dx%d grid" % [flat_tiles.size(), dungeon.width, dungeon.height])
|
|
|
|
func _handle_dungeon_state(data: Dictionary):
|
|
# Check dungeon phase first
|
|
var phase = data.get("phase", data.get("Phase", "active"))
|
|
if phase == "cleared":
|
|
# Only print once when transitioning to cleared state
|
|
if dungeon.phase != "cleared":
|
|
print("[GameState] Dungeon cleared! Use the portal to exit.")
|
|
dungeon_cleared.emit()
|
|
dungeon.phase = "cleared"
|
|
# Don't return - continue processing state so player can still move and loot
|
|
|
|
var ps = data.get("players", data.get("Players", []))
|
|
for p in ps:
|
|
var pid = int(p.get("id", p.get("Id", 0)))
|
|
if pid == character.id:
|
|
self_player.x = p.get("x", p.get("X", self_player.get("x", 0)))
|
|
self_player.y = p.get("y", p.get("Y", self_player.get("y", 0)))
|
|
self_player.health = p.get("health", p.get("Health", self_player.get("health", 100)))
|
|
self_player.max_health = p.get("maxHealth", p.get("MaxHealth", self_player.get("max_health", 100)))
|
|
self_player.mana = p.get("mana", p.get("Mana", self_player.get("mana", 50)))
|
|
self_player.max_mana = p.get("maxMana", p.get("MaxMana", self_player.get("max_mana", 50)))
|
|
self_player.stamina = p.get("stamina", p.get("Stamina", self_player.get("stamina", 55)))
|
|
self_player.max_stamina = p.get("maxStamina", p.get("MaxStamina", self_player.get("max_stamina", 55)))
|
|
self_player.is_alive = p.get("isAlive", p.get("IsAlive", true))
|
|
|
|
# Check for death from state update
|
|
if not self_player.is_alive and current_state == STATE_PLAYING:
|
|
set_state(STATE_DEAD)
|
|
player_died.emit()
|
|
else:
|
|
players[pid] = p
|
|
|
|
# Parse mob catalog (sent once per dungeon join, contains static render metadata)
|
|
var catalog = data.get("mobCatalog", data.get("MobCatalog", []))
|
|
if catalog is Array and catalog.size() > 0:
|
|
for entry in catalog:
|
|
var cid = entry.get("id", entry.get("Id"))
|
|
if cid != null:
|
|
mob_catalog[cid] = entry
|
|
print("[GameState] Mob catalog received: %d entries" % catalog.size())
|
|
# Prefetch textures from catalog entries
|
|
_prefetch_mob_textures_from_list(catalog)
|
|
|
|
# With spatial filtering, mobs array only contains nearby/relevant mobs.
|
|
# Don't clear the full dict — update present mobs and track visibility.
|
|
var ms = data.get("mobs", data.get("Mobs", []))
|
|
var mobs_in_packet: Array = []
|
|
for m in ms:
|
|
var mid = m.get("id", m.get("Id"))
|
|
mobs_in_packet.append(mid)
|
|
# Merge catalog metadata into mob data when per-tick data lacks render fields
|
|
if mob_catalog.has(mid):
|
|
var cat = mob_catalog[mid]
|
|
if not m.has("spriteConfig") and not m.has("SpriteConfig"):
|
|
var sc = cat.get("spriteConfig", cat.get("SpriteConfig", null))
|
|
if sc != null:
|
|
m["spriteConfig"] = sc
|
|
if not m.has("tintColor") and not m.has("TintColor"):
|
|
var tc = cat.get("tintColor", cat.get("TintColor", null))
|
|
if tc != null:
|
|
m["tintColor"] = tc
|
|
if not m.has("scale") and not m.has("Scale"):
|
|
var s = cat.get("scale", cat.get("Scale", null))
|
|
if s != null:
|
|
m["scale"] = s
|
|
if not m.has("name") and not m.has("Name"):
|
|
var n = cat.get("name", cat.get("Name", null))
|
|
if n != null:
|
|
m["name"] = n
|
|
if not m.has("definitionId") and not m.has("DefinitionId"):
|
|
var did = cat.get("definitionId", cat.get("DefinitionId", null))
|
|
if did != null:
|
|
m["definitionId"] = did
|
|
m["_visible"] = true
|
|
m["_last_seen"] = Time.get_ticks_msec()
|
|
mobs[mid] = m
|
|
# Mark mobs not in this packet as out-of-range (but keep them)
|
|
for mid in mobs:
|
|
if mid not in mobs_in_packet:
|
|
mobs[mid]["_visible"] = false
|
|
|
|
var cs = data.get("chests", data.get("Chests", []))
|
|
for c_item in cs:
|
|
var cid = c_item.get("id", c_item.get("Id"))
|
|
chests[cid] = c_item
|
|
|
|
var items = data.get("items", data.get("Items", []))
|
|
dropped_items.clear()
|
|
for i in items:
|
|
var iid = i.get("id", i.get("Id"))
|
|
dropped_items[iid] = i
|
|
|
|
# Parse portals — server sends the authoritative active set each packet
|
|
var ports = data.get("portals", data.get("Portals", []))
|
|
if ports is Array and ports.size() > 0:
|
|
portals.clear()
|
|
for p in ports:
|
|
var pid = p.get("id", p.get("Id"))
|
|
portals[pid] = p
|
|
|
|
# Parse loot chests (personal to this player)
|
|
var lchests = data.get("lootChests", data.get("LootChests", []))
|
|
loot_chests.clear()
|
|
for lc in lchests:
|
|
var lcid = lc.get("id", lc.get("Id"))
|
|
loot_chests[lcid] = lc
|
|
|
|
# Parse active projectiles (spatially-filtered, sent each tick like mobs)
|
|
var projs = data.get("projectiles", data.get("Projectiles", []))
|
|
active_projectiles.clear()
|
|
for proj in projs:
|
|
var pid = proj.get("id", proj.get("Id"))
|
|
if pid != null:
|
|
active_projectiles[pid] = proj
|
|
|
|
# Parse active hazard zones (ability type 29 ground effects)
|
|
var hzs = data.get("hazards", data.get("Hazards", []))
|
|
hazards.clear()
|
|
for hz in hzs:
|
|
var hid = hz.get("id", hz.get("Id"))
|
|
if hid != null:
|
|
hazards[hid] = hz
|
|
|
|
# Parse events (damage, deaths, projectile hits/expires)
|
|
var events = data.get("events")
|
|
if events:
|
|
# Handle damage events - spawn floating damage numbers
|
|
var damage_events = events.get("damage", [])
|
|
for dmg_event in damage_events:
|
|
damage_number.emit(dmg_event)
|
|
|
|
# Handle projectile hit events - remove projectile from client
|
|
var projectile_hits = events.get("projectileHits", [])
|
|
for hit_event in projectile_hits:
|
|
projectile_hit.emit(hit_event)
|
|
|
|
# Handle projectile expired events - remove projectile from client
|
|
var proj_expired = events.get("projectileExpired", [])
|
|
for expire_event in proj_expired:
|
|
projectile_expired.emit(expire_event)
|
|
|
|
dungeon_state_updated.emit()
|
|
|
|
func _handle_inventory_state(data: Dictionary):
|
|
if data.has("items") or data.has("Items"):
|
|
inventory = data.get("items", data.get("Items", []))
|
|
if data.has("equipment") or data.has("Equipment"):
|
|
equipment = data.get("equipment", data.get("Equipment", {}))
|
|
if data.has("hotbar") or data.has("Hotbar"):
|
|
var hb = data.get("hotbar", data.get("Hotbar", []))
|
|
for i in range(min(hb.size(), 8)):
|
|
hotbar[i] = hb[i]
|
|
inventory_updated.emit()
|
|
|
|
func _handle_loot_received(data: Dictionary):
|
|
print("[GameState] _handle_loot_received called with: ", data)
|
|
var items = data.get("items", data.get("Items", []))
|
|
print("[GameState] Loot items count: ", items.size())
|
|
if items.size() > 0:
|
|
for item in items:
|
|
print("[GameState] Loot item: ", item.get("name", item.get("Name", "Unknown")))
|
|
loot_received.emit(items)
|
|
Network.send_message(OpCodes.INVENTORY_REQUEST, {})
|
|
|
|
func _handle_chat_message(data: Dictionary):
|
|
var sender = data.get("sender", data.get("Sender", data.get("playerName", data.get("PlayerName", "Unknown"))))
|
|
var message = data.get("message", data.get("Message", data.get("text", data.get("Text", ""))))
|
|
var type = data.get("type", data.get("Type", data.get("channel", data.get("Channel", "normal"))))
|
|
|
|
chat_messages.append({"sender": sender, "message": message, "type": type})
|
|
if chat_messages.size() > 100:
|
|
chat_messages.pop_front()
|
|
chat_message_received.emit(sender, message, type)
|
|
|
|
func _handle_server_broadcast(data: Dictionary):
|
|
var message = data.get("message", data.get("Message", ""))
|
|
var msg_type = data.get("type", data.get("Type", "system"))
|
|
|
|
print("[GameState] Server broadcast received: [%s] %s" % [msg_type, message])
|
|
|
|
# Broadcast messages appear in chat with [Server] prefix
|
|
var sender = "[Server]"
|
|
chat_messages.append({"sender": sender, "message": message, "type": msg_type})
|
|
if chat_messages.size() > 100:
|
|
chat_messages.pop_front()
|
|
chat_message_received.emit(sender, message, msg_type)
|
|
|
|
func _handle_damage(_data: Dictionary):
|
|
pass
|
|
|
|
func _handle_death(data: Dictionary):
|
|
var target_id = int(data.get("targetId", data.get("TargetId", data.get("playerId", data.get("PlayerId", 0)))))
|
|
print("[GameState] Death event for: %d, our id: %d" % [target_id, character.id])
|
|
if target_id == character.id:
|
|
self_player.is_alive = false
|
|
set_state(STATE_DEAD)
|
|
player_died.emit()
|
|
|
|
func _handle_levelup(data: Dictionary):
|
|
character.level = int(data.get("newLevel", data.get("NewLevel", character.level)))
|
|
character.xp_next = int(data.get("xpNext", data.get("XpNext", character.xp_next)))
|
|
character.unspent_points = int(data.get("unspentPoints", data.get("UnspentPoints", character.unspent_points)))
|
|
character_updated.emit()
|
|
|
|
func _handle_escape_success(_data: Dictionary):
|
|
print("[GameState] Escape successful! Returning to hub...")
|
|
is_escaping = false
|
|
|
|
# Clear dungeon data
|
|
players.clear()
|
|
mobs.clear()
|
|
mob_catalog.clear()
|
|
chests.clear()
|
|
dropped_items.clear()
|
|
portals.clear()
|
|
loot_chests.clear()
|
|
active_projectiles.clear()
|
|
hazards.clear()
|
|
dungeon = {
|
|
"id": "",
|
|
"tier": 1,
|
|
"width": 0,
|
|
"height": 0,
|
|
"tiles": [],
|
|
"phase": "active"
|
|
}
|
|
set_state(STATE_PORTALUSED)
|
|
escaped.emit()
|
|
# Server will send HUB_STATE next which will call set_state(STATE_HUB).
|
|
# Safety timeout: if HUB_STATE never arrives (network drop), force transition.
|
|
_start_hub_fallback_timer()
|
|
|
|
func _start_hub_fallback_timer():
|
|
# Cancel any existing fallback timer
|
|
if _hub_fallback_timer and _hub_fallback_timer.time_left > 0:
|
|
_hub_fallback_timer.timeout.disconnect(_on_hub_fallback_timeout)
|
|
_hub_fallback_timer = get_tree().create_timer(5.0)
|
|
_hub_fallback_timer.timeout.connect(_on_hub_fallback_timeout)
|
|
|
|
func _on_hub_fallback_timeout():
|
|
if current_state == STATE_PORTALUSED or current_state == STATE_DUNGEONCLEARED:
|
|
print("[GameState] HUB_STATE not received in time — forcing transition to HUB")
|
|
set_state(STATE_HUB)
|
|
|
|
# Helper functions
|
|
func send_move(dx: float, dy: float, aim_angle: float):
|
|
Network.send_message(OpCodes.INPUT_MOVE, {"Dx": dx, "Dy": dy, "AimAngle": aim_angle})
|
|
|
|
func send_attack(aim_angle: float):
|
|
Network.send_message(OpCodes.INPUT_ATTACK, {"AimAngle": aim_angle})
|
|
|
|
func send_fire_projectile(direction_x: float, direction_y: float):
|
|
Network.send_message(OpCodes.INPUT_FIRE_PROJECTILE, {"DirectionX": direction_x, "DirectionY": direction_y})
|
|
|
|
func send_enter_dungeon(tier: int):
|
|
Network.send_message(OpCodes.DUNGEON_ENTER, {"Tier": tier})
|
|
|
|
func send_allocate_stat(stat: String):
|
|
Network.send_message(OpCodes.STAT_ALLOCATE, {"Stat": stat})
|
|
|
|
func send_equip_item(slot_index: int):
|
|
Network.send_message(OpCodes.EQUIP_ITEM, {"SlotIndex": slot_index})
|
|
|
|
func send_unequip_item(slot: String):
|
|
Network.send_message(OpCodes.UNEQUIP_ITEM, {"Slot": slot})
|
|
|
|
func send_use_item(slot_index: int):
|
|
Network.send_message(OpCodes.USE_ITEM, {"SlotIndex": slot_index})
|
|
|
|
func send_stack_items(source_slot: int, target_slot: int):
|
|
Network.send_message(OpCodes.STACK_ITEMS, {"SourceSlot": source_slot, "TargetSlot": target_slot})
|
|
|
|
func send_move_item(source_slot: int, target_slot: int):
|
|
Network.send_message(OpCodes.MOVE_ITEM, {"SourceSlot": source_slot, "TargetSlot": target_slot})
|
|
|
|
func send_auto_stack_inventory():
|
|
Network.send_message(OpCodes.AUTO_STACK_INVENTORY, {})
|
|
|
|
func send_chat(message: String):
|
|
Network.send_message(OpCodes.CHAT_SEND, {"Message": message})
|
|
|
|
func assign_hotbar(hotbar_slot: int, inventory_slot: int):
|
|
# Update locally
|
|
hotbar[hotbar_slot] = {"inventory_slot": inventory_slot}
|
|
# Send to server if there's an opcode for it
|
|
if OpCodes.get("HOTBAR_ASSIGN"):
|
|
Network.send_message(OpCodes.HOTBAR_ASSIGN, {
|
|
"HotbarSlot": hotbar_slot,
|
|
"InventorySlot": inventory_slot
|
|
})
|
|
inventory_updated.emit()
|
|
|
|
func start_escape():
|
|
is_escaping = true
|
|
escape_start_time = Time.get_ticks_msec()
|
|
Network.send_message(OpCodes.ESCAPE_START, {})
|
|
|
|
func cancel_escape():
|
|
is_escaping = false
|
|
Network.send_message(OpCodes.ESCAPE_CANCEL, {})
|
|
|
|
func return_to_hub():
|
|
Network.send_message(OpCodes.DUNGEON_LEAVE, {})
|
|
set_state(STATE_HUB)
|
|
|
|
func send_use_portal(portal_id: int):
|
|
Network.send_message(OpCodes.INPUT_PORTAL, {"PortalId": portal_id})
|
|
|
|
func _handle_portal_used(_data: Dictionary):
|
|
print("[GameState] Portal used! Returning to hub...")
|
|
is_escaping = false
|
|
|
|
# Clear dungeon data
|
|
players.clear()
|
|
mobs.clear()
|
|
mob_catalog.clear()
|
|
chests.clear()
|
|
dropped_items.clear()
|
|
portals.clear()
|
|
loot_chests.clear()
|
|
active_projectiles.clear()
|
|
hazards.clear()
|
|
dungeon = {
|
|
"id": "",
|
|
"tier": 1,
|
|
"width": 0,
|
|
"height": 0,
|
|
"tiles": [],
|
|
"phase": "active"
|
|
}
|
|
set_state(STATE_PORTALUSED)
|
|
escaped.emit()
|
|
# Server will send HUB_STATE next which will call set_state(STATE_HUB).
|
|
# Safety timeout: if HUB_STATE never arrives (network drop), force transition.
|
|
_start_hub_fallback_timer()
|
|
|
|
# Loot chest handlers
|
|
func _handle_loot_chest_spawned(data: Dictionary):
|
|
print("[GameState] Loot chest spawned: ", data)
|
|
loot_chest_spawned.emit(data)
|
|
|
|
func _handle_loot_chest_state(data: Dictionary):
|
|
print("[GameState] Loot chest state received")
|
|
loot_chest_state_received.emit(data)
|
|
|
|
func _handle_mob_loot_state(data: Dictionary):
|
|
print("[GameState] Mob loot state received for mob: ", data.get("mobName", "Unknown"))
|
|
# Signal will be connected by mob loot UI
|
|
mob_loot_state_received.emit(data)
|
|
|
|
func _handle_death_loot_lost(data: Dictionary):
|
|
print("[GameState] Death loot lost: ", data)
|
|
death_loot_lost.emit(data)
|
|
|
|
# Loot chest actions
|
|
func open_loot_chest(chest_id: int):
|
|
Network.send_message(OpCodes.LOOT_CHEST_OPEN, {"ChestId": chest_id})
|
|
|
|
func take_loot_chest_item(chest_id: int, slot_index: int, target_slot: int = -1):
|
|
Network.send_message(OpCodes.LOOT_CHEST_TAKE_ITEM, {
|
|
"ChestId": chest_id,
|
|
"SlotIndex": slot_index,
|
|
"TargetSlotIndex": target_slot
|
|
})
|
|
|
|
func take_all_loot_chest(chest_id: int):
|
|
Network.send_message(OpCodes.LOOT_CHEST_TAKE_ALL, {"ChestId": chest_id})
|
|
|
|
func close_loot_chest(chest_id: int):
|
|
Network.send_message(OpCodes.LOOT_CHEST_CLOSE, {"ChestId": chest_id})
|
|
|
|
# Mob loot actions
|
|
func request_mob_loot(mob_id: int):
|
|
Network.send_message(OpCodes.MOB_LOOT_REQUEST, {"mobId": mob_id})
|
|
|
|
func take_mob_loot_item(mob_id: int, item_index: int):
|
|
Network.send_message(OpCodes.MOB_LOOT_TAKE_ITEM, {
|
|
"mobId": mob_id,
|
|
"itemIndex": item_index
|
|
})
|
|
|
|
func take_all_mob_loot(mob_id: int):
|
|
Network.send_message(OpCodes.MOB_LOOT_TAKE_ALL, {"mobId": mob_id})
|
|
|
|
func _handle_error(data: Dictionary):
|
|
var error_message = data.get("error", "Unknown error")
|
|
push_error("[Server Error] " + error_message)
|
|
print("[GameState] Server error: " + error_message)
|
|
|
|
# Dungeon list handler
|
|
func _handle_dungeon_list(data: Dictionary):
|
|
print("[GameState] Received dungeon list")
|
|
dungeon_list_received.emit(data)
|
|
|
|
# Dungeon browser actions
|
|
func request_dungeon_list():
|
|
Network.send_message(OpCodes.DUNGEON_LIST_REQUEST, {})
|
|
|
|
func create_dungeon(tier: int):
|
|
Network.send_message(OpCodes.DUNGEON_CREATE, {"Tier": tier})
|
|
|
|
func join_dungeon(dungeon_id: String):
|
|
Network.send_message(OpCodes.DUNGEON_JOIN, {"DungeonId": dungeon_id})
|
|
|
|
# ===== CRAFTING SYSTEM =====
|
|
|
|
var crafting_skills: Dictionary = {} # skillType -> {level, xp, xpForNext}
|
|
var known_recipes: Array = []
|
|
|
|
func _handle_crafting_skills(data: Dictionary):
|
|
print("[GameState] Received crafting skills")
|
|
crafting_skills = data.get("skills", {})
|
|
crafting_skills_updated.emit(crafting_skills)
|
|
|
|
func _handle_crafting_recipes(data: Dictionary):
|
|
print("[GameState] Received crafting recipes")
|
|
known_recipes = data.get("recipes", [])
|
|
crafting_recipes_updated.emit(known_recipes)
|
|
|
|
func _handle_crafting_result(data: Dictionary):
|
|
print("[GameState] Received crafting result: %s" % str(data))
|
|
crafting_result_received.emit(data)
|
|
|
|
# Refresh inventory if successful
|
|
if data.get("success", false):
|
|
request_inventory()
|
|
|
|
func _handle_recipe_discovered(data: Dictionary):
|
|
print("[GameState] Discovered new recipe: %s" % data.get("name", "Unknown"))
|
|
recipe_discovered.emit(data)
|
|
# Refresh recipes
|
|
request_crafting_recipes()
|
|
|
|
func _handle_crafting_skill_levelup(data: Dictionary):
|
|
print("[GameState] Crafting skill level up: %s to level %d" % [
|
|
data.get("skillName", "Unknown"),
|
|
data.get("newLevel", 1)
|
|
])
|
|
# Refresh skills
|
|
request_crafting_skills()
|
|
|
|
func request_crafting_skills():
|
|
Network.send_message(OpCodes.CRAFTING_SKILLS_REQUEST, {})
|
|
|
|
func request_crafting_recipes():
|
|
Network.send_message(OpCodes.CRAFTING_RECIPES_REQUEST, {})
|
|
|
|
func request_inventory():
|
|
Network.send_message(OpCodes.INVENTORY_REQUEST, {})
|
|
|
|
func send_craft_request(recipe_id: int):
|
|
Network.send_message(OpCodes.CRAFTING_ATTEMPT, {"RecipeId": recipe_id})
|
|
|
|
func send_discover_recipe(ingredients: Array):
|
|
# ingredients is an array of {itemDefinitionId, quantity}
|
|
Network.send_message(OpCodes.CRAFTING_ATTEMPT, {"Ingredients": ingredients, "Discover": true})
|
|
|
|
func send_discover_recipe_with_skill(ingredients: Array, skill_type: int):
|
|
# Discovery with specific skill type
|
|
Network.send_message(OpCodes.CRAFTING_ATTEMPT, {
|
|
"Ingredients": ingredients,
|
|
"Discover": true,
|
|
"SkillType": skill_type
|
|
})
|
|
|
|
# Stash functions
|
|
func _handle_stash_state(data: Dictionary):
|
|
stash.slots = int(data.get("slots", data.get("Slots", 50)))
|
|
stash.items = data.get("items", data.get("Items", []))
|
|
is_vip = true # If we got stash state, we're VIP
|
|
stash_updated.emit(stash)
|
|
|
|
func _handle_stash_result(data: Dictionary):
|
|
var success = data.get("success", data.get("Success", false))
|
|
var error = data.get("error", data.get("Error", ""))
|
|
var message = data.get("message", data.get("Message", ""))
|
|
|
|
if error == "vip_required":
|
|
is_vip = false
|
|
|
|
stash_result.emit({"success": success, "error": error, "message": message})
|
|
|
|
func request_stash():
|
|
Network.send_message(OpCodes.STASH_REQUEST, {})
|
|
|
|
func stash_deposit(inventory_slot: int, quantity: int = 1, target_slot: int = -1):
|
|
Network.send_message(OpCodes.STASH_DEPOSIT, {
|
|
"inventorySlot": inventory_slot,
|
|
"quantity": quantity,
|
|
"targetSlot": target_slot
|
|
})
|
|
|
|
func stash_withdraw(stash_slot: int, quantity: int = 1):
|
|
Network.send_message(OpCodes.STASH_WITHDRAW, {
|
|
"stashSlot": stash_slot,
|
|
"quantity": quantity
|
|
})
|
|
|
|
func _handle_tile_update(data: Dictionary):
|
|
var tiles = data.get("tiles", data.get("Tiles", []))
|
|
var walkable_updates = data.get("walkable", data.get("Walkable", []))
|
|
|
|
print("[GameState] Received tile update: %d tiles, %d walkable changes" % [tiles.size(), walkable_updates.size()])
|
|
|
|
# Update walkable data if provided
|
|
for w in walkable_updates:
|
|
var x = int(w.get("x", 0))
|
|
var y = int(w.get("y", 0))
|
|
var is_walkable = w.get("w", true)
|
|
var idx = y * dungeon.width + x
|
|
if idx >= 0 and idx < dungeon.tiles.size():
|
|
dungeon.tiles[idx] = 1 if is_walkable else 0
|
|
|
|
# Update visual tiles cache
|
|
if dungeon.has_visual_tiles and tiles.size() > 0:
|
|
for tile in tiles:
|
|
var x = int(tile.get("x", 0))
|
|
var y = int(tile.get("y", 0))
|
|
var layer = int(tile.get("l", 0))
|
|
|
|
# Find and update or add
|
|
var found = false
|
|
for i in range(dungeon.visual_tiles.tiles.size()):
|
|
var t = dungeon.visual_tiles.tiles[i]
|
|
if int(t.get("x", -1)) == x and int(t.get("y", -1)) == y and int(t.get("l", 0)) == layer:
|
|
dungeon.visual_tiles.tiles[i] = tile
|
|
found = true
|
|
break
|
|
|
|
if not found:
|
|
dungeon.visual_tiles.tiles.append(tile)
|
|
|
|
dungeon_tiles_updated.emit(tiles)
|
|
|
|
func _handle_projectile_spawned(data: Dictionary):
|
|
print("[GameState] ===== PROJECTILE SPAWNED EVENT =====")
|
|
print("[GameState] Projectile ID: ", data.get("id", -1))
|
|
print("[GameState] Position: (", data.get("x", 0), ", ", data.get("y", 0), ")")
|
|
print("[GameState] Velocity: (", data.get("vx", 0), ", ", data.get("vy", 0), ")")
|
|
print("[GameState] Sprite: ", data.get("sprite", ""))
|
|
print("[GameState] Linear: ", data.get("isLinear", false))
|
|
print("[GameState] Full data: ", data)
|
|
print("[GameState] Emitting projectile_spawned signal")
|
|
projectile_spawned.emit(data)
|
|
print("[GameState] ===== END PROJECTILE SPAWNED =====")
|
|
|
|
|
|
func _handle_projectile_hit(data: Dictionary):
|
|
print("[GameState] Projectile hit: ", data)
|
|
projectile_hit.emit(data)
|
|
|
|
func _handle_projectile_expired(data: Dictionary):
|
|
print("[GameState] Projectile expired: ", data.get("id", -1))
|
|
projectile_expired.emit(data)
|
|
|
|
func _handle_damage_number(data: Dictionary):
|
|
# Emit damage number for floating damage text
|
|
damage_number.emit(data)
|