Develop a greedy snake in wechat games

I have also written a greedy Snake game, but it is the operation of dom. Wechat game is developed based on canvas using js syntax. In order to save trouble, we search a cannibal snake based on canvas directly on the Internet.

Thank you very much It's not gadobo's Treasure (from Jianshu)

Article address: https://www.jianshu.com/p/ba5031c20cde

However, if the author's code is to be fully used in small games, some modifications need to be made, such as the support of eval, the support of alert, the event of source code is keyboard event, and the width and height of snake is too small. I have modified the above part of the source code. The following is the directory structure and code. You can create a project and copy the code for demonstration:

Root directory:

 

js Directory:

The libs directory remains unchanged, and it will be automatically generated by fast generation;

libs Directory:

game.js

import './js/libs/weapp-adapter'
import './js/libs/symbol'

import Main from './js/main'

js/main.js

var c = canvas.getContext('2d')
console.log(canvas)


var mWidth = canvas.width; //The width of the current viewing area, that is, the width of canvas 
var mHeight = canvas.height; //The height of the current visible area, that is, the height of canvas 
var unit = 15; //Set the side length of each lattice 
var mwid = mWidth / unit; //Calculate the current number of horizontal grids 
var mhei = mHeight / unit; //Calculate the current number of vertical grids 
var point = point = {x : 0 , y : 0}; //Variable initialization to record food coordinates 
var score = 0; //Variable initialization for recording grades

//Note that this object does not change its appearance on the canvas. It is only responsible for changing the state. There are other ways to change the appearance
//Snake object
var shake = {
      startX: 3,
      //Start x coordinate
      startY: 0,
      //Start y coordinate
      currOri: 'right',
      //Initialization direction
      ori: [['left', 'right'], ['up', 'down']],
      //Opposite direction array
      oriss: ['left', 'right', 'up', 'down'],
      //All allowed directions are used to judge the validity of the direction. In the canChangeOri method
      mes: [{
        x: 3,
        y: 0
      },
      {
        x: 2,
        y: 0
      },
      {
        x: 1,
        y: 0
      }],
      //Initialize snake's body coordinates, initial length 3
      //Coordinates are lattice coordinates, non pixel coordinates
      //Add a body method
      add: function () {
        //Judge the current tail direction
        var last = this.mes[this.mes.length - 1]; //Get the last body
        var plast = this.mes[this.mes.length - 2]; //Get the last body
        var px = last.x - plast.x;
        var py = last.y - plast.y; //According to the coordinate difference between the last two bodies, calculate the direction in which the body should be added
        //Calculate new element position
        var newEle = {
          x: last.x + px,
          y: last.y + py
        }; //Create a new body
        this.mes.push(newEle); //Make the new body an array of bodies
      },
      //The following methods are similar, but the directions are different
      moveup: function () {
        var pre = this.mes[0]; //Record the coordinates of the first body, the head
        this.mes[0] = {
          x: pre.x,
          y: pre.y - 1
        }; //Let the coordinates of the head move up one grid
        this.move(pre); //Call move body method
      },
      movedown: function () {
        var pre = this.mes[0];
        this.mes[0] = {
          x: pre.x,
          y: pre.y + 1
        };
        this.move(pre);
      },
      moveleft: function () {
        var pre = this.mes[0];
        this.mes[0] = {
          x: pre.x - 1,
          y: pre.y
        };
        this.move(pre);
      },
      moveright: function () {
        var pre = this.mes[0];
        this.mes[0] = {
          x: pre.x + 1,
          y: pre.y
        };
        this.move(pre);
      },
      //Mobile body
      move: function (pre) { //The parameter is the position object of the first body, namely the head
        var tmp;
        for (var i = 1; i < this.mes.length; i++) { //Traverse every body node
          tmp = this.mes[i];
          this.mes[i] = pre;
          pre = tmp;
        } //And the left side of each node is changed into the coordinate of the previous node to achieve the goal of moving forward in sequence
      },
      //Change direction
      changeOri: function (ori) {
        if (this.oriss.indexOf(ori) == -1) { //Judge whether the direction is within the allowable direction
          return;
        }
        if (!this.canChangeOri(ori)) { //Judge whether the direction change is legal
          return;
        }
        this.currOri = ori; //If both go through, change direction
      },
      //Judge whether the direction of change is legal
      canChangeOri: function (ori) { //Parameter is direction string for example: left
        if (ori == this.currOri) { //Judge whether the direction is the current direction. If so, no operation is required
          return false;
        }
        var oris = null;
        for (var i in this.ori) { //Determine whether to change the direction to the reverse of the current direction
          if (this.ori[i].indexOf(this.currOri) != -1) {
            oris = this.ori[i];
            break;
          }
        }
        if (oris.indexOf(ori) != -1) {
          return false;
        }
        return true;
      },
      //Judge whether you have collided with yourself
      isCrashSelf: function () {
        var head = this.mes[0]; //Get header node
        for (var i = 1; i < this.mes.length; i++) { //Traverse body nodes
          if (this.mes[i].x == head.x && this.mes[i].y == head.y) { //Judge whether the head node collides with the body
            return true;
          }
        }
        return false;
      },
      //Judge whether to hit the wall
      isCrashWell: function (width, height) { //Number of cells with horizontal and vertical parameters
        var head = this.mes[0]; //Get header node
        if (head.x < 0 || head.y < 0) { //Judge whether to hit the upper left wall
          return true;
        }
        if (head.x > (width - 1) || head.y > (height - 1)) { //Judge whether to hit the right lower wall
          return true;
        }
        return false;
      },
      //Handling food
      handleAdd: function () {
        var head = this.mes[0]; //Get header node
        if (head.x == point.x && head.y == point.y) { //Determine whether the head node collides with the food node, and define the food outside
          this.add(); //Call to add body
          getPoint(); //Generate a node
          setPoint(); //Draw a node
          score++; //Bonus points
          //s.innerHTML = score; / / show score

        }
      }
}

//Generating point
function getPoint() {
  point.x = Math.floor(Math.random( ) * mwid);
  point.y = Math.floor(Math.random( ) * mhei);
}

//Draw points
function setPoint() {
      c.rect(point.x * unit, point.y * unit, unit, unit);
}

//Painting snake
function setShake() {
      for (var i = 0; i < shake.mes.length; i++) {
        //c.fullStyle = '#ffffff';
        c.strokeStyle = 'red';
        c.rect(shake.mes[i].x * unit, shake.mes[i].y * unit, unit, unit);
      }
      c.stroke();
}

//Clean screen
function clear() {
     c.clearRect(0, 0, mWidth, mHeight);
}


//Start the game
var looper=null;
function startGame() {
      clearInterval(looper); //End game main loop
      //Initialization status
      shake.mes = [{
        x: 3,
        y: 0
      },
      {
        x: 2,
        y: 0
      },
      {
        x: 1,
        y: 0
      }];
      shake.currOri = 'right';

      c.beginPath(); //Start painting brush
      getPoint(); //Setting point
      setPoint();

      setShake(); //Talking snake
      //painting
      c.stroke();

      //Game main cycle
      looper = setInterval(function () {

       //VaR method ='move '+ shake. Currori +' () '; / / call direction function
       //Eval ('shake. '+ method); / / execution direction method
       /*
         move
       */
       //ori: [['left', 'right'], ['up', 'down']],
        if (shake.currOri =="left"){
          shake.moveleft();
        } else if (shake.currOri == "right"){
          shake.moveright();
        } else if (shake.currOri == "up"){
          shake.moveup();
        } else if (shake.currOri == "down"){
          shake.movedown();
      }
      
        clear(); //Cleaning screen
        c.beginPath(); //Start drawing
        shake.handleAdd(); //Handling food
        setPoint(point); //Setting point
        setShake(); //Painting snake
        if (shake.isCrashWell(mwid, mhei)) { //Whether to hit the wall, whether to eat yourself without using. You want to call the shake.isCrashSelf method with.
          clearInterval(looper);
          //console.log('you die');
          //console.log('you die , and your score is ' + score);
          /*
          Tips
          */
          wx.showModal({
            title: 'Tips',
            content: 'Game over , Your score is ' + score,
            success: function (res) {
              if (res.confirm) {
                console.log('User click OK')
                startGame()
              } else if (res.cancel) {
                console.log('User click Cancel')
              }
            }
          })
        }
      },
      200);
}
/*
start-up
*/ 
wx.showModal({
  title: 'Tips',
  content: 'Start game or not ',
  success: function (res) {
    if (res.confirm) {
      console.log('User click OK')
      startGame()
    } else if (res.cancel) {
      console.log('User click Cancel')
    }
  }
})



//Keyboard monitoring
// window.onkeyup = function (key) {
//   var ori = '';
//   switch (key.keyCode) {
//     case 65:
//       ori = 'left';
//       break;
//     case 68:
//       ori = 'right';
//       break;
//     case 87:
//       ori = 'up';
//       break;
//     case 83:
//       ori = 'down';
//       break;
//   }
//   if (ori == '') {
//     return;
//   }
//   //Change the direction of the snake
//   shake.changeOri(ori);
// }
/*
direction
*/
var startX=0;
var startY = 0;
var moveEndX  = 0;
var moveEndY  = 0;
wx.onTouchStart(function (e) {
    //pageX
    //pageY
    //console.log(e.touches[0])
  startX = e.changedTouches[0].pageX;
  startY = e.changedTouches[0].pageY;
})

wx.onTouchMove(function (e) {
    // console.log(e.touches[0])
})

wx.onTouchEnd(function (e) {
    //console.log(e.changedTouches[0])
      moveEndX = e.changedTouches[0].pageX;
      moveEndY = e.changedTouches[0].pageY;
      var X = moveEndX - startX;
      var Y = moveEndY - startY;
      if (Math.abs(X) > Math.abs(Y) && X > 0) {
        console.log("right");
        shake.changeOri("right");
      }
      else if (Math.abs(X) > Math.abs(Y) && X < 0) {
        console.log(" left");
        shake.changeOri("left");
      }
      else if (Math.abs(Y) > Math.abs(X) && Y > 0) {
        console.log("down");
        shake.changeOri("down");
      }
      else if (Math.abs(Y) > Math.abs(X) && Y < 0) {
        console.log("up");
        shake.changeOri("up");
      }
      else {
        console.log("just touch");
      }
})

wx.onTouchCancel(function (e) {
  console.log(e.touches)
})

Effect in simulator:

You can also click the editor preview button to scan the QR code and try it.

Tags: Mobile simulator

Posted on Wed, 01 Apr 2020 14:36:26 -0700 by susrisha