unity实现简单的贪吃蛇游戏

本文实例为大家分享了unity实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下

SatUIController代码

using UnityEngine;
using UnityEngine.UI;

public class StartUIController : MonoBehaviour
{
  public Text lastText;
  public Text bestText;
  public Toggle blue;
  public Toggle yellow;
  public Toggle border;
  public Toggle noBorder;

  void Awake()
  {
    lastText.text = "上次:长度" + PlayerPrefs.GetInt("lastl", 0) + ",分数" + PlayerPrefs.GetInt("lasts", 0);
    bestText.text = "最好:长度" + PlayerPrefs.GetInt("bestl", 0) + ",分数" + PlayerPrefs.GetInt("bests", 0);
  }

  void Start()
  {
    if (PlayerPrefs.GetString("sh", "sh01") == "sh01")
    {
      blue.isOn = true;
      PlayerPrefs.SetString("sh", "sh01");
      PlayerPrefs.SetString("sb01", "sb0101");
      PlayerPrefs.SetString("sb02", "sb0102");
    }
    else
    {
      yellow.isOn = true;
      PlayerPrefs.SetString("sh", "sh02");
      PlayerPrefs.SetString("sb01", "sb0201");
      PlayerPrefs.SetString("sb02", "sb0202");
    }
    if (PlayerPrefs.GetInt("border", 1) == 1)
    {
      border.isOn = true;
      PlayerPrefs.SetInt("border", 1);
    }
    else
    {
      noBorder.isOn = true;
      PlayerPrefs.SetInt("border", 0);
    }
  }

  public void BlueSelected(bool isOn)
  {
    if (isOn)
    {
      PlayerPrefs.SetString("sh", "sh01");
      PlayerPrefs.SetString("sb01", "sb0101");
      PlayerPrefs.SetString("sb02", "sb0102");
    }
  }

  public void YellowSelected(bool isOn)
  {
    if (isOn)
    {
      PlayerPrefs.SetString("sh", "sh02");
      PlayerPrefs.SetString("sb01", "sb0201");
      PlayerPrefs.SetString("sb02", "sb0202");
    }
  }

  public void BorderSelected(bool isOn)
  {
    if (isOn)
    {
      PlayerPrefs.SetInt("border", 1);
    }
  }

  public void NoBorderSelected(bool isOn)
  {
    if (isOn)
    {
      PlayerPrefs.SetInt("border", 0);
    }
  }

  public void StartGame()
  {
    UnityEngine.SceneManagement.SceneManager.LoadScene(1);
  }
}

SnakeHead代码

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

public class SnakeHead : MonoBehaviour
{
  public List<Transform> bodyList = new List<Transform>();
  public float velocity = 0.35f;
  public int step;
  private int x;
  private int y;
  private Vector3 headPos;
  private Transform canvas;
  private bool isDie = false;

  public AudioClip eatClip;
  public AudioClip dieClip;
  public GameObject dieEffect;
  public GameObject bodyPrefab;
  public Sprite[] bodySprites = new Sprite[2];

  void Awake()
  {
    canvas = GameObject.Find("Canvas").transform;
    //通过Resources.Load(string path)方法加载资源,path的书写不需要加Resources/以及文件扩展名
    gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>(PlayerPrefs.GetString("sh", "sh02"));
    bodySprites[0] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb01", "sb0201"));
    bodySprites[1] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb02", "sb0202"));
  }

  void Start()
  {
    InvokeRepeating("Move", 0, velocity);
    x = 0;y = step;
  }

  void Update()
  {
    if (Input.GetKeyDown(KeyCode.Space) && MainUIController.Instance.isPause == false && isDie == false)
    {
      CancelInvoke();
      InvokeRepeating("Move", 0, velocity - 0.2f);
    }
    if (Input.GetKeyUp(KeyCode.Space) && MainUIController.Instance.isPause == false && isDie == false)
    {
      CancelInvoke();
      InvokeRepeating("Move", 0, velocity);
    }
    if (Input.GetKey(KeyCode.W) && y != -step && MainUIController.Instance.isPause == false && isDie == false)
    {
      gameObject.transform.localRotation = Quaternion.Euler(0, 0, 0);
      x = 0;y = step;
    }
    if (Input.GetKey(KeyCode.S) && y != step && MainUIController.Instance.isPause == false && isDie == false)
    {
      gameObject.transform.localRotation = Quaternion.Euler(0, 0, 180);
      x = 0; y = -step;
    }
    if (Input.GetKey(KeyCode.A) && x != step && MainUIController.Instance.isPause == false && isDie == false)
    {
      gameObject.transform.localRotation = Quaternion.Euler(0, 0, 90);
      x = -step; y = 0;
    }
    if (Input.GetKey(KeyCode.D) && x != -step && MainUIController.Instance.isPause == false && isDie == false)
    {
      gameObject.transform.localRotation = Quaternion.Euler(0, 0, -90);
      x = step; y = 0;
    }
  }

  void Move()
  {
    headPos = gameObject.transform.localPosition;                        //保存下来蛇头移动前的位置
    gameObject.transform.localPosition = new Vector3(headPos.x + x, headPos.y + y, headPos.z); //蛇头向期望位置移动
    if (bodyList.Count > 0)
    {
      //由于我们是双色蛇身,此方法弃用
      //bodyList.Last().localPosition = headPos;                       //将蛇尾移动到蛇头移动前的位置
      //bodyList.Insert(0, bodyList.Last());                         //将蛇尾在List中的位置更新到最前
      //bodyList.RemoveAt(bodyList.Count - 1);                        //移除List最末尾的蛇尾引用

      //由于我们是双色蛇身,使用此方法达到显示目的
      for (int i = bodyList.Count - 2; i >= 0; i--)                      //从后往前开始移动蛇身
      {
        bodyList[i + 1].localPosition = bodyList[i].localPosition;             //每一个蛇身都移动到它前面一个节点的位置
      }
      bodyList[0].localPosition = headPos;                          //第一个蛇身移动到蛇头移动前的位置
    }
  }

  void Grow()
  {
    AudioSource.PlayClipAtPoint(eatClip, Vector3.zero);
    int index = (bodyList.Count % 2 == 0) ? 0 : 1;
    GameObject body = Instantiate(bodyPrefab, new Vector3(2000, 2000, 0), Quaternion.identity);
    body.GetComponent<Image>().sprite = bodySprites[index];
    body.transform.SetParent(canvas, false);
    bodyList.Add(body.transform);
  }

  void Die()
  {
    AudioSource.PlayClipAtPoint(dieClip, Vector3.zero);
    CancelInvoke();
    isDie = true;
    Instantiate(dieEffect);
    PlayerPrefs.SetInt("lastl", MainUIController.Instance.length);
    PlayerPrefs.SetInt("lasts", MainUIController.Instance.score);
    if (PlayerPrefs.GetInt("bests", 0) < MainUIController.Instance.score)
    {
      PlayerPrefs.SetInt("bestl", MainUIController.Instance.length);
      PlayerPrefs.SetInt("bests", MainUIController.Instance.score);
    }
    StartCoroutine(GameOver(1.5f));
  }

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

  private void OnTriggerEnter2D(Collider2D collision)
  {
    if (collision.gameObject.CompareTag("Food"))
    {
      Destroy(collision.gameObject);
      MainUIController.Instance.UpdateUI();
      Grow();
      FoodMaker.Instance.MakeFood((Random.Range(0, 100) < 20) ? true : false);
    }
    else if (collision.gameObject.CompareTag("Reward"))
    {
      Destroy(collision.gameObject);
      MainUIController.Instance.UpdateUI(Random.Range(5, 15) * 10);
      Grow();
    }
    else if (collision.gameObject.CompareTag("Body"))
    {
      Die();
    }
    else
    {
      if (MainUIController.Instance.hasBorder)
      {
        Die();
      }
      else
      {
        switch (collision.gameObject.name)
        {
          case "Up":
            transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y + 30, transform.localPosition.z);
            break;
          case "Down":
            transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y - 30, transform.localPosition.z);
            break;
          case "Left":
            transform.localPosition = new Vector3(-transform.localPosition.x + 180, transform.localPosition.y, transform.localPosition.z);
            break;
          case "Right":
            transform.localPosition = new Vector3(-transform.localPosition.x + 240, transform.localPosition.y, transform.localPosition.z);
            break;
        }
      }
    }
  }
}

MainUIController

using UnityEngine;
using UnityEngine.UI;

public class MainUIController : MonoBehaviour
{
  private static MainUIController _instance;
  public static MainUIController Instance
  {
    get
    {
      return _instance;
    }
  }

  public bool hasBorder = true;
  public bool isPause = false;
  public int score = 0;
  public int length = 0;
  public Text msgText;
  public Text scoreText;
  public Text lengthText;
  public Image pauseImage;
  public Sprite[] pauseSprites;
  public Image bgImage;
  private Color tempColor;

  void Awake()
  {
    _instance = this;
  }

  void Start()
  {
    if (PlayerPrefs.GetInt("border", 1) == 0)
    {
      hasBorder = false;
      foreach (Transform t in bgImage.gameObject.transform)
      {
        t.gameObject.GetComponent<Image>().enabled = false;
      }
    }
  }

  void Update()
  {
    switch (score / 100)
    {
      case 0:
      case 1:
      case 2:
        break;
      case 3:
      case 4:
        ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
        bgImage.color = tempColor;
        msgText.text = "阶段" + 2;
        break;
      case 5:
      case 6:
        ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
        bgImage.color = tempColor;
        msgText.text = "阶段" + 3;
        break;
      case 7:
      case 8:
        ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
        bgImage.color = tempColor;
        msgText.text = "阶段" + 4;
        break;
      case 9:
      case 10:
        ColorUtility.TryParseHtmlString("#FFF3CCFF", out tempColor);
        bgImage.color = tempColor;
        msgText.text = "阶段" + 5;
        break;
      default:
        ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
        bgImage.color = tempColor;
        msgText.text = "无尽阶段";
        break;
    }
  }

  public void UpdateUI(int s = 5, int l = 1)
  {
    score += s;
    length += l;
    scoreText.text = "得分:\n" + score;
    lengthText.text = "长度:\n" + length;
  }

  public void Pause()
  {
    isPause = !isPause;
    if (isPause)
    {
      Time.timeScale = 0;
      pauseImage.sprite = pauseSprites[1];
    }
    else
    {
      Time.timeScale = 1;
      pauseImage.sprite = pauseSprites[0];
    }
  }

  public void Home()
  {
    UnityEngine.SceneManagement.SceneManager.LoadScene(0);
  }
}

FoodMaker代码

using UnityEngine;
using UnityEngine.UI;

public class FoodMaker : MonoBehaviour
{
  private static FoodMaker _instance;
  public static FoodMaker Instance
  {
    get
    {
      return _instance;
    }
  }

  public int xlimit = 21;
  public int ylimit = 11;
  public int xoffset = 7;
  public GameObject foodPrefab;
  public GameObject rewardPrefab;
  public Sprite[] foodSprites;
  private Transform foodHolder;

  void Awake()
  {
    _instance = this;
  }

  void Start()
  {
    foodHolder = GameObject.Find("FoodHolder").transform;
    MakeFood(false);
  }

  public void MakeFood(bool isReward)
  {
    int index = Random.Range(0, foodSprites.Length);
    GameObject food = Instantiate(foodPrefab);
    food.GetComponent<Image>().sprite = foodSprites[index];
    food.transform.SetParent(foodHolder, false);
    int x = Random.Range(-xlimit + xoffset, xlimit);
    int y = Random.Range(-ylimit, ylimit);
    food.transform.localPosition = new Vector3(x * 30, y * 30, 0);
    if (isReward)
    {
      GameObject reward = Instantiate(rewardPrefab);
      reward.transform.SetParent(foodHolder, false);
      x = Random.Range(-xlimit + xoffset, xlimit);
      y = Random.Range(-ylimit, ylimit);
      reward.transform.localPosition = new Vector3(x * 30, y * 30, 0);
    }
  }
}

代码放置如下

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • unity实现贪吃蛇游戏

    unity贪吃蛇基本原理实现,供大家参考,具体内容如下 原理: 1.每个身体跟着前面的身体移动: 2.蛇头自动一直向前走,可以向左或者向右转弯. 思想: 贪吃蛇的身体有若干个,每个身体有共同的特性,就是跟着前面的身体移动,这里把蛇的身体抽象出出来,用一个SnackBody类来表达,每一节身体都new出一个SnackBody对象,然后操作这个对象实现功能:蛇头可以看做特殊的蛇身体.应该有一个管理器来管理所有的蛇身体,所以有个SnackController类来管理.每段蛇身都有Front,self,

  • unity使用链表实现贪吃蛇游戏

    今天介绍一下如何利用链表结构来创建一条贪吃蛇. 要实现的功能很简单,按下空格键使蛇加长一节,每次按下空格就在蛇尾加一个cube.按下左方向键,控制蛇的移动.如图所示: //贪吃蛇的中心是:定义蛇身第一节,即链表头为temp.链表的子节点为next.蛇头带着temp(链表头)走,temp带着next(链表子节点)走. 1. 创建一个cube设为预设体,作为蛇身的节点.在预设体上面添加BodyScript脚本. using UnityEngine; using System.Collections;

  • unity实现简单贪吃蛇游戏

    本文实例为大家分享了unity实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 首先创建一个头部,编写脚本利用WASD控制头部的移动. Vector3 up=new Vector3(0,1,0); Vector3 down=new Vector3(0,-1,0); Vector3 left=new Vector3(-1,0,0); Vector3 right=new Vector3(1,0,0); Vector3 now;//头部实际前进方向 float timer=0f; float tim

  • Unity实现3D贪吃蛇的移动代码

    本文实例为大家分享了Unity实现3D贪吃蛇移动的具体代码,供大家参考,具体内容如下 记录一下前段时间写到的一个3D贪吃蛇的移动代码. 链接:Unity实现3D贪吃蛇 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { List<Transform> bodyL

  • unity实现简单的贪吃蛇游戏

    本文实例为大家分享了unity实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下 SatUIController代码 using UnityEngine; using UnityEngine.UI; public class StartUIController : MonoBehaviour { public Text lastText; public Text bestText; public Toggle blue; public Toggle yellow; public Toggle

  • javascript实现简单的贪吃蛇游戏

    javascript实现简单的贪吃蛇游戏,功能很简单,代码也很实用,就不多废话了,小伙伴们参考注释吧. <html> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8'> <title>贪吃蛇</title> <script type="text/javascript"> var map; //地图 var snake;

  • Java实现简单版贪吃蛇游戏

    本文实例为大家分享了Java实现简单版贪吃蛇游戏的具体代码,供大家参考,具体内容如下 这是一个比较简洁的小游戏,主要有三个类,一个主类,一个食物类,一个贪吃蛇类. 1.首先定义主类,主类中主要用来创建窗口 public class Main { public static final int WIDTH=600; public static final int HEIGHT=600; public static void main(String[] args) { JFrame win =new

  • 基于Pygame实现简单的贪吃蛇游戏

    目录 导入相关的包 设置屏幕大小以及基本参数 设置贪吃蛇的位置,以及移动的大小 绘制蛇 让蛇动起来 实现贪吃蛇拐弯 实现随机食物 吃食物 完整代码  导入相关的包 import pygame, sys, random from pygame.locals import * 设置屏幕大小以及基本参数 设置屏幕大小为400*400,mainClock = pygame.time.Clock()用来设置时间同步,不会根据计算机的运行来决定运行多少次, mainClock.tick(1) 一秒只会运行一

  • c++实现超简单的贪吃蛇游戏实例介绍

    目录 设计思路 实现代码 效果 设计思路         建议先将代码复制下来跑一遍再来看思路!!!         通俗易懂,请仔细看.         值得注意的是我给出的代码没有加墙体,如有需要自己添加.         也没有难度设计,同上. 地图大小(这里设计了墙体,代码中未实现) 设置一个整形数组map,其大小为1600,对应着地图的大小为1600,并初始化数组,令数组中的值全为0,0代表空地. 我们通过设定窗口的宽度为80,打印时每个map[i] 所对应的字符占两格位置即可实现每打

  • 教你用Pygame制作简单的贪吃蛇游戏

    目录 1.序言 2.安装与导入 3.定义后续需要的参数 4.绘制蛇与食物 5.游戏规则与运行 6.成品展示 7.完整代码 总结 1.序言 目前基本上软测会用到的工具或者第三方库都已经被写完,本着不要逮着一只羊进行薅羊毛原则,换个赛道,这次就使用pygame库写个简单的贪吃蛇吧,当做熟悉python练手也是不错的. 2.安装与导入 使用pip install pygame进入安装,安装成功后导入所需模块: import pygame,sys,random from pygame.locals im

  • python实现一个简单的贪吃蛇游戏附代码

    前言: 不知道有多少同学跟我一样,最初接触编程的动机就是为了自己做个游戏玩? 今天要给大家分享的是一个 pygame 写的“贪吃蛇”小游戏: “贪吃蛇”这个小游戏在编程学习中的常客,因为: 简单,最基本的游戏元素只需要蛇和食物两个就可以进行了.(打飞机还需要三个元素呢,想想分别是什么?)方向的话只要上下左右4个固定方向就可以了.有基本的数据结构和面向对象的思想在其中.游戏开发本身就会用到很多面向对象的概念,而蛇的身体又是一个天然的“链表”结构,太适合用来练习数据结构了.另外比较有趣的一点是,Py

  • C语言实现简单的贪吃蛇游戏的示例代码

    目录 运行效果 代码 一个简单的贪吃蛇游戏本来代码就不多,在保证可读性的情况下,很容易就控制在100以内了. 运行效果 代码 #include <Windows.h> #include <stdio.h> #include <conio.h> #include <time.h> #define PANIC(err) (fprintf(stderr,"PANIC Line %d : %s",__LINE__,err),exit(-1),1)

  • Java实现简单的贪吃蛇游戏

    本文实例为大家分享了Java实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下 代码 启动类 package snake; import javax.swing.*; //游戏的主启动类 public class StartGame { public static void main(String[] args) { JFrame frame = new JFrame("贪吃蛇"); frame.setBounds(10,10,900,720); frame.setResizabl

  • C语言实现简单的贪吃蛇游戏

    本文实例为大家分享了C语言实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下 用指针数组来表示蛇,p[0]表示蛇头 控制方向:w,s,a,d-->上下左右 j,k-->加速.减速 键盘控制需要用到线程 编译时需要在后面加     -lpthread 代码: #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <uni

随机推荐