欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

unity实现简单的贪吃蛇游戏

程序员文章站 2022-03-21 11:32:01
本文实例为大家分享了unity实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下satuicontroller代码using unityengine;using unityengine.ui;pu...

本文实例为大家分享了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);
    }
  }
}

代码放置如下

unity实现简单的贪吃蛇游戏

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

相关标签: unity 贪吃蛇