extends CharacterBody3D # Managers var movement_manager var race_manager var input_manager var playerboard_manager var action_manager var special_tiles_manager var powerup_manager # Score tracking var score: int = 0 signal position_changed signal tekton_carried_changed(is_carrying) # Display name (synced across network) var _display_name: String = "" var display_name: String: set(value): _display_name = value # Update label if it exists var name_label = get_node_or_null("Name") if name_label: name_label.text = _display_name # Sync to other peers if we are authority and connected if is_multiplayer_authority() and is_inside_tree() and can_rpc(): rpc("sync_display_name", _display_name) get: return _display_name # Helper to check network status func can_rpc() -> bool: if not multiplayer.has_multiplayer_peer(): return false if multiplayer.multiplayer_peer.get_class() == "OfflineMultiplayerPeer": return false return multiplayer.multiplayer_peer.get_connection_status() == MultiplayerPeer.CONNECTION_CONNECTED # Special effect states var is_frozen: bool = false: set(value): if is_frozen == value: return is_frozen = value _refresh_player_visuals() var is_stop_frozen: bool = false: # Special freeze for Stop n Go phase set(value): if is_stop_frozen == value: return is_stop_frozen = value _refresh_player_visuals() var is_invisible: bool = false: set(value): if is_invisible == value: return is_invisible = value _refresh_player_visuals() var is_slowed: bool = false: set(value): if is_slowed == value: return is_slowed = value _refresh_player_visuals() var original_movement_range: int = 1 # Tekton Interaction var carried_tekton: Node3D = null var is_carrying_tekton: bool = false: set(value): if is_carrying_tekton == value: return is_carrying_tekton = value _refresh_player_visuals() emit_signal("tekton_carried_changed", value) # Visual/Logic side effects if any var is_charged_strike: bool = false: set(value): if is_charged_strike == value: return is_charged_strike = value if is_charged_strike: charged_strike_timer = MAX_CHARGED_STRIKE_TIME _refresh_player_visuals() # Sync to others if we are the authority if is_multiplayer_authority() and can_rpc(): rpc("sync_charged_strike", is_charged_strike) @rpc("any_peer", "call_local", "reliable") func sync_charged_strike(state: bool): is_charged_strike = state @export var is_bot: bool = false @export var enhanced_gridmap_path: NodePath = "/root/Main/EnhancedGridMap" var enhanced_gridmap: EnhancedGridMap @export var current_position: Vector2i var target_position: Vector2i = Vector2i(-1, -1) # For collision prediction var is_player_moving: bool = false: get: return movement_manager.is_moving if movement_manager else false set(value): if movement_manager: movement_manager.is_moving = value var _verify_timer: float = 0.0 var _movement_tween: Tween = null var can_finish: bool: get: return race_manager.can_finish if race_manager else false set(value): if race_manager: race_manager.can_finish = value @export var cell_size: Vector3 = Vector3(1, 0.05, 1) @export var cell_offset: Vector3 = Vector3(0, 0, 0) @export var goals: Array[int]: get: return race_manager.goals if race_manager else Array([], TYPE_INT, "", null) as Array[int] set(value): if race_manager: race_manager.goals = value @export var playerboard: Array[int]: get: return race_manager.playerboard if race_manager else Array([], TYPE_INT, "", null) as Array[int] set(value): if race_manager: race_manager.playerboard = value # Modifier for Turn based var has_performed_action: bool = false var _is_processing_action: bool = false var selected_gridmap_position = Vector2i(-1, -1) var selected_playerboard_slot = -1 var targeted_playerboard_slot = -1 #var has_performed_action: bool = false # Modifier for player models var rotation_speed: float = 10.0 var spawn_locations = [ Vector2i(0, 0), # (0,1,0) Vector2i(0, 1), # (0,1,1) Vector2i(0, 2), # (0,1,2) Vector2i(0, 3), # (0,1,3) Vector2i(0, 4), # (0,1,4) Vector2i(0, 5), # (0,1,5) Vector2i(0, 6), Vector2i(0, 7), Vector2i(0, 8), Vector2i(0, 9), Vector2i(0, 10), Vector2i(0, 11), Vector2i(0, 12), Vector2i(0, 13) ] # Add these as class variables at the top of the file var finish_locations: Array: get: return race_manager.finish_locations if race_manager else [] var target_visual_position: Vector3 = Vector3.ZERO # For client-side smoothing var snapshot_buffer: Array = [] # Array of {time: int, pos: Vector3} const INTERPOLATION_OFFSET: int = 150 # Increased to 150ms for better jitter buffering var _last_received_timestamp: int = 0 var _last_movement_finish_time: int = 0 var spawn_point_selected = false # Action for hilighter var highlighted_spawn_points = [] var _is_highlighting: bool = false # Character selection and animation @onready var anim_player: AnimationPlayer = $AnimationPlayer @onready var character_bob: Node3D = $Bob @onready var character_masbro: Node3D = $Masbro @onready var character_gatot: Node3D = $Gatot @onready var character_oldpop: Node3D = $Oldpop # Skill initiator VFX @onready var vfx_skill_freeze: AnimatedSprite3D = $skill_freeze @onready var vfx_skill_ghost: AnimatedSprite3D = $skill_ghost @onready var vfx_skill_speed: AnimatedSprite3D = $skill_speed @onready var vfx_skill_wall: AnimatedSprite3D = $skill_wall # Knock / receiver VFX @onready var vfx_attack_top: AnimatedSprite3D = $attack_mode_top @onready var vfx_attack_bot: AnimatedSprite3D = $attack_mode_bot @onready var vfx_stunned: AnimatedSprite3D = $receiver_skill_stunned var _selected_character: String = "Masbro" var _player_loadout: Dictionary = {} ## Synced from the owning client via sync_loadout RPC var selected_character: String: get: return _selected_character set(value): if _selected_character == value: return _selected_character = value if is_inside_tree(): set_character(value) const AVAILABLE_CHARACTERS: Array[String] = ["Bob", "Masbro", "Gatot", "Oldpop"] @export var movement_range: int = 1: set(value): movement_range = value if movement_manager: movement_manager.movement_range = value @export var use_diagonal_movement: bool = false: set(value): use_diagonal_movement = value if enhanced_gridmap: enhanced_gridmap.set_diagonal_movement(value) if movement_manager: movement_manager.use_diagonal_movement = value @export var is_my_turn: bool = false: set(value): is_my_turn = value if is_my_turn and is_multiplayer_authority(): NotificationManager.send_message(self , NotificationManager.MESSAGES.TURN_START, NotificationManager.MessageType.NORMAL) @export var has_moved_this_turn = false # Track, Lap, Position # Delegated to RaceManager func _ready(): # Ensure name is set first (node name = authority ID for multiplayer identification) # 3. SET PHYSICS MODE TO FLOATING # This prevents "grounding" friction and gravity from fighting our Tweens motion_mode = CharacterBody3D.MOTION_MODE_FLOATING print("[Player] initialized: ", name, " Authority: ", get_multiplayer_authority()) # name = str(get_multiplayer_authority()) # CRITICAL FIX: Do NOT overwrite name. Bots have authority 1 but unique names (IDs). # Look up player's display name from LobbyManager var my_id = get_multiplayer_authority() print("[Player] _ready for %s (Auth: %s). Current display_name: '%s'" % [name, my_id, display_name]) if is_bot or is_in_group("Bots"): # Bots get a unique name based on their Node Name (Bot ID) var bot_id = name.to_int() var bot_names = ["Bot", "Alpha", "Beta", "Delta"] var name_idx = (bot_id - 1) % bot_names.size() display_name = "%s %d" % [bot_names[name_idx], bot_id] else: # Humans get name from Lobby for player_data in LobbyManager.get_players(): if player_data.get("id") == my_id: display_name = player_data.get("name", "Player") break if display_name.is_empty(): display_name = "Player %d" % my_id $Name.text = display_name # Character Pointer Visibility # Visible to all human players. Green for local player, Red for others. var pointer = get_node_or_null("CharacterPointer") # === All animations loaded from animation-pack (built from animation-0.glb) === if pointer: pointer.visible = true var pointer_shader = load("res://assets/shaders/character_pointer.gdshader") var mat = ShaderMaterial.new() mat.shader = pointer_shader if name == str(multiplayer.get_unique_id()): mat.set_shader_parameter("pointer_color", Color(0.0, 1.0, 0.0, 1.0)) # Green if has_node("Name"): $Name.modulate = Color(0.2, 0.8, 0.2, 1.0) # Pleasant Green for Name else: mat.set_shader_parameter("pointer_color", Color(1.0, 0.0, 0.0, 1.0)) # Red if has_node("Name"): $Name.modulate = Color.WHITE # White for others if pointer is MeshInstance3D: pointer.material_override = mat # Sync name to other peers if this is our local player or a bot we own if is_multiplayer_authority() and can_rpc(): rpc("sync_display_name", display_name) # Wait briefly to ensure proper scene setup and server recognition await get_tree().create_timer(0.5).timeout # More robust way to get the main scene var main_scene = get_tree().get_root().get_node_or_null("Main") if not main_scene: push_error("Main scene not found") return # Ensure proper initialization order enhanced_gridmap = get_node(enhanced_gridmap_path) if main_scene: enhanced_gridmap = main_scene.get_node("EnhancedGridMap") _init_managers() # Initialize character selection from LobbyManager _setup_character() # Initialize playerboard for everyone playerboard.resize(25) playerboard.fill(-1) # ========================================================================= # BOT-SPECIFIC SETUP - BotController handles bot AI, we just disable input # ========================================================================= if is_bot == true or is_in_group("Bots"): # Disable input processing for bots set_process_input(false) set_process_unhandled_input(false) # Set initial position for bots (Only if NOT randomized/Stop N Go by server) if enhanced_gridmap: if is_multiplayer_authority() and not LobbyManager.get_randomize_spawn() and LobbyManager.game_mode != "Stop n Go": current_position = _find_random_spawn_position() update_player_position(current_position) spawn_point_selected = true if can_rpc(): rpc("set_spawn_position", current_position) rpc("notify_spawn_selected", current_position) # Assign bot character (deterministic based on ID to match lobby preview) var bot_id_val = name.to_int() var bot_characters = ["Bob", "Gatot", "Masbro", "Oldpop"] var char_index = (bot_id_val - 1) % bot_characters.size() var bot_char_name = bot_characters[char_index] set_character(bot_char_name) if is_multiplayer_authority() and can_rpc(): rpc("sync_character", bot_char_name) # Sync bot status to network if is_multiplayer_authority() and can_rpc(): rpc("sync_bot_status", true) # Continue to manager initialization... # ========================================================================= # HUMAN PLAYER SETUP # ========================================================================= if enhanced_gridmap: enhanced_gridmap.initialize_astar() enhanced_gridmap.set_diagonal_movement(use_diagonal_movement) # Only set position if not using random spawn (host will assign via RPC) if not LobbyManager.get_randomize_spawn() and LobbyManager.game_mode != "Stop n Go" and not spawn_point_selected: current_position = find_valid_starting_position() update_player_position(current_position) # Ensure proper initial positioning if not LobbyManager.get_randomize_spawn() and LobbyManager.game_mode != "Stop n Go" and not spawn_point_selected: global_position = Vector3( current_position.x * 1 + 1 * 0.5, 1.0, current_position.y * 1 + 1 * 0.5 ) target_visual_position = global_position if is_multiplayer_authority() and can_rpc(): rpc("sync_position", current_position) else: target_visual_position = global_position # If random spawn is enabled, do NOT broadcast (0,0). Wait for set_spawn_position. # Prevent visual "jump" by hiding until spawn position is confirmed if LobbyManager.get_randomize_spawn() and not spawn_point_selected: visible = false _init_floor_spawn_anchor() var floor_spawn_anchor: Node3D func _init_floor_spawn_anchor(): floor_spawn_anchor = Node3D.new() floor_spawn_anchor.name = "FloorSpawnAnchor" floor_spawn_anchor.top_level = true add_child(floor_spawn_anchor) if floor_spawn_bot: floor_spawn_bot.reparent(floor_spawn_anchor, false) if floor_spawn_top: floor_spawn_top.reparent(floor_spawn_anchor, false) func _load_dasher_animations(): # Deprecated: dasher animations merged into animation-pack. pass @onready var floor_spawn_bot: AnimatedSprite3D = $floor_spawn_bot @onready var floor_spawn_top: AnimatedSprite3D = $floor_spawn_top @onready var vfx_scatter_knock: AnimatedSprite3D = $scatter_knock #func _input(event: InputEvent) -> void: #if event.is_action_pressed("grab_item"): #play_floor_spawn() func play_floor_spawn(): if not floor_spawn_anchor: return # Anchor detaches the visual effect from player's movement if is_instance_valid(carried_tekton): floor_spawn_anchor.global_position = Vector3(carried_tekton.global_position.x, global_position.y, carried_tekton.global_position.z) else: floor_spawn_anchor.global_position = global_position floor_spawn_bot.visible = true floor_spawn_top.visible = true floor_spawn_bot.play("floor_spawn_bot") floor_spawn_top.play("floor_spawn_top") # Wait for animation to finish then hide. # We assume both animations have roughly similar lengths. await floor_spawn_bot.animation_finished floor_spawn_bot.visible = false floor_spawn_top.visible = false @rpc("any_peer", "call_local") func play_scatter_knock(): if vfx_scatter_knock: vfx_scatter_knock.visible = true vfx_scatter_knock.play("scatter_knock") await vfx_scatter_knock.animation_finished vfx_scatter_knock.visible = false @rpc("any_peer", "call_local", "reliable") func play_playerboard_scatter(): """Show the one-shot scatter VFX over the playerboard UI, but only on the local human player's own client (the board UI belongs to them).""" var is_local = name == str(multiplayer.get_unique_id()) var is_bot_check = is_bot or is_in_group("Bots") if not is_local or is_bot_check: return var main = get_tree().get_root().get_node_or_null("Main") if main and main.has_method("play_playerboard_scatter_vfx"): main.play_playerboard_scatter_vfx() func _init_managers(): movement_manager = load("res://scripts/managers/player_movement_manager.gd").new() movement_manager.name = "MovementManager" add_child(movement_manager) movement_manager.initialize(self , enhanced_gridmap) movement_manager.movement_finished.connect(_on_movement_finished) race_manager = load("res://scripts/managers/player_race_manager.gd").new() race_manager.name = "RaceManager" add_child(race_manager) race_manager.initialize(self , enhanced_gridmap) # Skip InputManager for bots if not (is_bot or is_in_group("Bots")): input_manager = load("res://scripts/managers/player_input_manager.gd").new() input_manager.name = "InputManager" add_child(input_manager) input_manager.initialize(self , movement_manager, race_manager) playerboard_manager = load("res://scripts/managers/playerboard_manager.gd").new() playerboard_manager.name = "PlayerboardManager" add_child(playerboard_manager) playerboard_manager.initialize(self , enhanced_gridmap) action_manager = load("res://scripts/managers/player_action_manager.gd").new() action_manager.name = "ActionManager" add_child(action_manager) action_manager.initialize(self , enhanced_gridmap) special_tiles_manager = load("res://scripts/managers/special_tiles_manager.gd").new() special_tiles_manager.name = "SpecialTilesManager" add_child(special_tiles_manager) special_tiles_manager.initialize(self , enhanced_gridmap) powerup_manager = load("res://scripts/managers/powerup_manager.gd").new() powerup_manager.name = "PowerUpManager" add_child(powerup_manager) powerup_manager.initialize(self , enhanced_gridmap) # ============================================================================= # Character Selection # ============================================================================= func set_character(character_name: String) -> void: """Show only the selected character model and hide others. Updates AnimationPlayer root.""" # Map Lobby names to Model names match character_name: "Copper": character_name = "Oldpop" "Dabro": character_name = "Masbro" "Pip": character_name = "Bob" # "Gatot" matches "Gatot" if character_name not in AVAILABLE_CHARACTERS: push_warning("Invalid character name: %s" % character_name) return _selected_character = character_name # Hide all character models if character_bob: character_bob.visible = false if character_masbro: character_masbro.visible = false if character_gatot: character_gatot.visible = false if character_oldpop: character_oldpop.visible = false # Show selected character and update AnimationPlayer root var active_character: Node3D = null match character_name: "Bob": if character_bob: character_bob.visible = true active_character = character_bob "Masbro": if character_masbro: character_masbro.visible = true active_character = character_masbro "Gatot": if character_gatot: character_gatot.visible = true active_character = character_gatot "Oldpop": if character_oldpop: character_oldpop.visible = true active_character = character_oldpop # Update AnimationPlayer's root node to point to active character if anim_player and active_character: anim_player.root_node = anim_player.get_path_to(active_character) # Start with idle animation play_idle_animation() # Apply outline shader to the active character if active_character: _apply_outline_recursive(active_character) # Apply cosmetic loadout to active model. # Uses _player_loadout (synced by owning client) so ALL peers see the correct skin. if active_character: apply_loadout(active_character) func _apply_outline_recursive(node: Node): if node is MeshInstance3D and node.mesh: for i in range(node.mesh.get_surface_count()): var mat = node.get_active_material(i) if mat: # Only apply if it doesn't already have a next pass if not mat.next_pass: var unique_mat = mat.duplicate() var outline_mat = ShaderMaterial.new() outline_mat.shader = load("res://assets/shaders/outline3d.gdshader") unique_mat.next_pass = outline_mat node.set_surface_override_material(i, unique_mat) for child in node.get_children(): _apply_outline_recursive(child) const COSMETIC_MAPPING = { "head_hat1": { "hide": ["helm_default", "helm1", "helm2", "helm3"], "show": ["head_hat1"], "materials": {} }, "head_crown": { "hide": ["helm_default", "helm1", "helm2", "helm3"], "show": ["head_crown"], "materials": {} }, "costume_red": { "hide": [], "show": [], "materials": { "body": "res://assets/materials/body_red.tres", "arm": "res://assets/materials/body_red.tres" } }, "costume_gold": { "hide": [], "show": [], "materials": { "body": "res://assets/materials/body_gold.tres", "arm": "res://assets/materials/body_gold.tres" } }, "glove_leather": { "hide": ["hands", "glove_default"], "show": ["glove_leather"], "materials": {} }, "acc_glasses": { "hide": [], "show": ["acc_glasses"], "materials": {} } } func apply_loadout(character_node: Node3D) -> void: """Apply equipped cosmetics via SkinManager — the single source of truth. Uses _player_loadout (synced from the owning client via sync_loadout RPC) so all peers render the same skin regardless of their own loadout.""" # Fall back to UserProfileManager for the local player before network sync arrives var loadout: Dictionary = {} if not is_bot and not is_in_group("Bots"): loadout = _player_loadout if not _player_loadout.is_empty() else UserProfileManager.loadout # Pass 'self' (the player CharacterBody3D) as character_root because SkinManager # looks for a CHILD node named e.g. "Oldpop" inside character_root. # self.$Oldpop, self.$Bob etc. are direct children, matching SKIN_CATALOG "character" keys. SkinManager.apply_loadout(self, loadout) func _get_all_mesh_instances(node: Node) -> Array: var result = [] if node is MeshInstance3D or node.get_class() == "SkinnedMeshInstance3D": result.append(node) for child in node.get_children(): result.append_array(_get_all_mesh_instances(child)) return result @rpc("any_peer", "call_local", "reliable") func sync_character(character_name: String) -> void: """Sync character selection across all clients.""" set_character(character_name) @rpc("any_peer", "call_local", "reliable") func sync_loadout(loadout_data: Dictionary) -> void: """Sync the player's skin loadout to all peers so everyone sees the correct skin.""" _player_loadout = loadout_data # Pass 'self' as character_root — SkinManager will find $Oldpop/$Bob/etc. by name SkinManager.apply_loadout(self, _player_loadout) # Re-apply outline shader to ensure it's present after skin changes var active_character: Node3D = null match _selected_character: "Bob": active_character = character_bob "Masbro": active_character = character_masbro "Gatot": active_character = character_gatot "Oldpop": active_character = character_oldpop if active_character: _apply_outline_recursive(active_character) func _setup_character() -> void: """Initialize character based on LobbyManager selection or defaults.""" # Bots self-assign characters based on ID in _ready() # Skipping this for bots prevents race conditions or defaults overriding deterministic bot logic if is_bot or is_in_group("Bots"): return var character_name = "Masbro" # Default var player_authority_id = get_multiplayer_authority() # Look up character from LobbyManager for this player (works for all players) if LobbyManager: var players = LobbyManager.get_players() for player_data in players: if player_data.get("id") == player_authority_id: character_name = player_data.get("character", "Masbro") break set_character(character_name) # If this is our local player, sync character AND loadout to all peers if is_multiplayer_authority() and can_rpc(): # Populate _player_loadout from UserProfileManager and broadcast _player_loadout = UserProfileManager.loadout.duplicate() rpc("sync_character", character_name) rpc("sync_loadout", _player_loadout) # ============================================================================= # Animation Functions # ============================================================================= # Animation speed multiplier for fast-paced gameplay const ANIMATION_SPEED: float = 2.0 func play_walk_animation() -> void: """Play walking animation at increased speed.""" if is_carrying_tekton: if anim_player and anim_player.has_animation("animation-pack/holding_walk"): anim_player.play("animation-pack/holding_walk", -1, ANIMATION_SPEED) return if anim_player and anim_player.has_animation("animation-pack/walk_forward"): anim_player.play("animation-pack/walk_forward", -1, ANIMATION_SPEED) func play_pickup_animation() -> void: """Play pickup/grab tile animation at increased speed.""" if anim_player and anim_player.has_animation("animation-pack/take_tile_1"): anim_player.play("animation-pack/take_tile_1", -1, ANIMATION_SPEED) func play_put_animation() -> void: """Play put/drop tile animation at increased speed.""" if anim_player and anim_player.has_animation("animation-pack/drop_tile_1"): anim_player.play("animation-pack/drop_tile_1", -1, ANIMATION_SPEED) func play_special_animation() -> void: """Play special ability animation (backflip) at increased speed.""" if anim_player and anim_player.has_animation("animation-pack/backflip_1"): anim_player.play("animation-pack/backflip_1", -1, ANIMATION_SPEED * 1.5) func play_idle_animation() -> void: """Play idle animation at normal speed.""" if is_carrying_tekton: if anim_player and anim_player.has_animation("animation-pack/holding_1"): anim_player.play("animation-pack/holding_1") return if anim_player and anim_player.has_animation("animation-pack/idle"): anim_player.play("animation-pack/idle") func _on_movement_finished() -> void: play_idle_animation() # ============================================================================= # Network-Synced Animation Functions # ============================================================================= @rpc("any_peer", "call_local", "reliable") func sync_walk_animation() -> void: """Sync walk animation across network.""" play_walk_animation() @rpc("any_peer", "call_local", "reliable") func sync_pickup_animation(item_id: int = -1) -> void: """Sync pickup/grab animation across network and play sound.""" play_pickup_animation() if item_id >= 11 and item_id <= 14: SfxManager.play("pick_up_power_tile") elif item_id >= 7 and item_id <= 10: SfxManager.play("pick_up_tiles") @rpc("any_peer", "call_local", "reliable") func sync_put_animation() -> void: """Sync put/drop animation across network.""" play_put_animation() @rpc("any_peer", "call_local", "reliable") func sync_special_animation() -> void: """Sync special ability animation across network.""" play_special_animation() @rpc("any_peer", "call_local", "reliable") func sync_floor_spawn_animation() -> void: """Sync floor spawn animation across network.""" play_floor_spawn() # ============================================================================= # Skill VFX # ============================================================================= @rpc("any_peer", "call_local", "reliable") func play_skill_vfx(node_name: String) -> void: """Show, play, and auto-hide a skill AnimatedSprite3D by node name. Called on all peers so everyone sees the initiator's VFX.""" var vfx: AnimatedSprite3D = get_node_or_null(node_name) if not vfx: return vfx.visible = true vfx.play() await vfx.animation_finished vfx.visible = false # ============================================================================= # Screen Shake # ============================================================================= @rpc("any_peer", "call_local", "reliable") func trigger_screen_shake(_shake_type: String) -> void: # Shake disabled by user request. Camera movement now handled by CameraContextManager. pass # Add function to check if position is at finish line func is_at_finish_line() -> bool: return race_manager.is_at_finish_line() # Helper function to check if a 3x3 section matches the goals pattern # Delegated to RaceManager # Generate full 3x3 goals for second lap # Delegated to RaceManager # Modify finish_race to handle lap completion @rpc("any_peer", "reliable") func finish_race(): race_manager.finish_race() # Add function to check 3x3 pattern matching anywhere in 5x5 playerboard func check_pattern_match() -> bool: return race_manager.check_pattern_match() ## Add function to handle new lap #@rpc("any_peer", "reliable") #func start_new_lap(): ## Reset position to start #current_position = find_valid_starting_position() #update_player_position(current_position) # ## Reset playerboard but keep the goals #playerboard.fill(-1) # ## Reset can_finish flag #can_finish = false # ## Sync with other clients #if is_multiplayer_authority(): #rpc("sync_position", current_position) #rpc("sync_playerboard", playerboard) # Modify start_new_lap to handle different lap goals and starting positions @rpc("any_peer", "reliable") func start_new_lap(): race_manager.start_new_lap() # Function to find valid position in finish line # Delegated to RaceManager # Add function to check if player can reach finish func update_finish_availability(): race_manager.update_finish_availability() func unhighlight_finish_line(): race_manager.unhighlight_finish_line() # Add functions to handle finish line visualization func highlight_finish_line(): race_manager.highlight_finish_line() func request_spawn_positions_update(): if multiplayer.is_server(): # Server can directly highlight available positions highlight_available_spawn_points() else: # Clients request an update from the server rpc_id(1, "server_update_spawn_positions") # Add server-side spawn position update handler @rpc("any_peer", "reliable") func server_update_spawn_positions(): if not multiplayer.is_server(): return var sender_id = multiplayer.get_remote_sender_id() var occupied = get_occupied_positions() # Send the occupied positions back to the requesting client rpc_id(sender_id, "receive_spawn_positions_update", occupied) # Add client-side spawn position update receiver @rpc("authority", "reliable") func receive_spawn_positions_update(occupied_positions: Array): # Update local highlight state based on received occupied positions for pos in highlighted_spawn_points: if pos in occupied_positions: highlighted_spawn_points.erase(pos) if enhanced_gridmap: # Clear the highlight from Layer 2 (Overlay) instead of overwriting Floor 0 # PROTECTION: Never clear if it's a Safe Zone (ID 2) var current_l2 = enhanced_gridmap.get_cell_item(Vector3i(pos.x, 2, pos.y)) if current_l2 != 2: enhanced_gridmap.set_cell_item( Vector3i(pos.x, 2, pos.y), -1 ) # Now highlight available positions highlight_available_spawn_points() @rpc("any_peer", "call_local", "reliable") func sync_playerboard(new_playerboard: Array): """Sync playerboard data. Called by BotController or ActionManager.""" playerboard = new_playerboard.duplicate() # Only update UI if this is the LOCAL HUMAN PLAYER # Bots managed by server (ID 1) might sync here, but we must NOT update UI for them var is_local = name == str(multiplayer.get_unique_id()) var is_bot_check = is_bot or is_in_group("Bots") # DEBUG: Trace why UI updates might be happening # print("[sync_playerboard] Player: %s (ID: %s), LocalID: %s, IsLocal: %s, IsBot: %s" % [name, get_multiplayer_authority(), multiplayer.get_unique_id(), is_local, is_bot_check]) if is_local and not is_bot_check: var main = get_tree().get_root().get_node_or_null("Main") if main and main.ui_manager: main.ui_manager.update_playerboard_ui() elif is_local and is_bot_check: # This is a Bot running on the server (which is also the host) # We must NOT update the Host's UI with the Bot's data pass @rpc("any_peer", "call_local") func sync_bot_status(is_bot_status: bool): is_bot = is_bot_status if is_bot: add_to_group("Bots", true) set_process_input(false) set_process_unhandled_input(false) # Clear any existing highlights (if action_manager is initialized) if action_manager: action_manager.highlighted_cells.clear() # BotController already exists in scene and manages itself @rpc("any_peer", "call_local", "reliable") func sync_display_name(new_name: String) -> void: """Sync display name across network.""" _display_name = new_name if has_node("Name"): $Name.text = _display_name func _refresh_player_visuals(): var color_to_apply = Color.WHITE var alpha_to_apply = 1.0 if is_frozen: color_to_apply = Color.BLUE # Frozen (Staggered) elif is_stop_frozen: color_to_apply = Color.CYAN # Stop n Go Freeze elif is_slowed: color_to_apply = Color(0.6, 0.8, 1.0) # Slowed / Icy Blue elif is_charged_strike: color_to_apply = Color(1.0, 0.5, 0.5) # Charged Strike (Red Tint) elif is_carrying_tekton: color_to_apply = Color(1.0, 1.0, 0.0) # Carrying (Yellow) alpha_to_apply = 0.5 # 50% opacity when carrying Tekton elif immunity_timer > 0: color_to_apply = Color(0.5, 1.0, 0.5) # Immunity (Light Green) elif is_invisible: color_to_apply = Color.WHITE alpha_to_apply = 0.5 # Invisible (Semi-transparent) # Apply the determined color and alpha _apply_tint_recursive(self, color_to_apply, alpha_to_apply) # If returning to normal, _apply_tint_recursive wiped all material_overlays. # We must re-apply the cosmetics so "overlay" model skins (e.g. pants) return. if color_to_apply == Color.WHITE and alpha_to_apply == 1.0: var active_character: Node3D = null match _selected_character: "Bob": active_character = character_bob "Masbro": active_character = character_masbro "Gatot": active_character = character_gatot "Oldpop": active_character = character_oldpop if active_character: apply_loadout(active_character) func update_rank_visuals(rank: int, score: int = -1): var pos_label = get_node_or_null("Position") if not pos_label: return # Hide rank until the player has actually scored, so the match doesn't # start with everyone showing a position (e.g. all "1st"). if score == 0: pos_label.visible = false return if rank <= 4: pos_label.visible = true if race_manager: pos_label.text = race_manager.get_ordinal_string(rank) else: pos_label.text = str(rank) match rank: 1: pos_label.modulate = Color(1.0, 0.84, 0.0) # Gold 2: pos_label.modulate = Color(0.75, 0.75, 0.75) # Silver 3: pos_label.modulate = Color(0.8, 0.5, 0.2) # Bronze 4: pos_label.modulate = Color(0.5, 0.5, 0.5) # Grey else: pos_label.visible = false func _apply_tint_recursive(node: Node, color: Color, alpha: float = 1.0): if node is MeshInstance3D: var mat = StandardMaterial3D.new() mat.albedo_color = Color(color.r, color.g, color.b, alpha) mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA mat.blend_mode = BaseMaterial3D.BLEND_MODE_MIX mat.cull_mode = BaseMaterial3D.CULL_DISABLED mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED if color == Color.WHITE and alpha == 1.0: node.material_overlay = null else: node.material_overlay = mat for child in node.get_children(): _apply_tint_recursive(child, color, alpha) var immunity_timer: float = 0.0 var slow_timer: float = 0.0 var tekton_carry_timer: float = 0.0 const MAX_TEKTON_CARRY_TIME: float = 3.0 var charged_strike_timer: float = 0.0 const MAX_CHARGED_STRIKE_TIME: float = 5.0 @rpc("any_peer", "call_local") func apply_stagger(duration: float = 1.5): if is_carrying_tekton: return # Cannot be staggered while carrying a Tekton if immunity_timer > 0: return # Immune! if is_frozen: return # Already staggered is_frozen = true # Play knock VFX sequence on the receiver _play_knock_vfx() if anim_player and anim_player.has_animation("animation-pack/getting_hit_1"): anim_player.play("animation-pack/getting_hit_1") if anim_player.has_animation("animation-pack/stun_1"): anim_player.queue("animation-pack/stun_1") # Set immunity (3 seconds as requested) immunity_timer = 3.0 print("Player %s staggered for %.1f seconds" % [name, duration]) if is_multiplayer_authority(): NotificationManager.send_message(self , NotificationManager.MESSAGES.CRUSHED, NotificationManager.MessageType.WARNING) # Grant "Smashed" Bonus (1 bar, max 2) if powerup_manager: powerup_manager.acquire_smash_bonus() await get_tree().create_timer(duration).timeout is_frozen = false _refresh_player_visuals() play_idle_animation() func _play_knock_vfx() -> void: """Plays the three knock receiver VFX concurrently. Each hides itself once its animation finishes.""" play_skill_vfx("attack_mode_top") play_skill_vfx("attack_mode_bot") play_skill_vfx("receiver_skill_stunned") func set_stop_frozen(enabled: bool): self.is_stop_frozen = enabled if enabled: print("[STOP n GO] Player %s FROZEN until GO phase" % name) else: print("[STOP n GO] Player %s UNFROZEN" % name) @rpc("any_peer", "call_local", "reliable") func sync_stop_freeze(enabled: bool): # Security: Only allow server (peer 1) or local calls (peer 0) var sender = multiplayer.get_remote_sender_id() if sender != 1 and sender != 0: return set_stop_frozen(enabled) @rpc("any_peer", "call_local") func apply_slow_effect(duration: float = 3.0): # Update the timer (extend if already slowed) slow_timer = max(slow_timer, duration) self.is_slowed = true # Logic: Slow Movement speed if movement_manager: # Use 0.2 multipliers to match "slowed" request (20% speed) movement_manager.set_speed_multiplier(0.2) print("Player %s is slowed for %.1f seconds" % [name, duration]) @rpc("any_peer", "call_local") @rpc("any_peer", "call_local") func remove_slow_effect(): slow_timer = 0.0 self.is_slowed = false if movement_manager: # INSTANT response: restore speed multiplier to 1.0 immediately movement_manager.set_speed_multiplier(1.0) print("Player %s slow effect removed early" % name) func playerboard_is_empty() -> bool: for item in playerboard: if item != -1: return false return true func drop_random_item(): if playerboard_is_empty(): return # Find occupied slots var occupied_indices = [] for i in range(playerboard.size()): if playerboard[i] != -1: occupied_indices.append(i) if occupied_indices.size() == 0: return # Pick random slot var slot_index = occupied_indices.pick_random() var item_id = playerboard[slot_index] # Try to find empty spot on grid near player var drop_pos = _find_valid_drop_position() if drop_pos != Vector2i(-1, -1): # Drop it playerboard[slot_index] = -1 rpc("sync_playerboard", playerboard) SfxManager.play("tile_scatter") # Sync grid item var cell = Vector3i(drop_pos.x, 1, drop_pos.y) rpc("sync_grid_item", cell.x, cell.y, cell.z, item_id) NotificationManager.send_message(self , NotificationManager.MESSAGES.DROPPED_ITEM, NotificationManager.MessageType.WARNING) print("Player %s dropped item %d at %s" % [name, item_id, drop_pos]) @rpc("any_peer", "call_local") func drop_all_tiles(): """Drops all tiles from playerboard. Used by Super Push.""" var dropped_count = 0 for i in range(playerboard.size()): if playerboard[i] != -1: var item_id = playerboard[i] playerboard[i] = -1 # Find a spot to drop? Or just destroy? # User: "drop all tiles on playerboard" -> usually implies they scatter on floor # But scattering 25 tiles is chaotic. # Let's drop a few random ones and destroy rest? # Or per user "spawn nearby tiles into power up" -> Maybe the dropped tiles BECOME powerups? # User request: "victim drops all tiles... and spawn / replace your nearby tiles into power up" # I will just clear the board here. Spawning is handled by spawn_powerups_around. dropped_count += 1 if dropped_count > 0: rpc("sync_playerboard", playerboard) rpc("trigger_screen_shake", "targeted") SfxManager.play("tile_scatter") NotificationManager.send_message(self , NotificationManager.MESSAGES.CRITICALLY_HIT, NotificationManager.MessageType.WARNING) print("Player %s dropped %d tiles due to Super Push" % [name, dropped_count]) func _find_valid_drop_position() -> Vector2i: # Try random adjacent cells var neighbors = enhanced_gridmap.get_neighbors(current_position, 0) neighbors.shuffle() for neighbor in neighbors: var pos = neighbor.position # Check item layer var item_cell = Vector3i(pos.x, 1, pos.y) if enhanced_gridmap.get_cell_item(item_cell) == -1: if not is_position_occupied(pos): # Gauntlet Mode explicit overrides var gm = null var main_gauntlet = get_tree().root.get_node_or_null("Main") if main_gauntlet and main_gauntlet.get("gauntlet_manager"): gm = main_gauntlet.gauntlet_manager if gm and gm.is_active: if pos.x == 0 or pos.x == gm.ARENA_COLUMNS - 1 or pos.y == 0 or pos.y == gm.ARENA_ROWS - 1: continue if gm._is_npc_zone(pos): continue return pos return Vector2i(-1, -1) @rpc("any_peer", "call_local") func on_stop_phase_violation(): """Moving during STOP phase makes you lose and scatter tiles.""" if not multiplayer.is_server(): return if is_stop_frozen: return # Already penalized for this phase print("[STOP n GO] Violation by player %s! Scattering tiles." % name) # New Indefinite Freeze until phase ends rpc("sync_stop_freeze", true) # Scatter only 3 random items (User request) var occupied_indices = [] for i in range(playerboard.size()): if playerboard[i] != -1: occupied_indices.append(i) if occupied_indices.is_empty(): return occupied_indices.shuffle() var scatter_count = min(occupied_indices.size(), 3) var items_to_scatter = [] for i in range(scatter_count): var idx = occupied_indices[i] items_to_scatter.append(playerboard[idx]) playerboard[idx] = -1 rpc("sync_playerboard", playerboard) # Find multiple valid drop positions around the player var drop_positions = _find_multiple_drop_positions(items_to_scatter.size()) for i in range(items_to_scatter.size()): var item_id = items_to_scatter[i] var pos = drop_positions[i] if i < drop_positions.size() else _find_valid_drop_position() if pos != Vector2i(-1, -1): var cell = Vector3i(pos.x, 1, pos.y) # MUST call sync_grid_item on Main, not Player! var main = get_tree().get_root().get_node_or_null("Main") if main: main.rpc("sync_grid_item", cell.x, cell.y, cell.z, item_id) SfxManager.rpc("play_rpc", "tile_scatter") NotificationManager.send_message(self , "STOP VIOLATION! Tiles scattered!", NotificationManager.MessageType.WARNING) func _find_multiple_drop_positions(count: int) -> Array: var positions = [] var neighbors = enhanced_gridmap.get_neighbors(current_position, 0) neighbors.shuffle() # Also consider neighbors of neighbors (radius 2) for more scattering var candidates = [] for n in neighbors: candidates.append(n.position) var n2 = enhanced_gridmap.get_neighbors(n.position, 0) for nn in n2: if not nn.position in candidates: candidates.append(nn.position) candidates.shuffle() for pos in candidates: if positions.size() >= count: break var item_cell = Vector3i(pos.x, 1, pos.y) if enhanced_gridmap.get_cell_item(item_cell) == -1: if not is_position_occupied(pos): positions.append(pos) return positions # ============================================================================= # Targeting Action # ============================================================================= func attempt_target_action(target_index: int): # 1. Get Selected Effect from UI var main = get_tree().get_root().get_node_or_null("Main") if not main or not main.ui_manager: return # Quick check if UI exists and has a selection # We need to access the script variable 'selected_effect' from the dynamically created/loaded UI. # Let's assume ui_manager has a reference or we find it. # Based on previous step, we haven't integrated PowerUpInventoryUI into UIManager yet. # So we might fail here if not wired up. # For now, let's look for "PowerUpInventoryUI" in CanvasLayer. var inventory_ui = main.ui_manager.get_node_or_null("PowerUpInventoryUI") # Or check if ui_manager tracks it. # Note: We haven't instantiated it yet in UIManager. We will need to do that. if not inventory_ui or inventory_ui.selected_effect == -1: return # No effect selected using mouse/touch first var effect = inventory_ui.selected_effect # 2. Find Target Player var player_manager = main.get_node_or_null("PlayerManager") if not player_manager: return if target_index < 0 or target_index >= player_manager.connected_peer_ids.size(): return var target_id = player_manager.connected_peer_ids[target_index] var target_player = main.get_node_or_null(str(target_id)) if not target_player: return if target_player == self and effect != 4: # 4 = INVISIBLE (Self) # Trying to target self with harmful effect? NotificationManager.send_message(self , NotificationManager.MESSAGES.CANT_TARGET_SELF, NotificationManager.MessageType.WARNING) return # 3. Activate Effect var st_manager = get_node_or_null("SpecialTilesManager") if st_manager: st_manager.activate_effect(effect, target_player) inventory_ui.deselect() func activate_powerup(effect_id: int): if is_carrying_tekton or is_charged_strike: NotificationManager.send_message(self, "Cannot use Power-Up right now!", NotificationManager.MessageType.WARNING) return var main = get_tree().get_root().get_node_or_null("Main") if not main or not main.ui_manager: return # Try to find the UI button directly if possible, or simulate the click # The goal is to Select it (if it requires targeting) OR Activate it (if instant) # Since PowerUpInventoryUI manages selection state, we should route through it if possible # or directly tell SpecialTilesManager to prepare? # Let's try to mimic the button press var inventory_ui = main.ui_manager.get_node_or_null("PowerUpInventoryUI") # Or wherever it lives if not inventory_ui: # Fallback: Find it in scene inventory_ui = main.get_node_or_null("PowerUpInventoryUI") if inventory_ui: # Inventory UI handles: "activate_effect(effect_id)" on click # Which then calls SpecialTilesManager.activate_effect # This handles both "Instant" effects (Speed) and "Targeting" effects (Wall) inventory_ui._on_btn_pressed(effect_id) else: # Fallback if UI not found var st_manager = get_node_or_null("SpecialTilesManager") if st_manager: st_manager.activate_effect(effect_id) func activate_held_powerup(): """Finds whichever powerup is currently held and activates it.""" if is_carrying_tekton or is_charged_strike: NotificationManager.send_message(self, "Cannot use Power-Up right now!", NotificationManager.MessageType.WARNING) return var active_effect = -1 if special_tiles_manager: for effect_key in special_tiles_manager.inventory: if special_tiles_manager.inventory[effect_key]: active_effect = effect_key break if active_effect != -1: activate_powerup(active_effect) else: print("[Player] No powerup currently held to activate.") func _process(delta): # Failsafe: Ensure player is visible if spawn point is selected and random spawn is active # This handles race conditions where set_spawn_position might be called before _ready finishes hiding if LobbyManager.get_randomize_spawn() and spawn_point_selected and not visible: visible = true if not multiplayer.has_multiplayer_peer(): return if is_multiplayer_authority(): # Visual debugging - show display name with connection status $Name.text = display_name if not display_name.is_empty() else str(name) # Periodically verify our existence to others _verify_timer += delta if _verify_timer >= 3.0: _verify_timer = 0.0 if can_rpc(): rpc("ping_existence") else: # Client-side visual smoothing with snapshot interpolation # Only interpolate if NOT running a movement tween if not is_player_moving: _process_remote_interpolation(delta) # Delegate rotation to movement manager if movement_manager: movement_manager._process(delta) # Charged Strike Expiration Timer if is_multiplayer_authority() and is_charged_strike: if charged_strike_timer > 0: charged_strike_timer -= delta if charged_strike_timer <= 0: charged_strike_timer = 0.0 is_charged_strike = false NotificationManager.send_message(self, "Charged Strike Expired!", NotificationManager.MessageType.WARNING) if powerup_manager: powerup_manager.reset_boost() # Immunity Timer Logic if immunity_timer > 0: immunity_timer -= delta if immunity_timer <= 0: immunity_timer = 0 _refresh_player_visuals() # Slow Timer Logic if slow_timer > 0: slow_timer -= delta if slow_timer <= 0: slow_timer = 0.0 self.is_slowed = false if movement_manager: movement_manager.set_speed_multiplier(1.0) func _process_remote_interpolation(_delta): if snapshot_buffer.size() < 2: # Fallback to simple lerp if not enough snapshots # Keep this very soft to smooth out transitions between tween and interpolation if global_position.distance_squared_to(target_visual_position) > 0.001: global_position = global_position.lerp(target_visual_position, _delta * 10.0) return var render_time = Time.get_ticks_msec() - INTERPOLATION_OFFSET # Find the two snapshots to interpolate between var older = snapshot_buffer[0] var newer = null for i in range(1, snapshot_buffer.size()): if snapshot_buffer[i].time > render_time: newer = snapshot_buffer[i] older = snapshot_buffer[i - 1] break if newer: # Interpolate var total_time = newer.time - older.time var elapsed_time = render_time - older.time var t = float(elapsed_time) / float(total_time) var target_pos = older.pos.lerp(newer.pos, t) # If drift is massive (teleport), snap var dist_sq = global_position.distance_squared_to(target_pos) if dist_sq > 16.0: global_position = target_pos elif dist_sq > 0.0001: # Use a lower lerp weight for much softer tracking global_position = global_position.lerp(target_pos, _delta * 30.0) else: # Extrapolate or just stay at latest if render_time is ahead of buffer var latest = snapshot_buffer[-1] if global_position.distance_squared_to(latest.pos) > 0.001: global_position = global_position.lerp(latest.pos, _delta * 20.0) # Slower catchup to latest @rpc("any_peer", "call_local") func ping_existence(): # This just lets other clients know this player exists # They can check if they have this node pass var last_sent_position: Vector3 func _physics_process(delta): # Sync position periodically (Heartbeat / Smoothing) if not multiplayer.has_multiplayer_peer(): return if is_multiplayer_authority(): # OPTIMIZATION: Only send smoothing updates if we ARE NOT currently mid-tween # The start/end of paths are already synced via start_movement_along_path. # Sending packets during a tween just adds noise/jitter for the client. if not is_player_moving: var current_world_pos = global_position var last_sent_pos = get_meta("_last_sent_pos", Vector3.ZERO) # Use a slightly larger threshold (0.05) to ignore micro-vibrations if current_world_pos.distance_to(last_sent_pos) > 0.05: set_meta("_last_sent_pos", current_world_pos) if can_rpc(): rpc("remote_set_position", current_world_pos, Time.get_ticks_msec()) # Tekton Auto-Reward Timer (3s Rule) if is_multiplayer_authority() and is_carrying_tekton: tekton_carry_timer += delta if tekton_carry_timer >= MAX_TEKTON_CARRY_TIME: tekton_carry_timer = 0.0 print("[Player %s] 3-second rule: Auto-spawning reward tiles" % name) if powerup_manager and powerup_manager.has_method("spawn_boost_reward"): powerup_manager.spawn_boost_reward() else: drop_tekton() elif not is_carrying_tekton: tekton_carry_timer = 0.0 # NOTE: Finish line checking removed - game uses cycle-based goals system now # -------------------------------------------------------------------- # Input # -------------------------------------------------------------------- func _unhandled_input(event): if input_manager: input_manager.handle_unhandled_input(event) func _on_slot_gui_input(event, slot_index, slot_ui) -> int: if input_manager: return input_manager.handle_slot_gui_input(event, slot_index, slot_ui) return -1 func handle_grid_click(grid_position: Vector2i): if is_frozen or is_stop_frozen: return if input_manager: input_manager.handle_grid_click(grid_position) # Modify is_position_occupied to check for selected spawn points func is_position_occupied(pos: Vector2i) -> bool: for p in get_tree().get_nodes_in_group("Players"): if p == self: continue # Check if player has selected a spawn point OR is already visible (active in match) if (p.spawn_point_selected or p.visible) and p.current_position == pos: return true # Check target position (where they are moving to) if p.is_player_moving and p.target_position == pos: return true # Prevent overlap with Static Tekton Stands (Exactly the 3x3 area) using the actual spawned nodes for stand in get_tree().get_nodes_in_group("StaticTektonStands"): var local_pos = enhanced_gridmap.to_local(stand.global_position) var stand_map_pos = enhanced_gridmap.local_to_map(local_pos) if abs(pos.x - stand_map_pos.x) <= 1 and abs(pos.y - stand_map_pos.z) <= 1: return true return false func find_valid_starting_position() -> Vector2i: if is_bot: return _find_random_spawn_position() else: # For Stop n Go, use Column 0 if LobbyManager.game_mode == "Stop n Go": for spawn_pos in spawn_locations: if not is_position_occupied(spawn_pos): return spawn_pos # For Freemode, try corners if random spawn is OFF, or just find any walkable # But wait, host will assign most of the time. This is just for initial _ready. return Vector2i(1, 1) # Default away from the very edge if possible # highlight_available_spawn_points is no longer needed for manual selection in this mode func highlight_available_spawn_points(): pass # Add function to get all occupied positions func get_occupied_positions() -> Array: var occupied = [] for player in get_tree().get_nodes_in_group("Players"): if player.spawn_point_selected: # Only count players who have selected a spawn point occupied.append(player.current_position) return occupied # Helper to find which player is at a specific position func get_player_at_position(pos: Vector2i) -> Node3D: for player in get_tree().get_nodes_in_group("Players"): if player == self: continue # Check current position if player.current_position == pos: return player # Check target position if moving if player.is_player_moving and player.target_position == pos: return player return null # Modify the select_spawn_point function to notify other clients func select_spawn_point(spawn_pos: Vector2i) -> bool: if not is_multiplayer_authority() or is_bot or spawn_point_selected: return false if spawn_pos in highlighted_spawn_points and not is_position_occupied(spawn_pos): current_position = spawn_pos spawn_point_selected = true # Update position in the world position = grid_to_world(spawn_pos) # Notify all clients about the spawn selection rpc("notify_spawn_selected", spawn_pos) # Clear highlights locally clear_spawn_highlights() # Sync position with other clients if is_multiplayer_authority(): rpc("sync_position", current_position) return true return false func clear_spawn_highlights(): # Clear the highlighted spawn points array for spawn_pos in highlighted_spawn_points: if enhanced_gridmap: # Clear Layer 2 (Overlay Highlight) instead of potentially overwriting Layer 0 enhanced_gridmap.set_cell_item( Vector3i(spawn_pos.x, 2, spawn_pos.y), -1 ) # Clear the array highlighted_spawn_points.clear() # Force an update of the grid visualization if enhanced_gridmap: enhanced_gridmap._update_cell_option_buttons() func _find_random_spawn_position() -> Vector2i: if not enhanced_gridmap: print("Warning: No gridmap for random spawn") return Vector2i.ZERO # Special handling for Stop n Go mode (22x10 Grid) if LobbyManager.game_mode == "Stop n Go": var available_positions = [] # Scan the 22x10 grid for x in range(22): for z in range(10): var pos = Vector2i(x, z) # Check if position is walkable (not a wall/obstacle) # We check Floor 0 item. Assuming walls are identifiable. # In setup_arena, walls are TILE_OBSTACLE (4). # We should check if it is NOT TILE_OBSTACLE. var item = enhanced_gridmap.get_cell_item(Vector3i(x, 0, z)) # Assuming 4 is obstacle, and -1 is void. 0 is walkable, 2 is safe zone. if item != -1 and item != 4: if not is_position_occupied(pos): available_positions.append(pos) if available_positions.size() > 0: var rng = RandomNumberGenerator.new() rng.randomize() return available_positions[rng.randi() % available_positions.size()] return Vector2i(10, 5) # Fallback center var available_positions = [] # Scan the grid for valid walkable floor tiles that are not occupied var cols = enhanced_gridmap.columns if "columns" in enhanced_gridmap else 14 var rs = enhanced_gridmap.rows if "rows" in enhanced_gridmap else 14 for x in range(cols): for z in range(rs): var pos = Vector2i(x, z) # Check Floor 0 for walkable ground (Not a wall/obstacle) var ground_item = enhanced_gridmap.get_cell_item(Vector3i(x, 0, z)) var is_walkable = ground_item != -1 and not ground_item in enhanced_gridmap.non_walkable_items if is_walkable: # Check if position is occupied by another player if not is_position_occupied(pos): available_positions.append(pos) if available_positions.size() > 0: var rng = RandomNumberGenerator.new() rng.randomize() return available_positions[rng.randi() % available_positions.size()] # Better fallback center instead of 0,0 which is often a wall/border print("[Player] Warning: No available spawn positions found! Using fallback.") return Vector2i(cols / 2, rs / 2) func find_random_valid_position_in_range() -> Vector2i: var rng = RandomNumberGenerator.new() rng.randomize() var valid_positions = [] for x in range(max(0, current_position.x - movement_range), min(enhanced_gridmap.columns, current_position.x + movement_range + 1)): for z in range(max(0, current_position.y - movement_range), min(enhanced_gridmap.rows, current_position.y + movement_range + 1)): var pos = Vector2i(x, z) if pos != current_position and is_within_movement_range(pos): var cell_item = enhanced_gridmap.get_cell_item(Vector3i(x, 0, z)) if cell_item != -1 and not (cell_item in enhanced_gridmap.non_walkable_items) and not is_position_occupied(pos): valid_positions.append(pos) if valid_positions.size() > 0: return valid_positions[rng.randi() % valid_positions.size()] return current_position func raycast_to_grid(from: Vector3, to: Vector3) -> Vector2i: var plane = Plane(Vector3.UP, cell_offset.y) var intersection = plane.intersects_ray(from, to - from) if intersection: var adjusted_intersection = intersection - cell_offset var grid_position = Vector2i( floor(adjusted_intersection.x / cell_size.x), floor(adjusted_intersection.z / cell_size.z) ) if grid_position.x >= 0 and grid_position.x < enhanced_gridmap.columns and \ grid_position.y >= 0 and grid_position.y < enhanced_gridmap.rows: return grid_position return Vector2i(-1, -1) func is_within_movement_range(target_position: Vector2i) -> bool: return movement_manager.is_within_movement_range(target_position) # ----------------------------------------------------------------- # Movement # ----------------------------------------------------------------- func simple_move_to(grid_position: Vector2i): movement_manager.simple_move_to(grid_position) func move_player_to_clicked_position(grid_position: Vector2i): movement_manager.move_to_clicked_position(grid_position) @rpc("any_peer", "call_remote", "reliable") func start_movement_along_path(path: Array, clear_visual: bool = true, force: bool = false): if is_player_moving and not force: return # ALREADY MOVING. Guard against redundant RPCs or interruptions unless forced. if force and movement_manager: movement_manager.movement_queue.clear() movement_manager.current_move_direction = Vector2i.ZERO print("[Player] %s starting move along path: %s (Forced: %s)" % [name, path, force]) # SERVER-SIDE VIOLATION CHECK (for Stop n Go) if multiplayer.is_server() and LobbyManager.game_mode == "Stop n Go": var main = get_tree().root.get_node_or_null("Main") if main: var sng_manager = main.get_node_or_null("StopNGoManager") if sng_manager and sng_manager.has_method("check_movement_violation"): var target_pos = Vector2i(path[0].x, path[0].y) if path.size() > 0 else current_position sng_manager.check_movement_violation(name.to_int(), current_position, target_pos) is_player_moving = true if path.size() > 0: target_position = Vector2i(path[-1].x, path[-1].y) # RELAXED SNAP START: Only snap if the visual node is far from where it should be (> 0.5 units) # This prevents "twitching" when a move starts if the node was still lerping slowly to its final spot. var start_world_pos = grid_to_world(current_position) if global_position.distance_to(start_world_pos) > 0.5: global_position = start_world_pos if _movement_tween: _movement_tween.kill() _movement_tween = create_tween() _movement_tween.set_trans(Tween.TRANS_LINEAR) _movement_tween.set_ease(Tween.EASE_IN_OUT) var step_duration = 0.25 if movement_manager: step_duration = step_duration / movement_manager.speed_multiplier for point in path: # Use global_position for consistency _movement_tween.tween_property(self , "global_position", grid_to_world(Vector2i(point.x, point.y)), step_duration) _movement_tween.tween_callback(func(): var old_pos = current_position current_position = Vector2i(path[-1].x, path[-1].y) is_player_moving = false _movement_tween = null target_position = Vector2i(-1, -1) _last_movement_finish_time = Time.get_ticks_msec() print("[Player] %s finished move. %s -> %s" % [name, old_pos, current_position]) if is_carrying_tekton and is_instance_valid(carried_tekton): carried_tekton.current_position = current_position # Stop n Go Win Check if LobbyManager.game_mode == "Stop n Go": var sng_main = get_tree().root.get_node_or_null("Main") if sng_main: var sng_manager = sng_main.get_node_or_null("StopNGoManager") if sng_manager and sng_manager.has_method("check_win_condition"): if sng_manager.check_win_condition(name.to_int(), current_position): sng_main.rpc("sync_game_end_stop_n_go", name.to_int()) # Tekton Doors Win Check elif LobbyManager.game_mode == "Tekton Doors": var main_node = get_tree().root.get_node_or_null("Main") if main_node and main_node.portal_mode_manager: if main_node.portal_mode_manager.check_win_condition(name.to_int(), current_position): main_node.rpc("sync_game_end_portal_mode", name.to_int()) # FORCE SNAP: Update target visual position to the perfect grid center # This ensures that when interpolation resumes (in _process), it pulls to the correct spot target_visual_position = grid_to_world(current_position) # Racing Win Check (Skipped in Stop n Go which uses its own block above) if LobbyManager.game_mode != "Stop n Go": var current_finish_locs = race_manager.get_current_finish_locations() if race_manager else finish_locations if current_position in current_finish_locs and can_finish: finish_race() var main = get_tree().get_root().get_node_or_null("Main") # Clear visuals for everyone including bots if clear_visual: if enhanced_gridmap: enhanced_gridmap.clear_path_visualization() # Reset interpolation buffer to prevent "jumping back" 150ms after tween ends snapshot_buffer.clear() target_visual_position = grid_to_world(current_position) has_moved_this_turn = path.size() <= movement_range if TurnManager.turn_based_mode: end_turn() _after_action_completed() if movement_manager and movement_manager.has_method("_on_movement_finished"): movement_manager.call_deferred("_on_movement_finished") ) #func trigger_finish_line(): #if not is_multiplayer_authority(): #return # #if current_lap == 0: # First lap #lap1_finishers += 1 #race_position = lap1_finishers # ## Display first lap completion message #var message = "Finish 1st lap on " + get_ordinal_string(race_position) #rpc("display_message", message) #print("DEBUG: Triggered first lap finish. Position: ", race_position) # ## Start second lap #current_lap += 1 #rpc("start_new_lap") # #elif current_lap == 1: # Second lap #lap2_finishers += 1 #race_position = lap2_finishers # ## Display second lap completion message #var message = "Finish 2nd lap on " + get_ordinal_string(race_position) #rpc("display_message", message) #print("DEBUG: Triggered second lap finish. Position: ", race_position) # ##func debug_finish_state(): ##print("DEBUG: Current Position: ", current_position) ##print("DEBUG: Can Finish: ", can_finish) ##print("DEBUG: Current Lap: ", current_lap) ##print("DEBUG: Pattern Match: ", check_pattern_match()) ##print("DEBUG: Is at finish: ", current_position in finish_locations) func update_player_position(grid_position: Vector2i): position = grid_to_world(grid_position) emit_signal("position_changed") func grid_to_world(grid_position: Vector2i) -> Vector3: var world_position = Vector3( grid_position.x * cell_size.x + cell_size.x * 0.5, cell_size.y, grid_position.y * cell_size.z + cell_size.z * 0.5 ) + cell_offset return world_position func start_turn(): has_moved_this_turn = false has_performed_action = false is_my_turn = true if is_multiplayer_authority(): # rpc("display_message", "It's your turn!") # Handled by setter _after_action_completed() func end_turn(): is_my_turn = false has_moved_this_turn = false if is_multiplayer_authority(): get_tree().get_root().get_node_or_null("Main").request_next_turn() func reset_race(): if race_manager: race_manager.current_lap = 0 race_manager.race_position = 0 race_manager.can_finish = false race_manager.goals = race_manager.first_lap_goals.duplicate() race_manager.playerboard.fill(-1) if is_multiplayer_authority(): rpc("sync_goals", race_manager.goals) rpc("sync_playerboard", race_manager.playerboard) # Add a static reset for new games static func reset_race_stats(): var race_mgr = load("res://scripts/managers/player_race_manager.gd") if race_mgr: race_mgr.lap1_finishers = 0 race_mgr.lap2_finishers = 0 @rpc("any_peer", "call_remote", "unreliable") func remote_set_position(authority_position: Vector3, timestamp: int = -1): if timestamp == -1: timestamp = Time.get_ticks_msec() # DISCARD STALE PACKETS: # 1. If we've already seen a newer packet if timestamp <= _last_received_timestamp: return # 2. If this packet was sent before we finished our last authoritative movement step # (Preventing "past" packets from overriding the "present" destination) if timestamp <= _last_movement_finish_time: return _last_received_timestamp = timestamp # Add to snapshot buffer snapshot_buffer.append({"time": timestamp, "pos": authority_position}) # Ensure chronological order (in case of network jitter/reordering) snapshot_buffer.sort_custom(func(a, b): return a.time < b.time) # Keep buffer size manageable if snapshot_buffer.size() > 30: snapshot_buffer.pop_front() # Update target visual position as fallback for simpler lerping target_visual_position = authority_position @rpc("any_peer", "call_local") func display_message(message, type: int = 0): # Send message to the main scene's message bar instead of player bubble var main = get_tree().get_root().get_node_or_null("Main") if main and main.has_method("add_message_to_bar"): var player_name_str = display_name if not display_name.is_empty() else str(name) main.add_message_to_bar(player_name_str, message, type) func initialize_random_goals(_size: int, min_value: int, max_value: int, null_count: float) -> Array[int]: goals.clear() var rng = RandomNumberGenerator.new() rng.randomize() var result: Array[int] = [] var null_val = 0 var max_nulls = 3 const SPECIAL_VALUES = {1: 7, 2: 8, 3: 9, 4: 10} for i in range(_size): if null_val < max_nulls and rng.randf() < null_count: result.append(-1) null_val += 1 else: var val = rng.randi_range(min_value, max_value) result.append(val if not val in SPECIAL_VALUES else SPECIAL_VALUES[val]) return result # Remove this since goals are now set by main.gd func append_random_goals(): goals.append_array(initialize_random_goals(9, 7, 10, 1.0)) if is_multiplayer_authority(): rpc("sync_goals", goals) func bot_try_grab_item() -> bool: return playerboard_manager.bot_try_grab_item() # ----------------------------------------------------------------- # OLD GRAB Func # ----------------------------------------------------------------- #func grab_item(grid_position: Vector2i = current_position) -> bool: #if is_bot: #return bot_try_grab_item() # #if not enhanced_gridmap or action_points <= 0: #return false # #var cell = Vector3i(grid_position.x, 1, grid_position.y) #var item = enhanced_gridmap.get_cell_item(cell) # #if grid_position != current_position: #var neighbors = enhanced_gridmap.get_neighbors(current_position, 0) #var is_adjacent = false #for neighbor in neighbors: #if neighbor.position == grid_position: #is_adjacent = true #break #if not is_adjacent: #return false # #if item == -1: #return false # ## Bot-specific grab logic moved to bot_grab_item RPC #if is_in_group("Bots") or is_bot: #var empty_slot = playerboard.find(-1) #if empty_slot == -1: #return false # #if is_multiplayer_authority(): #rpc("bot_grab_item", grid_position, empty_slot, cell.x, cell.y, cell.z) #return true # #var main = get_tree().get_root().get_node_or_null("Main") #if main: #selected_gridmap_position = grid_position #clear_highlights() #clear_playerboard_highlights() # #for i in range(playerboard.size()): #if playerboard[i] == -1: #var slot = main.playerboard_ui.get_child(i) #if slot.get_child_count() > 0: #slot.get_child(0).show() #highlighted_cells.append(i) #return true # #return false # ----------------------------------------------------------------- #func grab_item(grid_position: Vector2i = current_position) -> bool: #if not enhanced_gridmap or action_points <= 0: #return false # #var cell = Vector3i(grid_position.x, 1, grid_position.y) #var item = enhanced_gridmap.get_cell_item(cell) # ## Validate adjacency (unless it's current position) #if grid_position != current_position: #var neighbors = enhanced_gridmap.get_neighbors(current_position, 0) #var is_adjacent = false #for neighbor in neighbors: #if neighbor.position == grid_position: #is_adjacent = true #break #if not is_adjacent: #return false # #if item == -1: #return false # ## === AUTO-ARRANGE LOGIC === #var target_slot = find_best_goal_slot_for_item(item) #if target_slot == -1: #return false # no space # ## Perform the grab and auto-place #if is_multiplayer_authority(): ## Update gridmap: remove item #rpc("sync_grid_item", cell.x, cell.y, cell.z, -1) ## Update playerboard #playerboard[target_slot] = item #rpc("sync_playerboard", playerboard) ## Consume action #has_performed_action = true #consume_action_points(1) # ## Optional: visual feedback #var main = get_tree().get_root().get_node_or_null("Main") #if main: #main.update_playerboard_ui() #main.set_action_state(main.ActionState.NONE) # #return true # ----------------------------------------------------------------- func grab_item(grid_position: Vector2i = current_position) -> bool: return playerboard_manager.grab_item(grid_position) # ----------------------------------------------------------------- # Execute Grab # ----------------------------------------------------------------- func _execute_grab(grid_pos: Vector2i, cell: Vector3i, item_id: int): return playerboard_manager._execute_grab(grid_pos, cell, item_id) # ----------------------------------------------------------------- # This function runs on the server when requested by a client # ----------------------------------------------------------------- @rpc("any_peer", "reliable") func request_server_grab(grid_pos: Vector2i, x: int, y: int, z: int, item_id: int, expected_slot: int = -1): # 1. Only the server (peer 1) should process this if not multiplayer.is_server(): return # 2. Security check: Did this request come from the actual owner of this node? if multiplayer.get_remote_sender_id() != get_multiplayer_authority(): push_error("Security: Non-authority tried to grab item!") return # 3. Call the execution logic (pass expected_slot for deterministic placement) playerboard_manager._execute_grab(grid_pos, Vector3i(x, y, z), item_id, expected_slot) # ----------------------------------------------------------------- # Auto-put: no manual selection needed # Automatically puts a goal-matching tile into an adjacent (or current) empty grid cell # ----------------------------------------------------------------- # ----------------------------------------------------------------- # Auto-put: no manual selection needed # Automatically puts a goal-matching tile into an adjacent (or current) empty grid cell # ----------------------------------------------------------------- func auto_put_item() -> bool: return playerboard_manager.auto_put_item() # ----------------------------------------------------------------- # Force ActionState : None # ----------------------------------------------------------------- @rpc("any_peer", "call_local", "reliable") func force_action_state_none(): # This is called by the server on the client to reset the UI if is_bot or is_in_group("Bots"): return clear_highlights() clear_playerboard_highlights() # ----------------------------------------------------------------- @rpc("any_peer", "reliable") func request_server_put(grid_position: Vector2i, slot_index: int, x: int, y: int, z: int, item: int): # This RPC should only be processed by the server if not multiplayer.is_server(): return # Verify that this request came from the authority of this player if multiplayer.get_remote_sender_id() != get_multiplayer_authority(): push_error("Security: Non-authority tried to put item!") return # Server-side validation var cell = Vector3i(x, y, z) if enhanced_gridmap.get_cell_item(cell) != -1: return # Cell not empty # Check if position is adjacent or current position if grid_position != current_position: var is_adjacent = false var neighbors = enhanced_gridmap.get_neighbors(current_position, 0) for neighbor in neighbors: if neighbor.position == grid_position: is_adjacent = true break if not is_adjacent: return # Not adjacent # Verify player has the item if playerboard[slot_index] != item: push_error("Item mismatch! Player doesn't have claimed item") return # Perform the put operation as the server rpc("sync_grid_item", x, y, z, item) playerboard[slot_index] = -1 rpc("sync_playerboard", playerboard) # Update player state has_performed_action = true selected_playerboard_slot = -1 # Notify about action completion _after_action_completed() # Add new RPC function to notify others about spawn selection @rpc("any_peer", "reliable") func notify_spawn_selected(spawn_pos: Vector2i): # Mark as selected on all peers so occupancy checks work spawn_point_selected = true # Update local highlight state for all clients if spawn_pos in highlighted_spawn_points: highlighted_spawn_points.erase(spawn_pos) # Clear highlight for the selected position on Layer 2 (Overlay) if enhanced_gridmap: enhanced_gridmap.set_cell_item( Vector3i(spawn_pos.x, 2, spawn_pos.y), -1 ) # Disabled, auto put activated #func handle_put_action(): #var main = get_tree().get_root().get_node_or_null("Main") #if not main or action_points < 1: #return # #if not is_bot == true: #clear_highlights() #clear_playerboard_highlights() # ## Highlight non-empty slots in playerboard #for i in range(playerboard.size()): #if playerboard[i] != -1: # Highlight occupied slots #var slot = main.playerboard_ui.get_child(i) #if slot.get_child_count() > 0: #slot.get_child(0).show() # Show highlight for occupied slots #highlighted_cells.append(i) func handle_playerboard_slot_selected(slot_index: int): playerboard_manager.handle_playerboard_slot_selected(slot_index) # We also need to add handle_put_slot_selected: func handle_put_slot_selected(slot_index: int): playerboard_manager.handle_put_slot_selected(slot_index) func arrange_playerboard_item(slot_index: int): playerboard_manager.arrange_playerboard_item(slot_index) func _on_slot_clicked(event: InputEvent, slot_index: int): if not event is InputEventMouseButton or is_bot == true or not event.pressed or event.button_index != MOUSE_BUTTON_LEFT: return playerboard_manager.handle_slot_clicked(slot_index) func has_item_at_current_position() -> bool: var current_cell = Vector3i(current_position.x, 1, current_position.y) return enhanced_gridmap.get_cell_item(current_cell) != -1 func has_items_in_playerboard() -> bool: return playerboard.any(func(item): return item != -1) func playerboard_is_full() -> bool: return playerboard.find(-1) == -1 func highlight_cells_if_authorized(cells_to_highlight: Array, item_id: int = -1): action_manager.highlight_cells_if_authorized(cells_to_highlight, item_id) # Update highlight_movement_range to respect the expanded obstacle blocking func highlight_movement_range(): movement_manager.highlight_movement_range() # Helper function to check if a cell can be reached given the blocked cells # Helper function to check if a direction is diagonal func highlight_adjacent_cells(): movement_manager.highlight_adjacent_cells() func highlight_empty_adjacent_cells(): action_manager.highlight_empty_adjacent_cells() func highlight_random_valid_cells(): action_manager.highlight_random_valid_cells() func highlight_occupied_playerboard_slots(): action_manager.highlight_occupied_playerboard_slots() func clear_highlights(): if action_manager: action_manager.clear_highlights() func clear_playerboard_highlights(): if action_manager: action_manager.clear_playerboard_highlights() func rotate_towards_target(target_pos: Vector2i): movement_manager.rotate_towards_target(target_pos) # We also need to add these supporting functions: func select_playerboard_slot(slot_index: int): playerboard_manager.select_playerboard_slot(slot_index) func deselect_playerboard_slot(): playerboard_manager.deselect_playerboard_slot() func target_playerboard_slot(slot_index: int): playerboard_manager.target_playerboard_slot(slot_index) func untarget_playerboard_slot(): playerboard_manager.untarget_playerboard_slot() func can_move_to_target_playerboard_slot() -> bool: return playerboard_manager.can_move_to_target_playerboard_slot() func _update_playerboard_slot_visual(slot_index: int): playerboard_manager._update_playerboard_slot_visual(slot_index) func _highlight_adjacent_playerboard_slots(): playerboard_manager._highlight_adjacent_playerboard_slots() @rpc("any_peer", "call_local", "reliable") func sync_rotation(new_rotation: float): # Apply rotation if we are NOT the authority (syncing others) # OR if the server (ID 1) is forcing a rotation (start of match) var sender_id = multiplayer.get_remote_sender_id() if not is_multiplayer_authority() or sender_id == 1: rotation.y = new_rotation if movement_manager: movement_manager.target_rotation = new_rotation @rpc("any_peer", "call_local", "reliable") func sync_grid_item(x: int, y: int, z: int, item: int): if enhanced_gridmap: var cell = Vector3i(x, y, z) # Log the change for debugging print("Setting grid item at ", cell, " to ", item, " (called by ", multiplayer.get_remote_sender_id(), ")") # Make sure we set the cell reliably enhanced_gridmap.set_cell_item(cell, item) # Double-check the cell was set var check_value = enhanced_gridmap.get_cell_item(cell) if check_value != item: push_warning("Cell item didn't update correctly! Expected " + str(item) + " but got " + str(check_value)) # Try once more enhanced_gridmap.set_cell_item(cell, item) @rpc("any_peer", "call_local") func sync_goals(new_goals: Array): goals = new_goals.duplicate() # Make sure to duplicate the array # Also update race_manager's goals directly if race_manager: race_manager.goals = new_goals.duplicate() # Re-check finish availability with new goals race_manager.update_finish_availability() @rpc("any_peer", "call_local") func sync_second_lap_goals(new_goals: Array): if race_manager: race_manager.second_lap_goals = new_goals.duplicate() func _after_action_completed(): action_manager.after_action_completed() func is_finish_position(pos: Vector2i) -> bool: var current_finish = race_manager.get_current_finish_locations() if race_manager else finish_locations return pos in current_finish func consume_action_points(points: int): action_manager.consume_action_points(points) @rpc("any_peer", "call_local") func bot_grab_item(pos: Vector2i, slot: int, x: int, y: int, z: int): playerboard_manager.bot_grab_item(pos, slot, x, y, z) @rpc("any_peer", "call_local") func bot_put_item(pos: Vector2i, slot: int, x: int, y: int, z: int): playerboard_manager.bot_put_item(pos, slot, x, y, z) @rpc("any_peer", "call_local") func bot_arrange_item(from_slot: int, to_slot: int): playerboard_manager.bot_arrange_item(from_slot, to_slot) func update_visual_position(): # Ensure proper grid-aligned positioning var new_pos = Vector3( current_position.x * cell_size.x + cell_size.x * 0.5, 1.0, current_position.y * cell_size.z + cell_size.z * 0.5 ) global_position = new_pos target_visual_position = new_pos # Snap target too if is_multiplayer_authority(): rpc("sync_position", current_position) @rpc("any_peer", "call_local") func sync_position(pos: Vector2i): current_position = pos # If random spawn is active, receiving a position sync essentially confirms a valid spawn if LobbyManager.get_randomize_spawn(): spawn_point_selected = true if not visible: visible = true # Always update the visual position after position sync var new_pos = Vector3( current_position.x * cell_size.x + cell_size.x * 0.5, cell_size.y, current_position.y * cell_size.z + cell_size.z * 0.5 ) + cell_offset # Only snap visual if not moving (moving players will tween to destination) if not is_player_moving: global_position = new_pos target_visual_position = new_pos # Reset smoothing target to prevent fighting @rpc("any_peer", "call_local", "reliable") func set_spawn_position(pos: Vector2i): """Set spawn position - used by random spawn system.""" current_position = pos spawn_point_selected = true # Clear any spawn highlights clear_spawn_highlights() # Update visual position var new_pos = grid_to_world(pos) print("[Player %s] set_spawn_position: Grid %s -> World %s (CellSize: %s)" % [name, pos, new_pos, cell_size]) if _movement_tween: _movement_tween.kill() _movement_tween = null is_player_moving = false global_position = new_pos target_visual_position = new_pos # Reveal character now that it's in the correct position visible = true # Notify systems that position changed (for Camera snap) position_changed.emit() emit_signal("position_changed") @rpc("any_peer", "call_local", "reliable") func complete_race(final_position: int): if race_manager: race_manager.on_race_completed(final_position) # ============================================================================= # Tekton Interaction Logic # ============================================================================= func grab_tekton(): if not is_multiplayer_authority() or is_carrying_tekton or is_frozen or is_stop_frozen: return # 1. Check for nearby carrier to snatch from var carrier = _find_nearby_carrier() if carrier: snatch_tekton(carrier) return # 2. Find nearby roaming Tekton var tekton = _find_nearby_tekton() if tekton: if is_multiplayer_authority() and can_rpc(): rpc("sync_grab_tekton", tekton.get_path()) elif is_multiplayer_authority(): sync_grab_tekton(tekton.get_path()) func snatch_tekton(target_carrier: Node3D): if not is_multiplayer_authority() or not target_carrier.is_carrying_tekton: return var tekton = target_carrier.carried_tekton if tekton: if is_multiplayer_authority() and can_rpc(): rpc("sync_snatch_tekton", target_carrier.get_path(), tekton.get_path()) elif is_multiplayer_authority(): sync_snatch_tekton(target_carrier.get_path(), tekton.get_path()) @rpc("any_peer", "call_local", "reliable") func sync_snatch_tekton(carrier_path: NodePath, tekton_path: NodePath): var carrier = get_node_or_null(carrier_path) var tekton = get_node_or_null(tekton_path) if carrier and tekton: # Security: ensure multiple people don't think they are carrying it # Transfer logic carrier.is_carrying_tekton = false carrier.carried_tekton = null self.is_carrying_tekton = true self.carried_tekton = tekton tekton.set_carried(true, self ) # Reset my carry timer (3s rule starts fresh) tekton_carry_timer = 0.0 # Visual/Logic side effects if is_charged_strike: is_charged_strike = false SfxManager.play("pick_up_tekton_roaming") if anim_player and anim_player.has_animation("animation-pack/pickup_1"): anim_player.play("animation-pack/pickup_1") if anim_player.has_animation("animation-pack/holding_1"): anim_player.queue("animation-pack/holding_1") # Visual feedback for the victim if carrier.has_method("sync_bump"): # Bump away from the snatcher carrier.sync_bump(current_position, true) print("[Player %s] SNATCHED Tekton from %s" % [name, carrier.name]) @rpc("any_peer", "call_local", "reliable") func sync_grab_tekton(tekton_path: NodePath): var tekton = get_node_or_null(tekton_path) if tekton: if anim_player and anim_player.has_animation("animation-pack/pickup_1"): anim_player.play("animation-pack/pickup_1") if anim_player.has_animation("animation-pack/holding_1"): anim_player.queue("animation-pack/holding_1") carried_tekton = tekton self.is_carrying_tekton = true tekton.set_carried(true, self ) # Disposed of Charged Strike upon grab if is_charged_strike: is_charged_strike = false SfxManager.play("pick_up_tekton_roaming") print("[Player %s] Grabbed Tekton %s" % [name, tekton.name]) func throw_tekton(): if not is_multiplayer_authority() or not is_carrying_tekton or is_frozen or is_stop_frozen: return # Determine throw direction (where player is facing) # NOTE: Movement manager uses atan2(x, z) which implies 0 rotation = +Z facing. # So we must use +basis.z (Positive Z) as forward, not standard -basis.z. var forward = global_transform.basis.z.normalized() var throw_dir = Vector2i(round(forward.x), round(forward.z)) if throw_dir == Vector2i.ZERO: throw_dir = Vector2i(1, 0) # Fallback # Calculate distance (5 to 7 tiles) var rng = RandomNumberGenerator.new() rng.randomize() var distance = rng.randi_range(5, 7) var target_pos = current_position + (throw_dir * distance) # Clamp to grid bounds if possible, or just check validity if enhanced_gridmap: # Simple clamp assuming 0-based indexing and knowing size would be better, # but if we don't have size, we can just raycast or check validity step by step? # Let's just try the target. If invalid, maybe pull back? # Or just let it land "off map" and handle it? # Better: Clamp to grid dimensions if known. # EnhancedGridMap usually has columns/rows. if "columns" in enhanced_gridmap and "rows" in enhanced_gridmap: target_pos.x = clamp(target_pos.x, 0, enhanced_gridmap.columns - 1) target_pos.y = clamp(target_pos.y, 0, enhanced_gridmap.rows - 1) if is_multiplayer_authority(): rpc("sync_throw_tekton", target_pos) @rpc("any_peer", "call_local", "reliable") func sync_throw_tekton(target_pos: Vector2i): if anim_player and anim_player.has_animation("animation-pack/put_1"): anim_player.play("animation-pack/put_1") if carried_tekton: var tekton = carried_tekton carried_tekton = null self.is_carrying_tekton = false if tekton.has_method("set_thrown"): tekton.set_thrown(true) else: tekton.set_carried(false) # Face tekton toward throw direction var end_world_pos = Vector3( target_pos.x * cell_size.x + cell_size.x * 0.5, cell_size.y, target_pos.y * cell_size.z + cell_size.z * 0.5 ) + cell_offset tekton.look_at(Vector3(end_world_pos.x, tekton.global_position.y, end_world_pos.z), Vector3.UP) # Play throw animation on the tekton if tekton.has_method("play_animation"): tekton.play_animation("ted_bones_001|Tekton Throwing Tiles|Anima_Layer") # Visual Arc Tween var start_pos = tekton.global_position # end_world_pos already computed above for facing var mid_pos = (start_pos + end_world_pos) / 2.0 mid_pos.y += 4.0 # Arc height var tween = create_tween() tween.set_parallel(true) # Let's stick to a simple "Jump" tween: # 1. Move X/Z linearly to target tween.tween_property(tekton, "global_position:x", end_world_pos.x, 0.6).set_trans(Tween.TRANS_LINEAR) tween.tween_property(tekton, "global_position:z", end_world_pos.z, 0.6).set_trans(Tween.TRANS_LINEAR) # 2. Move Y up then down var jump_tween = create_tween() jump_tween.tween_property(tekton, "global_position:y", mid_pos.y, 0.3).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT) jump_tween.tween_property(tekton, "global_position:y", end_world_pos.y, 0.3).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_IN).set_delay(0.3) # Landing Callback jump_tween.tween_callback(func(): tekton.current_position = target_pos # Impact Effects! # 1. Stun nearby players (Radius 2?) # "if there's a player around that floor they will got stunned" -> "around that floor" implies radius var impact_center = target_pos var stun_radius = 1.5 var players = get_tree().get_nodes_in_group("Players") print("[Throw] Checking stun impact at %s. Found %d players." % [impact_center, players.size()]) for p in players: if p == self: continue # Check distance var dist = Vector2(p.current_position.x, p.current_position.y).distance_to(Vector2(impact_center.x, impact_center.y)) print("[Throw] Player %s at %s. Dist: %.2f (Radius: %.1f)" % [p.name, p.current_position, dist, stun_radius]) if dist <= stun_radius: if p.has_method("apply_stagger"): print("[Throw] Applying stagger to %s" % p.name) p.apply_stagger(3.0) NotificationManager.send_message(self , "Stunned " + p.name + "!", NotificationManager.MessageType.WARNING) # 2. Tekton drops tiles (Spawn tiles around) AND shrinks if tekton.has_method("on_thrown_landing"): tekton.on_thrown_landing(self , 2.0) else: # Fallback tekton.on_hit(self , 1.0) print("[Player %s] Tekton landed at %s" % [name, target_pos]) ).set_delay(0.6) print("[Player %s] Threw Tekton to %s (Dist: %s)" % [name, target_pos, target_pos.distance_to(tekton.current_position)]) func drop_tekton(): """Drops the Tekton at the current player position immediately.""" if not is_multiplayer_authority() or not is_carrying_tekton: return if is_multiplayer_authority() and can_rpc(): rpc("sync_drop_tekton") @rpc("any_peer", "call_local", "reliable") func sync_drop_tekton(): if anim_player and anim_player.has_animation("animation-pack/put_1"): anim_player.play("animation-pack/put_1") if carried_tekton: var tekton = carried_tekton carried_tekton = null self.is_carrying_tekton = false # Set its position to player's current position (but on ground) var drop_pos = grid_to_world(current_position) tekton.global_position = drop_pos if tekton.has_method("set_carried"): tekton.set_carried(false) # Trigger landing effects (minimal scale) if tekton.has_method("on_thrown_landing"): tekton.on_thrown_landing(self , 1.0) # Minimal scale impact print("[Player %s] Dropped Tekton at %s" % [name, current_position]) func enter_charged_strike(): if not is_multiplayer_authority(): return if is_invisible: NotificationManager.send_message(self , "Cannot use Charged Strike while in Ghost mode!", NotificationManager.MessageType.WARNING) return is_charged_strike = true NotificationManager.send_message(self , "Charged Strike ACTIVATED (Red)", NotificationManager.MessageType.POWERUP) update_active_player_indicator() func update_active_player_indicator(): _refresh_player_visuals() @rpc("any_peer", "call_local", "unreliable") func sync_bump(target_pos: Vector2i, is_soft: bool = false): """Visual attack 'bump' or collision animation.""" if not is_soft and anim_player and anim_player.has_animation("animation-pack/hit_1"): anim_player.play("animation-pack/hit_1") # Always return to LOGICAL position to prevent character drift! var original_pos = grid_to_world(current_position) var target_world = grid_to_world(target_pos) # If it's a soft bump (non-attack), just a tiny nudge var strength = 0.4 if not is_soft else 0.15 var duration = 0.1 if not is_soft else 0.08 var mid_pos = original_pos.lerp(target_world, strength) var tween = create_tween() # Ensure the character starts at logical pos if they were drifting global_position = original_pos tween.tween_property(self , "global_position", mid_pos, duration).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT) tween.tween_property(self , "global_position", original_pos, duration).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_IN) func knock_tekton(): if not is_multiplayer_authority() or is_frozen or is_stop_frozen or is_invisible: return # Requirement: Full Powerup Bar (or we are already charged) if not is_charged_strike and (not powerup_manager or not powerup_manager.can_use_special()): NotificationManager.send_message(self , "Need Full Boost to Knock!", NotificationManager.MessageType.WARNING) return var tekton = _find_nearby_tekton() if tekton: # Consume Boost if we haven't already (or just consume it now if we are in mode) if powerup_manager: powerup_manager.consume_boost(100.0) if is_multiplayer_authority(): rpc("sync_knock_tekton", tekton.get_path()) # Reset Charged Strike Mode after successful hit is_charged_strike = false NotificationManager.send_message(self , "Knock Successful!", NotificationManager.MessageType.POWERUP) update_active_player_indicator() else: # If we called knock_tekton but nothing was nearby, maybe we just enter the mode? # But usually this is called by movement_manager which knows something is there. pass @rpc("any_peer", "call_local", "reliable") func sync_knock_tekton(tekton_path: NodePath): if anim_player and anim_player.has_animation("animation-pack/hit_1"): anim_player.play("animation-pack/hit_1") var tekton = get_node_or_null(tekton_path) if tekton: # Intensity 2.0 for knock (drops 200% tiles) + Shrink/Recover # Use on_thrown_landing to trigger shrink animation and floor freeze tekton.on_thrown_landing(self , 2.0) SfxManager.play("attack_mode") print("[Player %s] Knocked Tekton %s" % [name, tekton.name]) # Visual feedback (Juice) if is_multiplayer_authority(): rpc("trigger_screen_shake", "heavy") func _find_nearby_tekton() -> Node3D: # Find closest Tekton var closest_tekton = null var min_dist = 9999.0 var tektons = get_tree().get_nodes_in_group("Tektons") for t in tektons: if t.is_carried: continue if t.get("is_recovering"): continue # Cannot grab recovering/shrunk Tekton if t.get("is_static_turret"): continue # Cannot grab/knock static turret # For example: (pos1 - pos2).length_squared() <= 2 (for adjacent or same tile) var dist_grid = (t.current_position - current_position).length() if dist_grid <= 1.5: # Adjacent (1.0 or 1.41) or same tile (0.0) var dist = global_position.distance_to(t.global_position) if dist < min_dist: min_dist = dist closest_tekton = t return closest_tekton func _find_nearby_carrier() -> Node3D: """Find a nearby player who is carrying a Tekton.""" var players = get_tree().get_nodes_in_group("Players") for p in players: if p == self: continue if p.is_carrying_tekton: # Check adjacency or same tile var dist = Vector2(p.current_position.x, p.current_position.y).distance_to(Vector2(current_position.x, current_position.y)) if dist <= 1.5: return p return null