match-3 grid generation

make game scene modular
global debug mode
This commit is contained in:
2025-09-24 10:45:14 +04:00
parent 122b5cb55f
commit afc808f0d6
21 changed files with 506 additions and 94 deletions

View File

@@ -0,0 +1,129 @@
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
func _ready():
print("Match3DebugMenu: _ready() called")
DebugManager.debug_toggled.connect(_on_debug_toggled)
# Initialize with current debug state
var current_debug_state = DebugManager.is_debug_enabled()
print("Match3DebugMenu: Current debug state is ", current_debug_state)
visible = current_debug_state
print("Match3DebugMenu: Initial visibility set to ", visible)
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():
# 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":
print("Debug: Found match3 scene: ", match3_scene.name, " at path: ", match3_scene.get_path())
return
# If we couldn't find it, clear the reference
match3_scene = null
print("Debug: Could not find match3_gameplay scene")
func _on_debug_toggled(enabled: bool):
print("Match3DebugMenu: Debug toggled to ", enabled)
visible = enabled
print("Match3DebugMenu: Visibility set to ", visible)
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:
print("Error: Could not find match3 scene for regeneration")
return
if match3_scene.has_method("regenerate_grid"):
print("Debug: Calling regenerate_grid()")
await match3_scene.regenerate_grid()
else:
print("Error: match3_scene does not have regenerate_grid method")
func _on_gem_types_changed(value: float):
if not match3_scene:
_find_match3_scene()
if not match3_scene:
print("Error: Could not find match3 scene for gem types change")
return
var new_value = int(value)
if match3_scene.has_method("set_tile_types"):
print("Debug: Setting tile types to ", new_value)
await match3_scene.set_tile_types(new_value)
gem_types_label.text = "Gem Types: " + str(new_value)
else:
print("Error: match3_scene does not have set_tile_types method")
func _on_grid_width_changed(value: float):
if not match3_scene:
_find_match3_scene()
if not match3_scene:
print("Error: Could not find match3 scene for grid width change")
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"):
print("Debug: Setting grid size to ", new_width, "x", current_height)
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:
print("Error: Could not find match3 scene for grid height change")
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"):
print("Debug: Setting grid size to ", current_width, "x", new_height)
await match3_scene.set_grid_size(Vector2i(current_width, new_height))

View File

@@ -0,0 +1,83 @@
[gd_scene load_steps=2 format=3 uid="uid://b76oiwlifikl3"]
[ext_resource type="Script" path="res://scenes/game/gameplays/Match3DebugMenu.gd" id="1_debug_menu"]
[node name="DebugMenu" type="Control"]
layout_mode = 3
anchors_preset = 1
anchor_left = 1.0
anchor_right = 1.0
offset_left = -201.0
offset_top = 59.0
offset_right = -11.0
offset_bottom = 169.0
grow_horizontal = 0
script = ExtResource("1_debug_menu")
[node name="VBoxContainer" type="VBoxContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = 10.0
offset_top = 10.0
offset_right = -10.0
offset_bottom = -10.0
grow_horizontal = 2
grow_vertical = 2
[node name="TitleLabel" type="Label" parent="VBoxContainer"]
layout_mode = 2
text = "Match-3 Debug Menu"
horizontal_alignment = 1
[node name="RegenerateButton" type="Button" parent="VBoxContainer"]
layout_mode = 2
text = "Generate New Grid"
[node name="GemTypesContainer" type="HBoxContainer" parent="VBoxContainer"]
layout_mode = 2
[node name="GemTypesLabel" type="Label" parent="VBoxContainer/GemTypesContainer"]
layout_mode = 2
text = "Gem Types: 5"
[node name="GemTypesSpinBox" type="SpinBox" parent="VBoxContainer/GemTypesContainer"]
layout_mode = 2
min_value = 3.0
max_value = 8.0
value = 5.0
[node name="GridSizeContainer" type="VBoxContainer" parent="VBoxContainer"]
layout_mode = 2
[node name="GridSizeLabel" type="Label" parent="VBoxContainer/GridSizeContainer"]
layout_mode = 2
text = "Grid Size"
horizontal_alignment = 1
[node name="GridWidthContainer" type="HBoxContainer" parent="VBoxContainer/GridSizeContainer"]
layout_mode = 2
[node name="GridWidthLabel" type="Label" parent="VBoxContainer/GridSizeContainer/GridWidthContainer"]
layout_mode = 2
text = "Width: 8"
[node name="GridWidthSpinBox" type="SpinBox" parent="VBoxContainer/GridSizeContainer/GridWidthContainer"]
layout_mode = 2
min_value = 4.0
max_value = 12.0
value = 8.0
[node name="GridHeightContainer" type="HBoxContainer" parent="VBoxContainer/GridSizeContainer"]
layout_mode = 2
[node name="GridHeightLabel" type="Label" parent="VBoxContainer/GridSizeContainer/GridHeightContainer"]
layout_mode = 2
text = "Height: 8"
[node name="GridHeightSpinBox" type="SpinBox" parent="VBoxContainer/GridSizeContainer/GridHeightContainer"]
layout_mode = 2
min_value = 4.0
max_value = 12.0
value = 8.0

View File

@@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3 uid="uid://bnk1gqom3oi6q"]
[ext_resource type="Script" path="res://scenes/game/gameplays/tile.gd" id="1_tile_script"]
[node name="Tile" type="Node2D"]
script = ExtResource("1_tile_script")
[node name="Sprite2D" type="Sprite2D" parent="."]

View File

@@ -0,0 +1,10 @@
extends Node2D
signal score_changed(points: int)
func _ready():
print("Clickomania gameplay loaded")
# Example: Add some score after a few seconds to test the system
await get_tree().create_timer(2.0).timeout
score_changed.emit(100)
print("Clickomania awarded 100 points")

View File

@@ -0,0 +1,21 @@
[gd_scene load_steps=2 format=3 uid="uid://cl7g8v0eh3mam"]
[ext_resource type="Script" path="res://scenes/game/gameplays/clickomania_gameplay.gd" id="1_script"]
[node name="Clickomania" type="Node2D"]
script = ExtResource("1_script")
[node name="Label" type="Label" parent="."]
anchors_preset = 8
anchor_left = 0.5
anchor_top = 0.5
anchor_right = 0.5
anchor_bottom = 0.5
offset_left = -100.0
offset_top = -12.0
offset_right = 100.0
offset_bottom = 12.0
grow_horizontal = 2
grow_vertical = 2
text = "Clickomania Gameplay (Demo)"
horizontal_alignment = 1

View File

@@ -0,0 +1,221 @@
extends Node2D
signal score_changed(points: int)
var GRID_SIZE := Vector2i(8, 8)
var TILE_TYPES := 5
const TILE_SCENE := preload("res://scenes/game/gameplays/tile.tscn")
var grid := []
var tile_size: float = 48.0
var grid_offset: Vector2
func _ready():
# 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)
_calculate_grid_layout()
_initialize_grid()
func _calculate_grid_layout():
var viewport_size = get_viewport().get_visible_rect().size
var available_width = viewport_size.x * 0.8 # Use 80% of screen width
var available_height = viewport_size.y * 0.7 # Use 70% of screen height
# Calculate tile size based on available space
var max_tile_width = available_width / GRID_SIZE.x
var max_tile_height = available_height / GRID_SIZE.y
tile_size = min(max_tile_width, max_tile_height)
# Align grid to left side with some margin
var total_grid_height = tile_size * GRID_SIZE.y
grid_offset = Vector2(
50, # Left margin
(viewport_size.y - total_grid_height) / 2 + 50 # Vertically centered with top margin
)
func _initialize_grid():
# Update gem pool BEFORE creating any tiles
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):
var tile = TILE_SCENE.instantiate()
tile.position = grid_offset + Vector2(x, y) * tile_size
tile.grid_position = Vector2i(x, y)
add_child(tile)
# Set tile type after adding to scene tree so sprite reference is available
var new_type = randi() % TILE_TYPES
tile.tile_type = new_type
# print("Debug: Created tile at (", x, ",", y, ") with type ", new_type)
grid[y].append(tile)
func _has_match_at(pos: Vector2i) -> bool:
# Fixed: Add bounds and null checks
if pos.x < 0 or pos.y < 0 or pos.x >= GRID_SIZE.x or pos.y >= GRID_SIZE.y:
return false
if not grid[pos.y][pos.x]:
return false
var matches_horizontal = _get_match_line(pos, Vector2i(1, 0))
if matches_horizontal.size() >= 3:
return true
var matches_vertical = _get_match_line(pos, Vector2i(0, 1))
return matches_vertical.size() >= 3
# Fixed: Add missing function to check for any matches on the board
func _check_for_matches() -> bool:
for y in range(GRID_SIZE.y):
for x in range(GRID_SIZE.x):
if _has_match_at(Vector2i(x, y)):
return true
return false
func _get_match_line(start: Vector2i, dir: Vector2i) -> Array:
var line = [grid[start.y][start.x]]
var type = grid[start.y][start.x].tile_type
# Fixed: Check in both directions separately to avoid infinite loops
for offset in [1, -1]:
var current = start + dir * offset
while current.x >= 0 and current.y >= 0 and current.x < GRID_SIZE.x and current.y < GRID_SIZE.y:
var neighbor = grid[current.y][current.x]
# Fixed: Add null check to prevent crashes
if not neighbor or neighbor.tile_type != type:
break
line.append(neighbor)
current += dir * offset
return line
func _clear_matches():
var to_clear := []
for y in range(GRID_SIZE.y):
for x in range(GRID_SIZE.x):
# Fixed: Add null check before processing
if not grid[y][x]:
continue
var pos = Vector2i(x, y)
var horiz = _get_match_line(pos, Vector2i(1, 0))
if horiz.size() >= 3:
to_clear.append_array(horiz)
var vert = _get_match_line(pos, Vector2i(0, 1))
if vert.size() >= 3:
to_clear.append_array(vert)
# Remove duplicates using dictionary keys trick
var unique_dict := {}
for tile in to_clear:
unique_dict[tile] = true
to_clear = unique_dict.keys()
# Fixed: Only proceed if there are matches to clear
if to_clear.size() == 0:
return
for tile in to_clear:
grid[tile.grid_position.y][tile.grid_position.x] = null
tile.queue_free()
_drop_tiles()
await get_tree().create_timer(0.2).timeout
_fill_empty_cells()
func _drop_tiles():
var moved = true
while moved:
moved = false
for x in range(GRID_SIZE.x):
# Fixed: Start from GRID_SIZE.y - 1 to avoid out of bounds
for y in range(GRID_SIZE.y - 1, -1, -1):
var tile = grid[y][x]
# Fixed: Check bounds before accessing y + 1
if tile and y + 1 < GRID_SIZE.y and not grid[y + 1][x]:
grid[y + 1][x] = tile
grid[y][x] = null
tile.grid_position = Vector2i(x, y + 1)
# You can animate position here using Tween for smooth drop:
# tween.interpolate_property(tile, "position", tile.position, grid_offset + Vector2(x, y + 1) * tile_size, 0.2)
tile.position = grid_offset + Vector2(x, y + 1) * tile_size
moved = true
func _fill_empty_cells():
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)
# Fixed: Add recursion protection to prevent stack overflow
await get_tree().create_timer(0.1).timeout
var max_iterations = 10
var iteration = 0
while _check_for_matches() and iteration < max_iterations:
_clear_matches()
await get_tree().create_timer(0.1).timeout
iteration += 1
func regenerate_grid():
# Use time-based seed to ensure different patterns each time
var new_seed = Time.get_ticks_msec()
seed(new_seed)
print("Debug: Regenerating grid with seed: ", new_seed)
# Fixed: Clear ALL tile children, not just ones in grid array
# This handles any orphaned tiles that might not be tracked in the grid
var children_to_remove = []
for child in get_children():
if child.has_method("get_script") and child.get_script():
var script_path = child.get_script().resource_path
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
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()
# Fixed: Recalculate grid layout before regenerating tiles
_calculate_grid_layout()
# Regenerate the grid (gem pool is updated in _initialize_grid)
_initialize_grid()
func set_tile_types(new_count: int):
TILE_TYPES = new_count
# Regenerate grid with new tile types (gem pool is updated in regenerate_grid)
await regenerate_grid()
func set_grid_size(new_size: Vector2i):
print("Debug: Changing grid size from ", GRID_SIZE, " to ", new_size)
GRID_SIZE = new_size
# Regenerate grid with new size
await regenerate_grid()

View File

@@ -0,0 +1,13 @@
[gd_scene load_steps=3 format=3 uid="uid://b4kv7g7kllwgb"]
[ext_resource type="Script" path="res://scenes/game/gameplays/match3_gameplay.gd" id="1_mvfdp"]
[ext_resource type="PackedScene" path="res://scenes/game/gameplays/Match3DebugMenu.tscn" id="2_debug_menu"]
[node name="Match3" type="Node2D"]
script = ExtResource("1_mvfdp")
[node name="GridContainer" type="Node2D" parent="."]
[node name="UILayer" type="CanvasLayer" parent="."]
[node name="Match3DebugMenu" parent="UILayer" instance=ExtResource("2_debug_menu")]

View File

@@ -0,0 +1,116 @@
extends Node2D
@export var tile_type: int = 0 : set = _set_tile_type
var grid_position: Vector2i
@onready var sprite: Sprite2D = $Sprite2D
# Target size for each tile to fit in the 54x54 grid cells
const TILE_SIZE = 48 # Slightly smaller than 54 to leave some padding
# All available gem textures
var all_gem_textures = [
preload("res://assets/sprites/gems/bg_19.png"), # 0 - Blue gem
preload("res://assets/sprites/gems/dg_19.png"), # 1 - Dark gem
preload("res://assets/sprites/gems/gg_19.png"), # 2 - Green gem
preload("res://assets/sprites/gems/mg_19.png"), # 3 - Magenta gem
preload("res://assets/sprites/gems/rg_19.png"), # 4 - Red gem
preload("res://assets/sprites/gems/yg_19.png"), # 5 - Yellow gem
preload("res://assets/sprites/gems/pg_19.png"), # 6 - Purple gem
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
func _set_tile_type(value: int) -> void:
tile_type = value
print("Debug: _set_tile_type called with value ", value, ", active_gem_types.size() = ", active_gem_types.size())
# Fixed: Add sprite null check to prevent crashes during initialization
if not sprite:
return
if value >= 0 and value < active_gem_types.size():
var texture_index = active_gem_types[value]
sprite.texture = all_gem_textures[texture_index]
# print("Debug: Set texture_index ", texture_index, " for tile_type ", value)
_scale_sprite_to_fit()
else:
push_error("Invalid tile type: " + str(value) + ". Available types: 0-" + str(active_gem_types.size() - 1))
func _scale_sprite_to_fit() -> void:
# Fixed: Add additional null checks
if sprite and sprite.texture:
var texture_size = sprite.texture.get_size()
var max_dimension = max(texture_size.x, texture_size.y)
var scale_factor = TILE_SIZE / max_dimension
sprite.scale = Vector2(scale_factor, scale_factor)
# 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()
# 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()
# 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
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) -> 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)
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)
func _remove_gem_type(gem_index: int) -> void:
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)
# 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()
_set_tile_type(tile_type)