贪吃蛇源码注释过程(未完成)

一、场景搭建

1.搭建场景,如下:
在这里插入图片描述
(1).皮肤和模式使用toggle来实现运行时候二选一的效果)
步骤一,在Hierarchy界面创建俩个toggle,命名为mode 1和mode 2并在Inspector中为这两个toggle添加toggle组件,并选择其中之一取消勾选Is On,取消勾选意为在开始只有一个选择勾选
在这里插入图片描述
步骤二,新建一个空物体命名为ModeManger,将mode1和mode2拖为他的子物体,再给ModeManger添加toggle group组件,取消勾选Allow Switch Off,再将ModeManger拖入mode1 和mode 2的toggle的Group中
在这里插入图片描述
(皮肤的二选一步骤也如上)
(Touch To Start为button按钮制作,操作如下)
1.在Hierarchy界面新建一个button,在文本位置改成想要的文字(如果需要可调节按钮透明度)
2.(因开始界面和游戏界面是两个不同的场景,所以我们需要创建两个场景,命名当前场景为StartSence,游戏界面为MainSence)在file→Build Settings→点击Add Open Sences将StartSence和MainSence添加进去
在这里插入图片描述

一、foodmake

(此代码为食物生成代码)

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

public class foodmake : MonoBehaviour
{
    public GameObject foodPerfatic;
    public GameObject foodReward;
    int xlimit, ylimit; //食物生成的位置的限定值
    int xoffset; //由于地图的横向位置不对称所以会有一个偏移量。
    int x, y;
    Transform canvas; //获取画布以便设置父对象
    public Sprite[] foodSprites = new Sprite[10];//食物的种类的照片


    //单例模式
    static private foodmake _instant;
    static public foodmake Instant
    {
        get { return _instant; }
    }

    private void Awake()
    {
        _instant = this;
        canvas = GameObject.Find("Canvas").transform;//获取名字为Canvas的组件
    }

    void Start()
    {
        ylimit = 7;
        xlimit = 15;
        xoffset = 9;
        CreatFood();
    }

    // Update is called once per frame

    public void CreatFood()
    {
        x = Random.Range(-(xlimit - xoffset), xlimit) * 30;//Random.Range是前开后闭区间
        y = Random.Range(-ylimit, ylimit) * 30;
        GameObject food = Instantiate(foodPerfatic);
        food.transform.SetParent(canvas, false);//设置生成食物的父对象,并使它保持未设置父对象之前的状态(缩放,旋转,坐标等值不变)
        int index = Random.Range(0, foodSprites.Length);
        food.GetComponent<Image>().sprite = foodSprites[index];//设置食物的图片
        food.transform.localPosition = new Vector3(x, y, 0);

        bool isnoreward = Random.Range(0, 100) < 20 ? true : false;//设置有1/5的概率生成奖励
        if (isnoreward)
        {
            x = Random.Range(-(xlimit - xoffset), xlimit) * 30;
            y = Random.Range(-ylimit, ylimit) * 30;
            GameObject reward = Instantiate(foodReward);
            reward.transform.SetParent(canvas, false);

            food.transform.localPosition = new Vector3(x, y, 0);
        }
    }
}

二、GameUICtroll

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;


public class GameUICtroll : MonoBehaviour
{
    static private GameUICtroll _instant;
    static public GameUICtroll Instant
    {
        get { return _instant; }
    }

    public bool ispause = false;
    public bool isPause;
    public int grade;
    public int Length;
    public int score;
    public Text ScoreText;
    public Text LengthText;
    public Text JieDuanText;
    public Transform BGM;//用于储存游戏背景图片
    public Button pauseButton;
    public Sprite[] pauseSprite = new Sprite[2];
    public Transform PauseButton;
    private Color tempColor;
 
    private void Awake()
    {

        //如果这里不初始时间流速,那么在游戏里按了暂停在返回家,再开始游戏就还会是暂停。
        Time.timeScale = 1;
        _instant = this;

    }

    void Update()
    {
        switch (grade / 100)
        {
            case 0:
            case 1:
                break;
            case 2:
                ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);//解析一个表示颜色的字符串
                BGM.GetComponent<Image>().color = tempColor;
                JieDuanText.text = "阶段" + 2;
                break;
            case 3: 
                ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);//解析一个表示颜色的字符串
                BGM.GetComponent<Image>().color = tempColor;
                JieDuanText.text = "阶段" + 3;
                break;
            case 4:
                ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);//解析一个表示颜色的字符串
                BGM.GetComponent<Image>().color = tempColor;
                JieDuanText.text = "阶段" + 4;
                break;
            case 5:
                ColorUtility.TryParseHtmlString("#FFF3CCFF", out tempColor);
                BGM.GetComponent<Image>().color = tempColor;
                JieDuanText.text = "阶段" + 5;
                break;
            case 6 :
                break;
            default:
                ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);//解析一个表示颜色的字符串
                BGM.GetComponent<Image>().color = tempColor;
                JieDuanText.text = "无尽阶段";
                break;
        }
    }

    void Start()
    {
        isPause = false;

        grade = 0;
    }
    /// <summary>
    /// 增加分数,以及分数增加后对游戏背景和小蛇速度的处理
    /// </summary>
    /// <param name="score"></param>
    /// <param name="length"></param>
    public void AddGrade(int score = 5, int length = 1)
    {
        Length += length;
        grade += score;
        
        ScoreText.text = "分数\n" + grade;
        LengthText.text = "长度\n" + Length;

    }
    /// <summary>
    /// 暂停功能
    /// </summary>
    public void Pause()
    {
        isPause = !isPause;
        if (isPause)
        {
            PauseButton.GetComponent<Image>().sprite = pauseSprite[1];
            Time.timeScale = 0;

        }
        else
        {
            PauseButton.GetComponent<Image>().sprite = pauseSprite[0];
            Time.timeScale = 1;
        }

    }
    /// <summary>
    /// 回到游戏开始界面
    /// </summary>
    public void Hoom()
    {
        SceneManager.LoadScene("StartSence");
    }
}

三、Skip

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

public class skip : MonoBehaviour
{
    public void Skip()
    {
        SceneManager.LoadScene("MainSence");

    }
    public void SKIP()
    {
    SceneManager.LoadScene("StartSence");
     }
}

四、snake

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class snake : MonoBehaviour
{
    //move函数
    int step;//每次移动的距离
    int x, y;//蛇横纵需要移动的距离
    Vector3 HeadPosition;//储存蛇头坐标
    List<Transform> bodylist = new List<Transform>();//定义一个链表储存蛇身
    public static float speed;

    //grow函数
    public Transform bodyPrefab;//身体的预制体
    public Sprite[] bodySprite = new Sprite[2];//蛇身体的图片
    Transform canvas;//获取画布以便设置父对象

    public GameObject dieEffect;

    //death函数
    bool isDie=false;//用于判断蛇是否死亡

    private void Start()
    {
        speed = 0.5f;
        step = 20;
        InvokeRepeating("Move", 0, 0.3f);
        x = step;
        canvas = GameObject.Find("Canvas").transform;

        isDie = false;
    }
    private void Update()
    {
        if (Input.GetKey(KeyCode.W) && y != -step  && !isDie)//蛇的移动不能反向,所以需要y != -step的判断
        {
            transform.rotation = Quaternion.Euler(0, 0, 0);//按w键蛇头应该要旋转的角度
            y = step;
            x = 0;
        }
        else if (Input.GetKey(KeyCode.S) && y != step && !isDie )
        {

            transform.rotation = Quaternion.Euler(0, 0, 180);//按s键蛇头应该要旋转的角度
            y = -step;
            x = 0;
        }
        else if (Input.GetKey(KeyCode.A) && x != step  && !isDie )
        {
            transform.rotation = Quaternion.Euler(0, 0, -90);//按a键蛇头应该要旋转的角度
            y = 0;
            x = -step;
        }
        else if (Input.GetKey(KeyCode.D) && x != -step && !isDie )
        {
            transform.rotation = Quaternion.Euler(0, 0, 90);//按d键蛇头应该要旋转的角度
            y = 0;
            x = step;
        }


        if (Input.GetKeyDown(KeyCode.Space)  && !isDie )
        {
            CancelInvoke();
            InvokeRepeating("Move", 0, speed - 0.4f);
        }
        if (Input.GetKeyUp(KeyCode.Space)  && !isDie)
        {
            CancelInvoke();
            InvokeRepeating("Move", 0, speed);
        }
    }
    /// <summary>
    /// 生长
    /// </summary>
    /// <param name="collision"></param>
    void Grow()
    {
        Transform newbody = Instantiate(bodyPrefab);
        newbody.transform.SetParent(canvas, false);
        int index = bodylist.Count % 2 == 0 ? 1 : 0;
        newbody.GetComponent<Image>().sprite = bodySprite[index];//当蛇身为奇数和偶数这两种不同情况时需要设置不同的照片
        newbody.localPosition = new Vector3(2000, 2000, 0);//先把新生成的蛇身块的坐标设置为屏幕外,Move移动时自动添加到相应位置
        bodylist.Add(newbody);

    }

    void Move()
    {
        Debug.Log(transform.position);
        HeadPosition = transform.localPosition;
        transform.localPosition = new Vector3(HeadPosition.x + x, HeadPosition.y + y, HeadPosition.z);

        if (bodylist.Count > 0)
        {
            for (int i = bodylist.Count - 2; i >= 0; i--)//从后往前,依次把上一个蛇身的坐标赋值下一个
            {
                bodylist[i + 1].localPosition = bodylist[i].localPosition;
            }
            bodylist[0].localPosition = HeadPosition;//把还未移动前的蛇头坐标赋值给第一个蛇身

        }

    }

    public void death()
    {
        isDie = true;
        CancelInvoke();//取消对move函数的调用
        Instantiate(dieEffect);
        PlayerPrefs.SetInt("lastl", GameUICtroll.Instant.Length);
        PlayerPrefs.SetInt("lasts", GameUICtroll.Instant.score);
        if (PlayerPrefs.GetInt("bests",0)< GameUICtroll.Instant.score)
        {
            PlayerPrefs.SetInt("bestl", GameUICtroll.Instant.Length);
            PlayerPrefs.SetInt("bests", GameUICtroll.Instant.score);
        }
        StartCoroutine(GameOver(1.5f));
    }

    IEnumerator GameOver(float t)
    {
        yield return new WaitForSeconds(t);
        UnityEngine.SceneManagement.SceneManager.LoadScene("StartSence");

    }
    public void OnTriggerEnter2D(Collider2D collision)
    {

        if (collision.tag == "food")
        {
            Destroy(collision.gameObject);
            GameUICtroll.Instant.AddGrade();
            Grow();
            foodmake.Instant.CreatFood();

        }
        else if (collision.tag == "reward")
        {
            Destroy(collision.gameObject);
            GameUICtroll.Instant.AddGrade(Random.Range(5,15)*10);
            Grow();
        }
        else if (collision.tag == "body")
        {
            death();
        }
        else
        {
            death();

        }

    }
}

五、StartUI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class StartUI : MonoBehaviour
{

    public Toggle blue;
    public Toggle yellow;
    public Toggle broad;
    public Toggle noBroad;
    public Text LastText;
    public Text BestText;
    void Start()
    {
        //显示上次和最高的分数
        LastText.text = "上次: " + "分数 " + PlayerPrefs.GetInt("lasts") + "长度 " + PlayerPrefs.GetInt("lastl");
        BestText.text = "最高: " + "分数 " + PlayerPrefs.GetInt("bests") + "长度 " + PlayerPrefs.GetInt("bestl");

        //设置刚开始的默认皮肤和用户选择了其它皮肤游戏结束时默认还是进入游戏时选择的皮肤
        if (PlayerPrefs.GetString("sh", "sh01") == "sh01")
        {
            blue.isOn = true;

        }
        else
        {
            yellow.isOn = true;
        }

        //模式同皮肤一样
        if (PlayerPrefs.GetInt("borad", 0) == 1)
        {
            broad.isOn = true;

        }
        else
        {
            noBroad.isOn = true;
        }
    }

    //该函数连接Toggle组件,当Toggle组件isOn变化时会动态的返回Toggle组件isOn的值
    public void Blue(bool isOn)
    {
        if (isOn)
        {
            PlayerPrefs.SetString("sh", "sh01");
            PlayerPrefs.SetString("sb01", "sb0101");
            PlayerPrefs.SetString("sb02", "sb0102");
        }

    }
    public void Yellow(bool isOn)
    {
        if (isOn)
        {

            PlayerPrefs.SetString("sh", "sh02");
            PlayerPrefs.SetString("sb01", "sb0201");
            PlayerPrefs.SetString("sb02", "sb0202");
        }

    }
    public void Classica(bool isOn)
    {
        if (isOn)
        {

            PlayerPrefs.SetInt("borad", 1);

        }

    }
    public void Free(bool isOn)
    {

        if (isOn)
        {
            PlayerPrefs.SetInt("borad", 0);

        }
    }
    public void GoToGame()
    {
        SceneManager.LoadScene(1);
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值