티스토리 뷰

아래는 유니티로 간단한 테트리스 게임을 구현하기 위한 예시 소스 코드입니다.

using UnityEngine;

public class TetrisGame : MonoBehaviour
{
    public int gridWidth = 10;
    public int gridHeight = 20;
    public float fallSpeed = 1f;
    public Transform[] spawnPoints;
    public GameObject[] tetrominoes;

    private float fallTimer;
    private GameObject currentTetromino;
    private bool gameOver = false;
    private bool[,] grid;

    private void Start()
    {
        grid = new bool[gridWidth, gridHeight];
        SpawnTetromino();
    }

    private void Update()
    {
        if (!gameOver)
        {
            fallTimer += Time.deltaTime;
            if (fallTimer >= fallSpeed)
            {
                MoveTetromino(Vector3.down);
                fallTimer = 0f;
            }

            if (Input.GetKeyDown(KeyCode.LeftArrow))
            {
                MoveTetromino(Vector3.left);
            }
            else if (Input.GetKeyDown(KeyCode.RightArrow))
            {
                MoveTetromino(Vector3.right);
            }
            else if (Input.GetKeyDown(KeyCode.UpArrow))
            {
                RotateTetromino();
            }
            else if (Input.GetKeyDown(KeyCode.DownArrow))
            {
                MoveTetromino(Vector3.down);
            }
        }
    }

    private void SpawnTetromino()
    {
        int index = Random.Range(0, tetrominoes.Length);
        currentTetromino = Instantiate(tetrominoes[index], spawnPoints[index].position, Quaternion.identity);
    }

    private void MoveTetromino(Vector3 direction)
    {
        currentTetromino.transform.position += direction;

        if (!IsValidPosition())
        {
            currentTetromino.transform.position -= direction;
            if (direction == Vector3.down)
            {
                AddToGrid();
                CheckLines();
                SpawnTetromino();

                if (!IsValidPosition())
                {
                    gameOver = true;
                    Debug.Log("Game Over");
                }
            }
        }
    }

    private void RotateTetromino()
    {
        currentTetromino.transform.Rotate(0f, 0f, 90f);

        if (!IsValidPosition())
        {
            currentTetromino.transform.Rotate(0f, 0f, -90f);
        }
    }

    private bool IsValidPosition()
    {
        foreach (Transform child in currentTetromino.transform)
        {
            Vector2 position = RoundPosition(child.position);

            if (!IsInsideGrid(position) || IsOccupied(position))
            {
                return false;
            }
        }

        return true;
    }

    private Vector2 RoundPosition(Vector2 position)
    {
        return new Vector2(Mathf.Round(position.x), Mathf.Round(position.y));
    }

    private bool IsInsideGrid(Vector2 position)
    {
        return position.x >= 0 && position.x < gridWidth && position.y >= 0;
    }

    private bool IsOccupied(Vector2 position)
    {
        return grid[(int)position.x, (int)position.y];
    }

    private void AddToGrid()
    {
        foreach (Transform child in currentTetromino.transform)
        {
            Vector2 position = RoundPosition(child.position);
            grid[(int)position.x, (int)position.y] = true;
        }
    }

    private void CheckLines()
    {
        for (int y = 0; y < gridHeight; y++)
        {
            if (IsLineFull(y))
            {
                DeleteLine(y);
                ShiftLinesDown(y + 1);
            }
        }
    }

    private bool IsLineFull(int y)
    {
        for (int x = 0; x < gridWidth; x++)
        {
            if (!grid[x, y])
            {
                return false;
            }
        }

        return true;
    }

    private void DeleteLine(int y)
    {
        for (int x = 0; x < gridWidth; x++)
        {
            Destroy(grid[x, y].gameObject);
            grid[x, y] = false;
        }
    }

    private void ShiftLinesDown(int startY)
    {
        for (int y = startY; y < gridHeight; y++)
        {
            for (int x = 0; x < gridWidth; x++)
            {
                if (grid[x, y])
                {
                    grid[x, y - 1] = true;
                    grid[x, y] = false;
                    grid[x, y - 1].position += Vector3.down;
                }
            }
        }
    }
}

위의 코드는 TetrisGame 스크립트로서 테트리스 게임의 로직을 다루고 있습니다. gridWidth와 gridHeight 변수를 통해 게임 보드의 크기를 설정하고, fallSpeed 변수로 블록이 자동으로 아래로 떨어지는 속도를 조절합니다. spawnPoints 배열은 각 테트로미노의 초기 위치를 지정하고, tetrominoes 배열은 사용될 테트로미노 프리팹을 저장합니다.

Start() 메서드에서는 초기화 작업을 수행하고, Update() 메서드에서는 사용자 입력을 감지하고 블록을 이동, 회전시킵니다. SpawnTetromino() 함수는 랜덤한 테트로미노를 생성하고, MoveTetromino() 함수는 테트로미노를 이동시킵니다. RotateTetromino() 함수는 테트로미노를 회전시킵니다. IsValidPosition() 함수는 현재 테트로미노의 위치가 유효한지 검사합니다.

게임에서 테트로미노가 한 줄을 채우면 그 줄을 삭제하고, 윗 줄들을 아래로 이동시킵니다. 이러한 로직은 CheckLines(), IsLineFull(), DeleteLine(), ShiftLinesDown() 함수들을 통해 구현됩니다.

이 예시 코드는 테트리스 게임의 핵심 로직을 담고 있으며, 더 많은 기능(점수, 레벨, 미리보기 등)을 추가하여 게임을 확장시킬 수 있습니다.

댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글