extends Node2D # Tile atlas coordinates in your tileset (adjust these to match your tileset) const FLOOR_ATLAS_COORD := Vector2i(1, 0) # Brown floor tile const WALL_ATLAS_COORD := Vector2i(3, 2) # Purple wall tile const TILE_SIZE := 16 # Tileset tile size const TILE_SCALE := 2 # Scale up for better visibility const WORLD_TILE_SIZE := TILE_SIZE * TILE_SCALE # 32 pixels per tile in world @onready var player_node = $Player @onready var camera = $Camera2D @onready var players_container = $Entities/Players @onready var mobs_container = $Entities/Mobs @onready var chests_container = $Entities/Chests @onready var items_container = $Entities/DroppedItems @onready var portals_container = $Entities/Portals @onready var loot_chests_container = $Entities/LootChests @onready var projectiles_container = $Entities/Projectiles @onready var tilemap: TileMapLayer = $TileMapLayer @onready var hud = $Hud @onready var inventory_panel = $Inventory @onready var chat_panel = $Chat # Crafting panel (loaded dynamically) var crafting_panel = null # Visual tile renderer (for V2 dungeons) var visual_renderer: VisualTileMapRenderer = null # Scenes for entities var player_scene: PackedScene = null var mob_scene: PackedScene = null var chest_scene: PackedScene = null var item_scene: PackedScene = null var portal_scene: PackedScene = null var loot_chest_scene: PackedScene = null var projectile_scene: PackedScene = null var damage_number_scene: PackedScene = null # Projectile tracking var projectiles: Dictionary = {} # id -> projectile node var aim_angle: float = 0.0 var last_attack_time: float = -999.0 # Start far in the past so first attack always works var attack_cooldown: float = 0.5 # Default attack cooldown in seconds func _ready(): # Add to group for HUD to access add_to_group("dungeon_manager") # Load entity scenes if ResourceLoader.exists("res://scenes/dungeon/other_player.tscn"): player_scene = load("res://scenes/dungeon/other_player.tscn") if ResourceLoader.exists("res://scenes/dungeon/mob.tscn"): mob_scene = load("res://scenes/dungeon/mob.tscn") if ResourceLoader.exists("res://scenes/dungeon/chest.tscn"): chest_scene = load("res://scenes/dungeon/chest.tscn") if ResourceLoader.exists("res://scenes/dungeon/dropped_item.tscn"): item_scene = load("res://scenes/dungeon/dropped_item.tscn") if ResourceLoader.exists("res://scenes/dungeon/portal.tscn"): portal_scene = load("res://scenes/dungeon/portal.tscn") if ResourceLoader.exists("res://scenes/dungeon/loot_chest.tscn"): loot_chest_scene = load("res://scenes/dungeon/loot_chest.tscn") if ResourceLoader.exists("res://scenes/dungeon/projectile.tscn"): projectile_scene = load("res://scenes/dungeon/projectile.tscn") if ResourceLoader.exists("res://scenes/dungeon/damage_number.tscn"): damage_number_scene = load("res://scenes/dungeon/damage_number.tscn") # Load crafting UI if ResourceLoader.exists("res://scenes/ui/crafting_ui.tscn"): var crafting_scene = load("res://scenes/ui/crafting_ui.tscn") crafting_panel = crafting_scene.instantiate() crafting_panel.visible = false add_child(crafting_panel) # Create visual tile renderer visual_renderer = VisualTileMapRenderer.new() visual_renderer.name = "VisualTileRenderer" add_child(visual_renderer) # Move it behind entities move_child(visual_renderer, 0) # Defer GameState connections call_deferred("_connect_gamestate") # Initially hidden visible = false func _connect_gamestate(): if GameState: GameState.dungeon_entered.connect(_on_dungeon_entered) GameState.dungeon_state_updated.connect(_on_state_updated) GameState.state_changed.connect(_on_game_state_changed) GameState.dungeon_tiles_updated.connect(_on_tiles_updated) GameState.projectile_spawned.connect(_on_projectile_spawned) GameState.projectile_hit.connect(_on_projectile_hit) GameState.projectile_expired.connect(_on_projectile_expired) GameState.damage_number.connect(_on_damage_number) func _on_game_state_changed(state: String): var is_playing = (state == "PLAYING") visible = is_playing set_process(is_playing) set_physics_process(is_playing) # Show/hide HUD with dungeon if hud: hud.visible = is_playing # Hide inventory and crafting when leaving dungeon if not is_playing: if inventory_panel: inventory_panel.visible = false if crafting_panel: crafting_panel.visible = false # Clear visual tiles when leaving dungeon if not is_playing and visual_renderer: visual_renderer.clear_tiles() func _on_dungeon_entered(): # Scale the tilemap to match world coordinates if tilemap: tilemap.scale = Vector2(TILE_SCALE, TILE_SCALE) # Check for visual tiles (V2 dungeon) if GameState.dungeon.has_visual_tiles and visual_renderer: print("[DungeonManager] Using V2 visual tiles") # Hide the old tilemap, use visual renderer instead if tilemap: tilemap.visible = false await visual_renderer.render_visual_tiles(GameState.dungeon.visual_tiles) else: print("[DungeonManager] Using legacy tilemap") # Use old tilemap for V1 dungeons if tilemap: tilemap.visible = true if visual_renderer: visual_renderer.clear_tiles() _build_tiles() # Position player at spawn var spawn_x = GameState.self_player.get("x", 0) var spawn_y = GameState.self_player.get("y", 0) var world_pos = Vector2(spawn_x, spawn_y) if player_node: player_node.position = world_pos if camera: camera.position = world_pos # Player texture is now setup in player.gd using AnimatedSprite2D # Request initial inventory if Network: Network.send_message(OpCodes.INVENTORY_REQUEST, {}) func _build_tiles(): if not tilemap: push_error("[DungeonManager] TileMapLayer not found!") return tilemap.clear() if not GameState: return var tiles = GameState.dungeon.tiles var width = GameState.dungeon.width var height = GameState.dungeon.height if tiles.is_empty(): print("[DungeonManager] No tiles to render") return if tilemap.tile_set == null: push_error("[DungeonManager] TileSet is null!") return var source_count = tilemap.tile_set.get_source_count() if source_count == 0: push_error("[DungeonManager] TileSet has no sources!") return var source_id = tilemap.tile_set.get_source_id(0) # Build the tilemap for x in range(width): if x >= tiles.size(): continue for y in range(height): if y >= tiles[x].size(): continue var tile_type = tiles[x][y] if tile_type == 1: tilemap.set_cell(Vector2i(x, y), source_id, WALL_ATLAS_COORD) else: tilemap.set_cell(Vector2i(x, y), source_id, FLOOR_ATLAS_COORD) print("[DungeonManager] Tilemap built: %dx%d" % [width, height]) func _input(event: InputEvent): # Handle touch screen taps for attacking if event is InputEventScreenTouch and event.pressed: var ui_open = (inventory_panel and inventory_panel.visible) or (chat_panel and chat_panel.visible) # Don't attack if UI is open if ui_open: return # Calculate attack direction from touch position to player var touch_world_pos = camera.get_global_mouse_position() var player_pos = Vector2(GameState.self_player.get("x", 0), GameState.self_player.get("y", 0)) var attack_angle = (touch_world_pos - player_pos).angle() # Update aim angle for visual feedback aim_angle = attack_angle if player_node and player_node.has_method("set_aim_angle"): player_node.set_aim_angle(aim_angle) # Perform attack _perform_attack(attack_angle) func _process(delta): if not GameState or GameState.current_state != GameState.STATE_PLAYING: return _handle_input() _update_camera(delta) func _physics_process(_delta): if not GameState or GameState.current_state != GameState.STATE_PLAYING: return _send_movement() func _handle_input(): if not camera: return # Don't process game input if inventory or chat is open var ui_open = (inventory_panel and inventory_panel.visible) or (chat_panel and chat_panel.visible) # Calculate aim angle from mouse/touch position var mouse_pos = get_global_mouse_position() var player_screen_pos = camera.get_screen_center_position() aim_angle = (mouse_pos - player_screen_pos).angle() # Update player aim visual if player_node and player_node.has_method("set_aim_angle"): player_node.set_aim_angle(aim_angle) # Attack on click/touch (only if UI not open) # This handles both mouse clicks and touch taps if not ui_open and Input.is_action_just_pressed("attack"): _perform_attack(aim_angle) # Inventory toggle (I key) if Input.is_action_just_pressed("inventory"): if chat_panel.visible != true: _toggle_inventory() # Crafting toggle (C key) if Input.is_action_just_pressed("crafting"): if chat_panel.visible != true: _toggle_crafting() # Escape handling - close UI panels, or show hint about portals if Input.is_action_just_pressed("escape_menu"): # Close UI first (in priority order) if crafting_panel and crafting_panel.visible: crafting_panel.visible = false elif inventory_panel and inventory_panel.visible: inventory_panel.visible = false elif chat_panel and chat_panel.visible: chat_panel.visible = false else: # Player pressed escape but no UI open - hint about portals print("[Dungeon] To exit, walk into the purple exit portal near spawn") # Chat (Enter key) if Input.is_action_just_pressed("chat"): _open_chat() # Hotbar keys 1-8 if not ui_open: for i in range(1, 9): if Input.is_action_just_pressed("hotbar_%d" % i): _use_hotbar_slot(i - 1) func _perform_attack(attack_angle: float): # Check attack cooldown var current_time = Time.get_ticks_msec() / 1000.0 var time_since_last_attack = current_time - last_attack_time # Get attack speed from equipped weapon var equipped_weapon = GameState.equipment.get("weapon", null) var weapon_cooldown = attack_cooldown # Default cooldown if equipped_weapon != null and not equipped_weapon.is_empty(): # Get attack speed stat (attacks per second) if available var attack_speed = equipped_weapon.get("attackSpeed", 0.0) if attack_speed > 0: weapon_cooldown = 1.0 / attack_speed # Convert attacks/sec to seconds/attack else: # Default cooldowns based on weapon type var weapon_type = equipped_weapon.get("type", "") match weapon_type: "Weapon": var weapon_name = equipped_weapon.get("name", "").to_lower() if "dagger" in weapon_name or "fist" in weapon_name: weapon_cooldown = 0.3 # Fast weapons elif "sword" in weapon_name: weapon_cooldown = 0.5 # Medium weapons elif "axe" in weapon_name or "mace" in weapon_name: weapon_cooldown = 0.7 # Slow weapons elif "bow" in weapon_name or "crossbow" in weapon_name: weapon_cooldown = 0.8 # Ranged weapons else: weapon_cooldown = 0.5 # Default # Check if enough time has passed since last attack if time_since_last_attack < weapon_cooldown: # Only print every 0.5 seconds to avoid spam if int(time_since_last_attack * 2) != int((time_since_last_attack - get_process_delta_time()) * 2): print("[DungeonManager] Attack on cooldown: %.2f / %.2f seconds" % [time_since_last_attack, weapon_cooldown]) return # Update last attack time last_attack_time = current_time # Determine weapon type for animation var animation_type = "fist" # Check if player has a ranged weapon equipped if equipped_weapon != null and not equipped_weapon.is_empty(): # Server sends camelCase properties var requires_ammo = equipped_weapon.get("requiresAmmunition", false) var is_throwable = equipped_weapon.get("isThrowable", false) var projectile_speed = equipped_weapon.get("projectileSpeed", 0) var weapon_name = equipped_weapon.get("name", "").to_lower() # Determine animation type from weapon if requires_ammo or "bow" in weapon_name or "crossbow" in weapon_name: animation_type = "bow" elif "staff" in weapon_name or "wand" in weapon_name: animation_type = "spell" elif weapon_name != "": animation_type = "sword" print("[DungeonManager] Attack - Weapon: ", equipped_weapon.get("name", "Unknown")) print("[DungeonManager] RequiresAmmo: ", requires_ammo, ", IsThrowable: ", is_throwable, ", Speed: ", projectile_speed) # If weapon fires projectiles (bow, crossbow, throwable), send projectile fire if (requires_ammo or is_throwable) and projectile_speed > 0: print("[DungeonManager] Firing projectile! Direction: (%.2f, %.2f)" % [cos(attack_angle), sin(attack_angle)]) # Calculate direction vector from aim angle var direction_x = cos(attack_angle) var direction_y = sin(attack_angle) if GameState and GameState.has_method("send_fire_projectile"): GameState.send_fire_projectile(direction_x, direction_y) print("[DungeonManager] Projectile fire command sent to server") else: print("[DungeonManager] ERROR: GameState.send_fire_projectile not available!") else: print("[DungeonManager] Using melee attack") # Melee weapon - use normal attack GameState.send_attack(attack_angle) else: print("[DungeonManager] No weapon equipped, using fists") # No weapon or empty slot - use normal attack (fists) GameState.send_attack(attack_angle) # Play attack animation on player (don't await to avoid blocking) if player_node and player_node.has_method("play_attack_animation"): player_node.play_attack_animation(animation_type) print("[DungeonManager] Triggered %s attack animation" % animation_type) func _send_movement(): # Don't move if UI is open var ui_open = (inventory_panel and inventory_panel.visible) or (chat_panel and chat_panel.visible) if ui_open: return var dx = Input.get_axis("move_left", "move_right") var dy = Input.get_axis("move_up", "move_down") var move_vec = Vector2(dx, dy) if move_vec.length() > 1: move_vec = move_vec.normalized() # Update player animation based on movement if player_node and player_node.has_method("set_movement"): player_node.set_movement(move_vec) GameState.send_move(move_vec.x, move_vec.y, aim_angle) func _update_camera(delta): if not camera or not GameState: return var target_x = GameState.self_player.get("x", camera.position.x) var target_y = GameState.self_player.get("y", camera.position.y) var target_pos = Vector2(target_x, target_y) camera.position = camera.position.lerp(target_pos, 5.0 * delta) func _on_state_updated(): if not GameState: return # Update player position if player_node: var px = GameState.self_player.get("x", player_node.position.x) var py = GameState.self_player.get("y", player_node.position.y) player_node.position = Vector2(px, py) if player_node.has_method("update_health"): var hp = GameState.self_player.get("health", 100) var max_hp = GameState.self_player.get("max_health", 100) player_node.update_health(hp, max_hp) # Update entities if player_scene and players_container: _update_entities(players_container, GameState.players, player_scene) if mob_scene and mobs_container: _update_entities(mobs_container, GameState.mobs, mob_scene) if chest_scene and chests_container: _update_entities(chests_container, GameState.chests, chest_scene) if item_scene and items_container: _update_entities(items_container, GameState.dropped_items, item_scene) if portal_scene and portals_container: _update_entities(portals_container, GameState.portals, portal_scene) if loot_chest_scene and loot_chests_container: _update_loot_chests() func _update_entities(container: Node2D, data: Dictionary, scene: PackedScene): if scene == null or container == null: return var seen_ids = [] for id in data: seen_ids.append(id) var entity_data = data[id] var entity_node = _find_entity_by_id(container, id) if entity_node == null: entity_node = scene.instantiate() entity_node.set_meta("entity_id", id) container.add_child(entity_node) var x = entity_data.get("x", entity_data.get("X", 0)) var y = entity_data.get("y", entity_data.get("Y", 0)) entity_node.position = Vector2(x, y) if entity_node.has_method("update_data"): entity_node.update_data(entity_data) for child in container.get_children(): if child.has_meta("entity_id"): var id = child.get_meta("entity_id") if id not in seen_ids: child.queue_free() func _find_entity_by_id(container: Node2D, id) -> Node2D: for child in container.get_children(): if child.has_meta("entity_id") and child.get_meta("entity_id") == id: return child return null func _toggle_inventory(): if inventory_panel: inventory_panel.visible = not inventory_panel.visible if inventory_panel.visible and Network: Network.send_message(OpCodes.INVENTORY_REQUEST, {}) func _toggle_crafting(): if crafting_panel: if crafting_panel.visible: crafting_panel.visible = false else: crafting_panel.show_crafting() else: print("[DungeonManager] Crafting UI not loaded") func _open_chat(): if chat_panel: chat_panel.visible = true if chat_panel.has_method("focus_input"): chat_panel.focus_input() func _use_hotbar_slot(index: int): if not GameState: return var hotbar_entry = GameState.hotbar[index] if hotbar_entry and hotbar_entry.has("inventory_slot"): GameState.send_use_item(hotbar_entry.inventory_slot) func _update_loot_chests(): if loot_chest_scene == null or loot_chests_container == null: return var seen_ids = [] for id in GameState.loot_chests: seen_ids.append(id) var chest_data = GameState.loot_chests[id] var chest_node = _find_entity_by_id(loot_chests_container, id) if chest_node == null: chest_node = loot_chest_scene.instantiate() chest_node.set_meta("entity_id", id) loot_chests_container.add_child(chest_node) if chest_node.has_method("setup"): chest_node.setup(chest_data) # Remove chests that no longer exist for child in loot_chests_container.get_children(): if child.has_meta("entity_id"): var id = child.get_meta("entity_id") if id not in seen_ids: child.queue_free() func _on_tiles_updated(tiles: Array): if visual_renderer: visual_renderer.update_tiles(tiles) # ===== Projectile Event Handlers ===== func _on_projectile_spawned(data: Dictionary): print("[DungeonManager] Projectile spawned event received: ", data) if projectile_scene == null: print("[DungeonManager] ERROR: projectile_scene is null!") return if projectiles_container == null: print("[DungeonManager] ERROR: projectiles_container is null!") return var proj_id = data.get("id", -1) if proj_id == -1: print("[DungeonManager] ERROR: Invalid projectile ID") return print("[DungeonManager] Creating projectile instance for ID: ", proj_id) # Create projectile instance var projectile = projectile_scene.instantiate() projectile.name = "Projectile_" + str(proj_id) projectiles_container.add_child(projectile) print("[DungeonManager] Projectile node created and added to container") # Initialize projectile with data if projectile.has_method("initialize"): projectile.initialize(data) print("[DungeonManager] Projectile initialized") else: print("[DungeonManager] ERROR: Projectile has no initialize method!") # Store in tracking dictionary projectiles[proj_id] = projectile print("[DungeonManager] Projectile ", proj_id, " tracked. Total projectiles: ", projectiles.size()) func _on_projectile_hit(data: Dictionary): var proj_id = data.get("projectileId", -1) if proj_id == -1: return # Remove projectile on hit if projectiles.has(proj_id): var projectile = projectiles[proj_id] if is_instance_valid(projectile): projectile.queue_free() projectiles.erase(proj_id) print("[DungeonManager] Projectile ", proj_id, " removed on hit") # TODO: Play hit effect at projectile position func _on_projectile_expired(data: Dictionary): var proj_id = data.get("projectileId", -1) if proj_id == -1: return # Remove projectile on expiration if projectiles.has(proj_id): var projectile = projectiles[proj_id] if is_instance_valid(projectile): projectile.queue_free() projectiles.erase(proj_id) var reason = data.get("reason", "unknown") print("[DungeonManager] Projectile ", proj_id, " expired (", reason, ")") func _on_damage_number(data: Dictionary): if not damage_number_scene: print("[DungeonManager] Damage number scene not loaded!") return var damage = data.get("damage", 0) print("[DungeonManager] Damage event received: ", data) print("[DungeonManager] Damage value: ", damage) if damage <= 0: print("[DungeonManager] Damage is 0 or negative, skipping") return # Get target position - need to find the entity's position var target_type = data.get("targetType", "") var target_id = data.get("targetId", 0) var target_pos = Vector2.ZERO var found_target = false # Find target entity to get position if target_type == "mob": # Check mobs container for mob_node in mobs_container.get_children(): var mob_id = mob_node.mob_data.get("id", mob_node.mob_data.get("Id", -1)) if mob_id == target_id: target_pos = mob_node.position found_target = true # Play hurt effect on mob if mob_node.has_method("play_hurt_effect"): mob_node.play_hurt_effect() break elif target_type == "player": # Check if it's the local player if target_id == GameState.character.id: target_pos = player_node.position found_target = true else: # Check other players for player in players_container.get_children(): if player.player_id == target_id: target_pos = player.position found_target = true break if not found_target: return # Create damage number var dmg_number = damage_number_scene.instantiate() add_child(dmg_number) dmg_number.position = target_pos # Determine color based on damage flags var color = Color.RED # Default red for normal damage if data.get("wasResisted", false): color = Color(0.7, 0.7, 0.7) # Gray for resisted elif data.get("wasWeakness", false): color = Color(1.0, 0.5, 0.0) # Orange for weakness dmg_number.initialize(damage, color)