using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class Cell : MonoBehaviour
{
public int x, y;
public SpriteRenderer fruit_image;
public SpriteRenderer check;
public Sprite[] fruitSprites; // 과일 스프라이트 배열
public string current_fruit = null;
enum Fruits
{
Apple,
Cherry,
Grape,
Orange,
Strawberry,
Watermelon
}
private void Start()
{
SetRandomFruitImage(); // Cell이 생성될 때 랜덤한 과일 이미지로 설정
}
// 랜덤한 과일 이미지를 설정하는 메서드
void SetRandomFruitImage()
{
if (fruitSprites.Length > 0)
{
Fruits fruit = (Fruits)Random.Range(0, System.Enum.GetValues(typeof(Fruits)).Length); // 랜덤 enum 값 선택
current_fruit = fruit.ToString(); // enum 값을 문자열로 변환하여 할당
int index = (int)fruit; // enum의 정수 값으로 인덱스 결정
fruit_image.sprite = fruitSprites[index]; // 선택된 인덱스의 과일 이미지로 설정
}
}
}
Cell.cs
using System;
using System.Collections;
using UnityEngine;
public class BoardManager : MonoBehaviour
{
public int width = 8;
public int height = 8;
public Cell cellPrefab;
public Transform boardHolder;
private Cell[,] cells;
private void Start()
{
cells = new Cell[width, height];
GenerateBoard();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(CellSelectionCoroutine());
}
}
// 보드판을 생성하는 함수
void GenerateBoard()
{
for (int x = 0; x < width; x++) // 가로 크기만큼 반복
{
for (int y = 0; y < height; y++) // 세로 크기만큼 반복
{
Cell newCell = Instantiate(cellPrefab, new Vector3(x, y, 0), Quaternion.identity); // 셀 프리팹으로부터 셀 인스턴스 생성
newCell.transform.SetParent(boardHolder, false); // 생성된 셀을 boardHolder의 자식으로 설정
newCell.x = x; // 셀의 x 위치 설정
newCell.y = y; // 셀의 y 위치 설정
newCell.name = $"Cell ({x}, {y})"; // 셀의 이름 설정
cells[x, y] = newCell; // 생성된 셀을 배열에 저장
}
}
}
private Cell firstSelectedCell = null; // 첫 번째로 선택된 셀을 저장
// 셀 선택 로직을 처리하는 코루틴
IEnumerator CellSelectionCoroutine()
{
yield return new WaitUntil(() => Input.GetMouseButtonDown(0)); // 다음 마우스 클릭까지 대기
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); // 마우스 위치에 대한 레이캐스트
if (hit.collider != null && hit.collider.gameObject.GetComponent<Cell>() != null) // 레이캐스트가 셀을 정확히 감지했는지 확인
{
Cell secondSelectedCell = hit.collider.gameObject.GetComponent<Cell>(); // 두 번째로 선택된 셀
if (firstSelectedCell == null)
{
firstSelectedCell = secondSelectedCell; // 첫 번째 셀이 null이면 현재 셀을 첫 번째 셀로 설정
firstSelectedCell.check.gameObject.SetActive(true);
}
else
{
if (IsAdjacent(firstSelectedCell, secondSelectedCell)) // 두 셀이 인접해 있는지 확인
{
SwapCells(firstSelectedCell, secondSelectedCell); // 셀 교환
yield return new WaitForSeconds(0.5f); // 0.5초 동안 대기
CheckForMatches(); // 매치 확인
firstSelectedCell.check.gameObject.SetActive(false);
}
else
{
firstSelectedCell.check.gameObject.SetActive(false);
}
firstSelectedCell = null; // 첫 번째 선택된 셀 초기화
}
}
}
// 두 셀이 인접해 있는지 확인하는 함수
bool IsAdjacent(Cell firstCell, Cell secondCell)
{
return (firstCell.x == secondCell.x && Math.Abs(firstCell.y - secondCell.y) == 1) ||
(firstCell.y == secondCell.y && Math.Abs(firstCell.x - secondCell.x) == 1);
}
// 두 셀의 위치와 속성을 교환하는 함수
void SwapCells(Cell firstCell, Cell secondCell)
{
Sprite tempSprite = firstCell.fruit_image.sprite;
firstCell.fruit_image.sprite = secondCell.fruit_image.sprite;
secondCell.fruit_image.sprite = tempSprite;
string tempFruit = firstCell.current_fruit;
firstCell.current_fruit = secondCell.current_fruit;
secondCell.current_fruit = tempFruit;
}
// 보드 전체를 순회하며 매치를 확인하는 함수
void CheckForMatches()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
CheckHorizontalMatch(x, y);
CheckVerticalMatch(x, y);
}
}
}
// 주어진 위치에서 가로 방향으로 연속 매치를 확인하는 함수
void CheckHorizontalMatch(int startX, int y)
{
string initialFruit = cells[startX, y].current_fruit;
int length = 1;
for (int x = startX + 1; x < width; x++)
{
if (cells[x, y].current_fruit == initialFruit)
{
length++;
}
else
{
break;
}
}
if (length >= 3) // 연속 매치된 셀이 3개 이상일 경우에만 로그 출력
{
Debug.Log($"Horizontal match of {length} {initialFruit} found starting at ({startX}, {y})");
}
}
// 주어진 위치에서 세로 방향으로 연속 매치를 확인하는 함수
void CheckVerticalMatch(int x, int startY)
{
string initialFruit = cells[x, startY].current_fruit;
int length = 1;
for (int y = startY + 1; y < height; y++)
{
if (cells[x, y].current_fruit == initialFruit)
{
length++;
}
else
{
break;
}
}
if (length >= 3) // 연속 매치된 셀이 3개 이상일 경우에만 로그 출력
{
Debug.Log($"Vertical match of {length} {initialFruit} found starting at ({x}, {startY})");
}
}
}
BoardManager.cs
반응형
'Games' 카테고리의 다른 글
3 Match Puzzle (3) - 인접한 퍼즐 Cell 스왑하기 (0) | 2024.03.08 |
---|---|
3 Match Puzzle (2) - 보드판 만들기 (0) | 2024.03.06 |
3 Match Puzzle (1) - 게임 규칙 사전 조사 (0) | 2024.03.06 |