// Prefab de la pieza
public GameObject piecePrefab;
// Matriz para almacenar las piezas
private Piece[,] grid;
// Colores disponibles para las piezas
public Color[] pieceColors;
void Start()
{
// Inicializar la cuadrícula
grid = new Piece[width, height];
// Generar la cuadrícula
GenerateGrid();
// Iniciar la corutina para encontrar y destruir combinaciones
StartCoroutine(FindAndDestroyMatches());
}
void GenerateGrid()
{
// Recorrer filas y columnas
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
SpawnNewPiece(x, y, false); // false porque no necesitamos animar las piezas al inicio
}
}
}
// Método para instanciar una nueva pieza en una posición determinada
void SpawnNewPiece(int x, int y, bool animate = true)
{
// Instanciar la pieza
GameObject newPiece = Instantiate(piecePrefab, new Vector3(x, y + (animate ? height : 0), 0), Quaternion.identity);
// Configurar como hijo del GridManager para mantener la jerarquía ordenada
newPiece.transform.parent = this.transform;
// Obtener el componente Piece
Piece piece = newPiece.GetComponent<Piece>();
// Asignar una posición en la cuadrícula
piece.SetPosition(x, y);
// Asignar un color aleatorio
int randomColorIndex = Random.Range(0, pieceColors.Length);
piece.SetColor(pieceColors[randomColorIndex]);
// Almacenar la pieza en la matriz
grid[x, y] = piece;
// Si se requiere animación
if (animate)
{
// Animar la caída de la pieza desde arriba utilizando la distancia para calcular la duración
float distance = height;
float duration = pieceMoveDurationPerUnit * distance;
newPiece.transform.DOMoveY(y, duration).SetEase(Ease.OutBounce);
}
else
{
// Colocar la pieza directamente en su posición sin animación
newPiece.transform.position = new Vector3(x, y, 0);
}
}
// Método para acceder a una pieza en una posición específica
public Piece GetPieceAt(int x, int y)
{
if (x >= 0 && x < width && y >= 0 && y < height)
{
return grid[x, y];
}
return null;
}
// Método para encontrar y destruir combinaciones
IEnumerator FindAndDestroyMatches()
{
bool needsProcessing = true;
while (needsProcessing)
{
// Encontrar combinaciones
FindAllMatches();
// Obtener las piezas marcadas
List<Piece> matchedPieces = GetAllMatchedPieces();
if (matchedPieces.Count > 0)
{
// Reproducir animaciones de las piezas marcadas
foreach (Piece piece in matchedPieces)
{
piece.PlayMatchAnimation(null);
}
// Esperar la duración de la animación
yield return new WaitForSeconds(0.5f);
// Eliminar las piezas con animación
int piecesToDestroy = matchedPieces.Count;
int destroyedPieces = 0;
foreach (Piece piece in matchedPieces)
{
piece.PlayDestroyAnimation(() =>
{
Destroy(piece.gameObject);
destroyedPieces++;
});
}
// Esperar a que todas las piezas sean destruidas
yield return new WaitUntil(() => destroyedPieces == piecesToDestroy);
// Eliminar referencias de las piezas en la matriz
foreach (Piece piece in matchedPieces)
{
grid[piece.GetX(), piece.GetY()] = null;
}
// Hacer que las piezas caigan
yield return StartCoroutine(CollapseColumns());
// Rellenar el tablero con nuevas piezas
yield return StartCoroutine(RefillBoard());
}
else
{
needsProcessing = false;
}
}
}
// Método para hacer que las piezas caigan y llenen los espacios vacíos
IEnumerator CollapseColumns()
{
bool anyPieceMoved = false;
float maxMoveDuration = 0f;
// Recorrer cada columna
for (int x = 0; x < width; x++)
{
int numEmptySpaces = 0;
// Recorrer cada fila desde abajo hacia arriba
for (int y = 0; y < height; y++)
{
if (grid[x, y] == null)
{
numEmptySpaces++;
}
else if (numEmptySpaces > 0)
{
// Mover la pieza a su nueva posición
Piece piece = grid[x, y];
grid[x, y - numEmptySpaces] = piece;
grid[x, y] = null;
int newY = y - numEmptySpaces;
piece.SetPosition(x, newY);
// Calcular duración basada en la distancia
float distance = numEmptySpaces;
float duration = pieceMoveDurationPerUnit * distance;
// Animar la caída de la pieza
piece.transform.DOMoveY(newY, duration).SetEase(Ease.InQuad);
// Actualizar la duración máxima
if (duration > maxMoveDuration)
maxMoveDuration = duration;
anyPieceMoved = true;
}
}
}
// Esperar a que todas las animaciones de caída terminen
if (anyPieceMoved)
{
yield return new WaitForSeconds(maxMoveDuration);
}
}
// Método para rellenar el tablero con nuevas piezas
IEnumerator RefillBoard()
{
bool anyPieceAdded = false;
float maxMoveDuration = 0f;
for (int x = 0; x < width; x++)
{
// Contar cuántas piezas faltan en esta columna
int piecesNeeded = 0;
for (int y = 0; y < height; y++)
{
if (grid[x, y] == null)
{
piecesNeeded++;
}
}
if (piecesNeeded > 0)
{
anyPieceAdded = true;
// Añadir nuevas piezas en la parte superior
for (int i = 0; i < piecesNeeded; i++)
{
int spawnY = height + i; // Posición Y por encima del tablero
int targetY = height - piecesNeeded + i; // Posición Y dentro del tablero
// Crear la pieza por encima del tablero
GameObject newPieceGO = Instantiate(piecePrefab, new Vector3(x, spawnY, 0), Quaternion.identity);
newPieceGO.transform.parent = this.transform;
Piece newPiece = newPieceGO.GetComponent<Piece>();
newPiece.SetPosition(x, targetY);
// Asignar un color
int randomColorIndex = Random.Range(0, pieceColors.Length);
newPiece.SetColor(pieceColors[randomColorIndex]);
// Asignar la pieza al arreglo grid en la posición targetY
grid[x, targetY] = newPiece;
// Calcular duración basada en la distancia
float distance = spawnY - targetY;
float duration = pieceMoveDurationPerUnit * distance;
Debug.Log("Duration " + duration);
// Animar la caída
newPieceGO.transform.DOMoveY(targetY, duration).SetEase(Ease.OutBounce);
// Actualizar la duración máxima
if (duration > maxMoveDuration)
maxMoveDuration = duration;
}
}
}
// Esperar a que todas las animaciones de caída terminen
if (anyPieceAdded)
{
yield return new WaitForSeconds(maxMoveDuration);
}
}
// Método para encontrar todas las combinaciones en el tablero
void FindAllMatches()
{
// Resetear todas las marcas de piezas
ResetMatchedFlags();
// Buscar combinaciones horizontales
CheckHorizontalMatches();
// Buscar combinaciones verticales
CheckVerticalMatches();
}
// Resetear la bandera de isMatched de todas las piezas
void ResetMatchedFlags()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (grid[x, y] != null)
{
grid[x, y].SetMatched(false);
}
}
}
}
// Buscar combinaciones horizontales
void CheckHorizontalMatches()
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width - 2;)
{
if (grid[x, y] == null)
{
x++;
continue;
}
Color baseColor = grid[x, y].GetColor();
if (grid[x + 1, y] != null && grid[x + 2, y] != null &&
baseColor == grid[x + 1, y].GetColor() && baseColor == grid[x + 2, y].GetColor())
{
// Encontramos una combinación horizontal de 3 o más piezas
int matchLength = 3;
grid[x, y].SetMatched(true);
grid[x + 1, y].SetMatched(true);
grid[x + 2, y].SetMatched(true);
// Verificar si hay más piezas del mismo color en línea
while (x + matchLength < width && grid[x + matchLength, y] != null &&
grid[x + matchLength, y].GetColor() == baseColor)
{
grid[x + matchLength, y].SetMatched(true);
matchLength++;
}
x += matchLength;
}
else
{
x++;
}
}
}
}
// Buscar combinaciones verticales
void CheckVerticalMatches()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height - 2;)
{
if (grid[x, y] == null)
{
y++;
continue;
}
Color baseColor = grid[x, y].GetColor();
if (grid[x, y + 1] != null && grid[x, y + 2] != null &&
baseColor == grid[x, y + 1].GetColor() && baseColor == grid[x, y + 2].GetColor())
{
// Encontramos una combinación vertical de 3 o más piezas
int matchLength = 3;
grid[x, y].SetMatched(true);
grid[x, y + 1].SetMatched(true);
grid[x, y + 2].SetMatched(true);
// Verificar si hay más piezas del mismo color en línea
while (y + matchLength < height && grid[x, y + matchLength] != null &&
grid[x, y + matchLength].GetColor() == baseColor)
{
grid[x, y + matchLength].SetMatched(true);
matchLength++;
}
y += matchLength;
}
else
{
y++;
}
}
}
}
// Obtener todas las piezas marcadas
List<Piece> GetAllMatchedPieces()
{
List<Piece> matchedPieces = new List<Piece>();
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
Piece piece = grid[x, y];
if (piece != null && piece.IsMatched())
{
matchedPieces.Add(piece);
}
}
}
return matchedPieces;
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
public class GridManager : MonoBehaviour
{
private int width = 8;
private int height = 8;
private float pieceMoveDurationPerUnit = 0.15f;
public GameObject piecePrefab;
private Piece[,] grid;
public Color[] pieceColors;
private bool isSwapping = false;
private bool isProcessingMatches = false;
void Start()
{
grid = new Piece[width, height];
GenerateGrid();
// Procesar posibles combinaciones iniciales
StartCoroutine(DestroyAndCollapseMatches());
}
void GenerateGrid()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
SpawnNewPiece(x, y, false);
}
}
}
void SpawnNewPiece(int x, int y, bool animate = true)
{
GameObject newPiece = Instantiate(piecePrefab, new Vector3(x, y + (animate ? height : 0), 0), Quaternion.identity);
newPiece.transform.parent = this.transform;
Piece piece = newPiece.GetComponent<Piece>();
piece.SetPosition(x, y);
int randomColorIndex = Random.Range(0, pieceColors.Length);
piece.SetColor(pieceColors[randomColorIndex]);
grid[x, y] = piece;
if (animate)
{
float distance = height;
float duration = pieceMoveDurationPerUnit * distance;
newPiece.transform.DOMoveY(y, duration).SetEase(Ease.OutBounce);
}
else
{
newPiece.transform.position = new Vector3(x, y, 0);
}
}
public Piece GetPieceAt(int x, int y)
{
if (IsValidPosition(x, y))
{
return grid[x, y];
}
return null;
}
// Métodos para manejar el intercambio de piezas
public bool IsValidPosition(int x, int y)
{
return x >= 0 && x < width && y >= 0 && y < height;
}
public bool CanSwap()
{
return !isSwapping && !isProcessingMatches;
}
public void SwapPieces(int x1, int y1, int x2, int y2)
{
if (isSwapping || isProcessingMatches)
return;
isSwapping = true;
Piece piece1 = grid[x1, y1];
Piece piece2 = grid[x2, y2];
// Actualizar la matriz y las posiciones de las piezas
grid[x1, y1] = piece2;
grid[x2, y2] = piece1;
piece1.SetPosition(x2, y2);
piece2.SetPosition(x1, y1);
// Animar el intercambio
float swapDuration = 0.25f;
Sequence swapSequence = DOTween.Sequence();
swapSequence.Append(piece1.transform.DOMove(new Vector3(x2, y2, 0), swapDuration));
swapSequence.Join(piece2.transform.DOMove(new Vector3(x1, y1, 0), swapDuration));
swapSequence.OnComplete(() =>
{
StartCoroutine(AfterSwapMatchesCheck(x1, y1, x2, y2));
});
}
IEnumerator AfterSwapMatchesCheck(int x1, int y1, int x2, int y2)
{
// Resetear marcas y buscar combinaciones
ResetMatchedFlags();
FindAllMatches();
List<Piece> matchedPieces = GetAllMatchedPieces();
if (matchedPieces.Count > 0)
{
// Hay combinaciones, procesar normalmente
isProcessingMatches = true;
yield return StartCoroutine(DestroyAndCollapseMatches());
isProcessingMatches = false;
isSwapping = false;
}
else
{
// No hay combinaciones, revertir el intercambio
Piece piece1 = grid[x1, y1];
Piece piece2 = grid[x2, y2];
grid[x1, y1] = piece2;
grid[x2, y2] = piece1;
piece1.SetPosition(x1, y1);
piece2.SetPosition(x2, y2);
float swapDuration = 0.25f;
Sequence swapBackSequence = DOTween.Sequence();
swapBackSequence.Append(piece1.transform.DOMove(new Vector3(x1, y1, 0), swapDuration));
swapBackSequence.Join(piece2.transform.DOMove(new Vector3(x2, y2, 0), swapDuration));
swapBackSequence.OnComplete(() =>
{
isSwapping = false;
});
}
}
// Método para destruir combinaciones y colapsar columnas
IEnumerator DestroyAndCollapseMatches()
{
bool needsProcessing = true;
while (needsProcessing)
{
List<Piece> matchedPieces = GetAllMatchedPieces();
if (matchedPieces.Count > 0)
{
// Reproducir animaciones de las piezas marcadas
foreach (Piece piece in matchedPieces)
{
piece.PlayMatchAnimation(null);
}
// Esperar la duración de la animación
yield return new WaitForSeconds(0.2f);
// Eliminar las piezas con animación
int piecesToDestroy = matchedPieces.Count;
int destroyedPieces = 0;
foreach (Piece piece in matchedPieces)
{
piece.PlayDestroyAnimation(() =>
{
Destroy(piece.gameObject);
destroyedPieces++;
});
}
// Esperar a que todas las piezas sean destruidas
yield return new WaitUntil(() => destroyedPieces == piecesToDestroy);
// Eliminar referencias de las piezas en la matriz
foreach (Piece piece in matchedPieces)
{
grid[piece.GetX(), piece.GetY()] = null;
}
// Hacer que las piezas caigan
yield return StartCoroutine(CollapseColumns());
// Rellenar el tablero con nuevas piezas
yield return StartCoroutine(RefillBoard());
// Resetear las marcas y buscar nuevas combinaciones
ResetMatchedFlags();
FindAllMatches();
}
else
{
needsProcessing = false;
}
}
// Finalizar el proceso
isSwapping = false;
}
// Resto de los métodos existentes (FindAllMatches, ResetMatchedFlags, CheckHorizontalMatches, CheckVerticalMatches, GetAllMatchedPieces, CollapseColumns, RefillBoard) permanecen sin cambios
// Ejemplo de uno de ellos:
void FindAllMatches()
{
ResetMatchedFlags();
CheckHorizontalMatches();
CheckVerticalMatches();
}
// ... (continúa con los demás métodos)
}