Fix critical memory leaks, race conditions, and improve code quality

- Fix memory leaks in match3_gameplay.gd with proper queue_free() usage
  - Add comprehensive error handling and fallback mechanisms to SettingsManager
  - Resolve scene loading race conditions in GameManager with state protection
  - Remove problematic static variables from tile.gd, replace with instance-based approach
  - Consolidate duplicate debug menu classes into shared DebugMenuBase
  - Add input validation across all user input paths for security and stability
This commit is contained in:
2025-09-25 00:47:08 +04:00
parent bbf512b675
commit 742e4251fb
11 changed files with 914 additions and 442 deletions

View File

@@ -1,129 +1,36 @@
extends Control
@onready var regenerate_button: Button = $VBoxContainer/RegenerateButton
@onready var gem_types_spinbox: SpinBox = $VBoxContainer/GemTypesContainer/GemTypesSpinBox
@onready var gem_types_label: Label = $VBoxContainer/GemTypesContainer/GemTypesLabel
@onready var grid_width_spinbox: SpinBox = $VBoxContainer/GridSizeContainer/GridWidthContainer/GridWidthSpinBox
@onready var grid_height_spinbox: SpinBox = $VBoxContainer/GridSizeContainer/GridHeightContainer/GridHeightSpinBox
@onready var grid_width_label: Label = $VBoxContainer/GridSizeContainer/GridWidthContainer/GridWidthLabel
@onready var grid_height_label: Label = $VBoxContainer/GridSizeContainer/GridHeightContainer/GridHeightLabel
var match3_scene: Node2D
extends DebugMenuBase
func _ready():
DebugManager.log_debug("Match3DebugMenu _ready() called", "Match3")
DebugManager.debug_toggled.connect(_on_debug_toggled)
# Initialize with current debug state
# Set specific configuration for Match3DebugMenu
log_category = "Match3"
target_script_path = "res://scenes/game/gameplays/match3_gameplay.gd"
# Call parent's _ready
super._ready()
DebugManager.log_debug("Match3DebugMenu _ready() completed", log_category)
# Initialize with current debug state if enabled
var current_debug_state = DebugManager.is_debug_enabled()
DebugManager.log_debug("Match3DebugMenu current debug state is " + str(current_debug_state), "Match3")
visible = current_debug_state
DebugManager.log_debug("Match3DebugMenu initial visibility set to " + str(visible), "Match3")
if current_debug_state:
_on_debug_toggled(true)
regenerate_button.pressed.connect(_on_regenerate_pressed)
gem_types_spinbox.value_changed.connect(_on_gem_types_changed)
grid_width_spinbox.value_changed.connect(_on_grid_width_changed)
grid_height_spinbox.value_changed.connect(_on_grid_height_changed)
func _find_match3_scene():
func _find_target_scene():
# Debug menu is now: Match3 -> UILayer -> Match3DebugMenu
# So we need to go up two levels: get_parent() = UILayer, get_parent().get_parent() = Match3
var ui_layer = get_parent()
if ui_layer and ui_layer is CanvasLayer:
match3_scene = ui_layer.get_parent()
if match3_scene and match3_scene.get_script():
var script_path = match3_scene.get_script().resource_path
if script_path == "res://scenes/game/gameplays/match3_gameplay.gd":
DebugManager.log_debug("Found match3 scene: " + match3_scene.name + " at path: " + str(match3_scene.get_path()), "Match3")
var potential_match3 = ui_layer.get_parent()
if potential_match3 and potential_match3.get_script():
var script_path = potential_match3.get_script().resource_path
if script_path == target_script_path:
match3_scene = potential_match3
DebugManager.log_debug("Found match3 scene: " + match3_scene.name + " at path: " + str(match3_scene.get_path()), log_category)
_update_ui_from_scene()
_stop_search_timer()
return
# If we couldn't find it, clear the reference
# If we couldn't find it, clear the reference and continue searching
match3_scene = null
DebugManager.log_error("Could not find match3_gameplay scene", "Match3")
func _on_debug_toggled(enabled: bool):
DebugManager.log_debug("Match3DebugMenu debug toggled to " + str(enabled), "Match3")
visible = enabled
DebugManager.log_debug("Match3DebugMenu visibility set to " + str(visible), "Match3")
if enabled:
# Always refresh match3 scene reference when debug menu opens
if not match3_scene:
_find_match3_scene()
# Update display values
if match3_scene and match3_scene.has_method("get") and "TILE_TYPES" in match3_scene:
gem_types_spinbox.value = match3_scene.TILE_TYPES
gem_types_label.text = "Gem Types: " + str(match3_scene.TILE_TYPES)
# Update grid size display values
if match3_scene and "GRID_SIZE" in match3_scene:
var grid_size = match3_scene.GRID_SIZE
grid_width_spinbox.value = grid_size.x
grid_height_spinbox.value = grid_size.y
grid_width_label.text = "Width: " + str(grid_size.x)
grid_height_label.text = "Height: " + str(grid_size.y)
func _on_regenerate_pressed():
if not match3_scene:
_find_match3_scene()
if not match3_scene:
DebugManager.log_error("Could not find match3 scene for regeneration", "Match3")
return
if match3_scene.has_method("regenerate_grid"):
DebugManager.log_debug("Calling regenerate_grid()", "Match3")
await match3_scene.regenerate_grid()
else:
DebugManager.log_error("match3_scene does not have regenerate_grid method", "Match3")
func _on_gem_types_changed(value: float):
if not match3_scene:
_find_match3_scene()
if not match3_scene:
DebugManager.log_error("Could not find match3 scene for gem types change", "Match3")
return
var new_value = int(value)
if match3_scene.has_method("set_tile_types"):
DebugManager.log_debug("Setting tile types to " + str(new_value), "Match3")
await match3_scene.set_tile_types(new_value)
gem_types_label.text = "Gem Types: " + str(new_value)
else:
DebugManager.log_error("match3_scene does not have set_tile_types method", "Match3")
func _on_grid_width_changed(value: float):
if not match3_scene:
_find_match3_scene()
if not match3_scene:
DebugManager.log_error("Could not find match3 scene for grid width change", "Match3")
return
var new_width = int(value)
grid_width_label.text = "Width: " + str(new_width)
# Get current height
var current_height = int(grid_height_spinbox.value)
if match3_scene.has_method("set_grid_size"):
DebugManager.log_debug("Setting grid size to " + str(new_width) + "x" + str(current_height), "Match3")
await match3_scene.set_grid_size(Vector2i(new_width, current_height))
func _on_grid_height_changed(value: float):
if not match3_scene:
_find_match3_scene()
if not match3_scene:
DebugManager.log_error("Could not find match3 scene for grid height change", "Match3")
return
var new_height = int(value)
grid_height_label.text = "Height: " + str(new_height)
# Get current width
var current_width = int(grid_width_spinbox.value)
if match3_scene.has_method("set_grid_size"):
DebugManager.log_debug("Setting grid size to " + str(current_width) + "x" + str(new_height), "Match3")
await match3_scene.set_grid_size(Vector2i(current_width, new_height))
DebugManager.log_error("Could not find match3_gameplay scene", log_category)
_start_search_timer()

View File

@@ -24,13 +24,7 @@ var keyboard_navigation_enabled: bool = false
func _ready():
DebugManager.log_debug("Match3 _ready() started", "Match3")
# Set up initial gem pool
var gem_indices = []
for i in range(TILE_TYPES):
gem_indices.append(i)
const TileScript = preload("res://scenes/game/gameplays/tile.gd")
TileScript.set_active_gem_pool(gem_indices)
# Gem pool will be set individually on each tile during creation
_calculate_grid_layout()
_initialize_grid()
@@ -58,14 +52,11 @@ func _calculate_grid_layout():
)
func _initialize_grid():
# Update gem pool BEFORE creating any tiles
# Create gem pool for current tile types
var gem_indices = []
for i in range(TILE_TYPES):
gem_indices.append(i)
const TileScript = preload("res://scenes/game/gameplays/tile.gd")
TileScript.set_active_gem_pool(gem_indices)
for y in range(GRID_SIZE.y):
grid.append([])
for x in range(GRID_SIZE.x):
@@ -74,9 +65,14 @@ func _initialize_grid():
tile.position = tile_position
tile.grid_position = Vector2i(x, y)
add_child(tile)
# Set gem types for this tile
tile.set_active_gem_types(gem_indices)
# Set tile type after adding to scene tree so sprite reference is available
var new_type = randi() % TILE_TYPES
tile.tile_type = new_type
# Connect tile signals
tile.tile_selected.connect(_on_tile_selected)
DebugManager.log_debug("Created tile at grid(%d,%d) world_pos(%s) with type %d" % [x, y, tile_position, new_type], "Match3")
@@ -147,10 +143,13 @@ func _clear_matches():
if to_clear.size() == 0:
return
# Clear grid references first, then queue nodes for removal
for tile in to_clear:
grid[tile.grid_position.y][tile.grid_position.x] = null
tile.queue_free()
# Wait one frame for nodes to be queued properly
await get_tree().process_frame
_drop_tiles()
await get_tree().create_timer(0.2).timeout
_fill_empty_cells()
@@ -174,16 +173,29 @@ func _drop_tiles():
moved = true
func _fill_empty_cells():
# Create gem pool for current tile types
var gem_indices = []
for i in range(TILE_TYPES):
gem_indices.append(i)
for y in range(GRID_SIZE.y):
for x in range(GRID_SIZE.x):
if not grid[y][x]:
var tile = TILE_SCENE.instantiate()
tile.grid_position = Vector2i(x, y)
tile.tile_type = randi() % TILE_TYPES
tile.position = grid_offset + Vector2(x, y) * tile_size
grid[y][x] = tile
add_child(tile)
# Set gem types for this tile
tile.set_active_gem_types(gem_indices)
# Set random tile type
tile.tile_type = randi() % TILE_TYPES
grid[y][x] = tile
# Connect tile signals for new tiles
tile.tile_selected.connect(_on_tile_selected)
# Fixed: Add recursion protection to prevent stack overflow
await get_tree().create_timer(0.1).timeout
var max_iterations = 10
@@ -208,21 +220,21 @@ func regenerate_grid():
if script_path == "res://scenes/game/gameplays/tile.gd":
children_to_remove.append(child)
# Remove all found tile children
for child in children_to_remove:
child.free()
# Also clear grid array references
# First clear grid array references to prevent access to nodes being freed
for y in range(grid.size()):
if grid[y] and grid[y] is Array:
for x in range(grid[y].size()):
# Set to null since we already freed the nodes above
grid[y][x] = null
# Clear the grid array
grid.clear()
# No need to wait for nodes to be freed since we used free()
# Remove all found tile children using queue_free for safe cleanup
for child in children_to_remove:
child.queue_free()
# Wait for nodes to be properly freed from the scene tree
await get_tree().process_frame
# Fixed: Recalculate grid layout before regenerating tiles
_calculate_grid_layout()
@@ -315,25 +327,37 @@ func _input(event: InputEvent) -> void:
func _move_cursor(direction: Vector2i) -> void:
# Input validation for direction vector
if abs(direction.x) > 1 or abs(direction.y) > 1:
DebugManager.log_error("Invalid cursor direction vector: " + str(direction), "Match3")
return
if direction.x != 0 and direction.y != 0:
DebugManager.log_error("Diagonal cursor movement not supported: " + str(direction), "Match3")
return
var old_pos = cursor_position
var new_pos = cursor_position + direction
# Bounds checking
new_pos.x = clamp(new_pos.x, 0, GRID_SIZE.x - 1)
new_pos.y = clamp(new_pos.y, 0, GRID_SIZE.y - 1)
if new_pos != cursor_position:
# Validate old position before accessing grid
if old_pos.x >= 0 and old_pos.y >= 0 and old_pos.x < GRID_SIZE.x and old_pos.y < GRID_SIZE.y:
var old_tile = grid[cursor_position.y][cursor_position.x]
if old_tile and not old_tile.is_selected:
old_tile.is_highlighted = false
DebugManager.log_debug("Cursor moved from (%d,%d) to (%d,%d)" % [old_pos.x, old_pos.y, new_pos.x, new_pos.y], "Match3")
# Clear highlighting from old cursor position (only if not selected)
var old_tile = grid[cursor_position.y][cursor_position.x]
if old_tile and not old_tile.is_selected:
old_tile.is_highlighted = false
cursor_position = new_pos
# Highlight new cursor position (only if not selected)
var new_tile = grid[cursor_position.y][cursor_position.x]
if new_tile and not new_tile.is_selected:
new_tile.is_highlighted = true
# Validate new position before accessing grid
if cursor_position.x >= 0 and cursor_position.y >= 0 and cursor_position.x < GRID_SIZE.x and cursor_position.y < GRID_SIZE.y:
var new_tile = grid[cursor_position.y][cursor_position.x]
if new_tile and not new_tile.is_selected:
new_tile.is_highlighted = true
func _select_tile_at_cursor() -> void:
if cursor_position.x >= 0 and cursor_position.y >= 0 and cursor_position.x < GRID_SIZE.x and cursor_position.y < GRID_SIZE.y:

View File

@@ -25,11 +25,8 @@ var all_gem_textures = [
preload("res://assets/sprites/gems/sg_19.png"), # 7 - Silver gem
]
# Static variable to store the current gem pool for all tiles
static var current_gem_pool = [0, 1, 2, 3, 4] # Start with first 5 gems
# Currently active gem types (indices into all_gem_textures)
var active_gem_types = [] # Will be set from current_gem_pool
var active_gem_types = [] # Will be set from TileManager
func _set_tile_type(value: int) -> void:
tile_type = value
@@ -54,65 +51,59 @@ func _scale_sprite_to_fit() -> void:
sprite.scale = original_scale
DebugManager.log_debug("Set original scale to %s for tile (%d,%d)" % [original_scale, grid_position.x, grid_position.y], "Match3")
# Gem pool management functions
static func set_active_gem_pool(gem_indices: Array) -> void:
# Update static gem pool for new tiles
current_gem_pool = gem_indices.duplicate()
func set_active_gem_types(gem_indices: Array) -> void:
if not gem_indices or gem_indices.is_empty():
DebugManager.log_error("Empty gem indices array provided", "Tile")
return
# Update all existing tile instances to use new gem pool
var scene_tree = Engine.get_main_loop() as SceneTree
if scene_tree:
var tiles = scene_tree.get_nodes_in_group("tiles")
for tile in tiles:
if tile.has_method("_update_active_gems"):
tile._update_active_gems(gem_indices)
func _update_active_gems(gem_indices: Array) -> void:
active_gem_types = gem_indices.duplicate()
# Validate all gem indices are within bounds
for gem_index in active_gem_types:
if gem_index < 0 or gem_index >= all_gem_textures.size():
DebugManager.log_error("Invalid gem index: %d (valid range: 0-%d)" % [gem_index, all_gem_textures.size() - 1], "Tile")
# Use default fallback
active_gem_types = [0, 1, 2, 3, 4]
break
# Re-validate current tile type
if tile_type >= active_gem_types.size():
# Generate a new random tile type within valid range
tile_type = randi() % active_gem_types.size()
_set_tile_type(tile_type)
static func get_active_gem_count() -> int:
# Get from any tile instance or default
var scene_tree = Engine.get_main_loop() as SceneTree
if scene_tree:
var tiles = scene_tree.get_nodes_in_group("tiles")
if tiles.size() > 0:
return tiles[0].active_gem_types.size()
return 5 # Default
func get_active_gem_count() -> int:
return active_gem_types.size()
static func add_gem_to_pool(gem_index: int) -> void:
var scene_tree = Engine.get_main_loop() as SceneTree
if scene_tree:
var tiles = scene_tree.get_nodes_in_group("tiles")
for tile in tiles:
if tile.has_method("_add_gem_type"):
tile._add_gem_type(gem_index)
func add_gem_type(gem_index: int) -> bool:
if gem_index < 0 or gem_index >= all_gem_textures.size():
DebugManager.log_error("Invalid gem index: %d" % gem_index, "Tile")
return false
func _add_gem_type(gem_index: int) -> void:
if gem_index >= 0 and gem_index < all_gem_textures.size():
if not active_gem_types.has(gem_index):
active_gem_types.append(gem_index)
if not active_gem_types.has(gem_index):
active_gem_types.append(gem_index)
return true
static func remove_gem_from_pool(gem_index: int) -> void:
var scene_tree = Engine.get_main_loop() as SceneTree
if scene_tree:
var tiles = scene_tree.get_nodes_in_group("tiles")
for tile in tiles:
if tile.has_method("_remove_gem_type"):
tile._remove_gem_type(gem_index)
return false
func _remove_gem_type(gem_index: int) -> void:
func remove_gem_type(gem_index: int) -> bool:
var type_index = active_gem_types.find(gem_index)
if type_index != -1 and active_gem_types.size() > 2: # Keep at least 2 gem types
active_gem_types.erase(gem_index)
# Update tiles that were using removed type
if tile_type >= active_gem_types.size():
tile_type = 0
_set_tile_type(tile_type)
if type_index == -1:
return false
if active_gem_types.size() <= 2: # Keep at least 2 gem types
DebugManager.log_warn("Cannot remove gem type - minimum 2 types required", "Tile")
return false
active_gem_types.erase(gem_index)
# Update tile if it was using the removed type
if tile_type >= active_gem_types.size():
tile_type = 0
_set_tile_type(tile_type)
return true
func _set_selected(value: bool) -> void:
var old_value = is_selected
@@ -184,8 +175,11 @@ func force_reset_visual_state() -> void:
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
add_to_group("tiles") # Add to group for gem pool management
# Initialize with current static gem pool
active_gem_types = current_gem_pool.duplicate()
# Initialize with default gem pool if not already set
if active_gem_types.is_empty():
active_gem_types = [0, 1, 2, 3, 4] # Default to first 5 gems
_set_tile_type(tile_type)