본문 바로가기

메모장/스네이크 게임

스네이크 게임 - 점수 카운트

스네이크가 음식을 먹었을 때 점수를 카운트하고
점수를 화면에 띄우는 코드와 설정은
유튜버 "골드메탈"님의 영상을 참고하였다.
https://www.youtube.com/watch?v=qXa7y1Que6s&t=810s

추가적으로 기존에 음식 종류가 하나이었던 것을
총 3종류로 만들고 각자 다른 점수를 배부하는 추가 작업을 진행하였다.
이 역시 유튜버 "골드메탈"님의 영상을 참고하였다.
https://www.youtube.com/watch?v=lKFka1regy8&t=601s

FoodSpawner Inspector (+게임 플레이)
ScoreText Inspector
FoodPrefab Inspector

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Food : MonoBehaviour
{
    // Point Var
    public int point;
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnFood : MonoBehaviour
{
    // Food Prefab -> Changed to Array
    public GameObject[] foodPrefab;

    // Border
    public Transform borderTop;
    public Transform borderBottom;
    public Transform borderLeft;
    public Transform borderRight;

    void Start()
    {
        // Repeat Function (function name, first delay time, repeat delay time)
        InvokeRepeating("Spawn", 3, 4);
    }

    // Spawn Food
    void Spawn()
    {
        // Food Position in Range of Border
        int x = (int)Random.Range(borderLeft.position.x, borderRight.position.x);
        int y = (int)Random.Range(borderBottom.position.y, borderTop.position.y);

        // Copy Food -> Changed to Ramdom Index
        Instantiate(foodPrefab[Random.Range(0,3)], new Vector2(x, y), Quaternion.identity);
    }
}

 

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Snake : MonoBehaviour	// SnakeMove -> Snake
{
    // Snake Movement Var
    Vector2 dir = 1 * Vector2.right;
    Vector2 dirTemp = 1 * Vector2.right;
    private float size = 1;

    // Snake Direction Var
    float h;
    float v;
    bool isHorizonMove;

    // Mobile Key Var
    int up_Value;
    int down_Value;
    int left_Value;
    int right_Value;
    bool up_Down;
    bool down_Down;
    bool left_Down;
    bool right_Down;
    bool up_Up;
    bool down_Up;
    bool left_Up;
    bool right_Up;

    // Snake Tail Var & Prefab
    List<Transform> tail = new List<Transform>();
    public GameObject tailPrefab;

    // for Check that Snake Eat
    bool ate = false;

    // for Check of Border
    bool isBorder = false;

    // Score Var
    public int score = 0;

    void Start()
    {
        InvokeRepeating("Move", 0.05f, 0.05f);
    }

    void Update()
    {
        // Move Value (PC + Mobile)
        h = Input.GetAxisRaw("Horizontal") + (right_Value + left_Value);
        v = Input.GetAxisRaw("Vertical") + (up_Value + down_Value);

        // Check Button Down & Up (PC || Mobile)
        bool hDown = Input.GetButtonDown("Horizontal") || right_Down || left_Down;
        bool vDown = Input.GetButtonDown("Vertical") || up_Down || down_Down;
        bool hUp = Input.GetButtonUp("Horizontal") || right_Up || left_Up;
        bool vUp = Input.GetButtonUp("Vertical") || up_Up || down_Up;

        // Check Horizontal Move
        if (hDown)
            isHorizonMove = true;
        else if (vDown)
            isHorizonMove = false;
        else if (hUp || vUp)
            isHorizonMove = (h != 0);

        // Determine Direction
        if (h != 0 || v != 0)
        {
            dirTemp = dir;
            dir = (isHorizonMove ? new Vector2(h, 0) : new Vector2(0, v));

            // Check Snake Direction (Reverse)
            if (dir == -dirTemp)
            {
                dir = dirTemp;
            }
        }

        // Mobile Var Init
        up_Down = false;
        down_Down = false;
        left_Down = false;
        right_Down = false;
        up_Up = false;
        down_Up = false;
        left_Up = false;
        right_Up = false;
    }

    void Move()
    {
        // Store Present Position
        Vector2 v = transform.position;

        // Check whether Front is Border or Not
        if (isBorder)
        {
            // Go Same Way
            dir = -dir;
            transform.Translate(size * dir);

            isBorder = false;
        }
        else
        {
            transform.Translate(size * dir);
        }

        // Check whether Snake Eats Food or Not
        if (ate)
        {
            // Copy the Tail in Present Position
            GameObject g = (GameObject)Instantiate(tailPrefab, v, Quaternion.identity);

            // Store the Tail
            tail.Insert(0, g.transform);

            ate = false;
        }
        // Move the Tail to the Head
        else if (tail.Count > 0)
        {
            tail.Last().position = v;

            tail.Insert(0, tail.Last());
            tail.RemoveAt(tail.Count - 1);
        }
    }

    // Button Down (Mobile)
    public void ButtonDown(string type)
    {
        switch (type)
        {
            case "U":
                up_Value = 1;
                up_Down = true;
                break;
            case "D":
                down_Value = -1;
                down_Down = true;
                break;
            case "L":
                left_Value = -1;
                left_Down = true;
                break;
            case "R":
                right_Value = 1;
                right_Down = true;
                break;
        }
    }

    // Button Up (Mobile)
    public void ButtonUp(string type)
    {
        switch (type)
        {
            case "U":
                up_Value = 0;
                up_Up = true;
                break;
            case "D":
                down_Value = 0;
                down_Up = true;
                break;
            case "L":
                left_Value = 0;
                left_Up = true;
                break;
            case "R":
                right_Value = 0;
                right_Up = true;
                break;
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        // Eat Food
        if (col.gameObject.tag == "Food")
        {
            ate = true;

            Destroy(col.gameObject);

            // Add Score
            Food foodLogic = col.gameObject.GetComponent<Food>();
            score += foodLogic.point;
        }
        else
        {

        }

        // Check Border
        if (col.gameObject.tag == "Border")
        {
            isBorder = true;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    // Snake
    public GameObject snake;
    
    // Score
    public Text scoreText;

    void Update()
    {
        // Load Score from Snake Script
        Snake snakeLogic = snake.GetComponent<Snake>();
        scoreText.text = string.Format("{0:n0}", snakeLogic.score); 
    }
}

모든 코드들을 조금씩 수정하였다.

 

궁금하신 점은 밑에 댓글 바랍니다