貪吃蛇的小程式

2022-01-08 20:00:01

1 建立專案

1.開啟微信開發者工具如圖所示的介面,點選「+
在這裡插入圖片描述
2.填寫專案以後,點選確定即可。如圖所示:在這裡插入圖片描述

2 程式設計

1.編寫index.wxml的程式碼如下:

<view class="container">
	<canvas style="width:100%;height:100%;" canvas-id="firstCanvas" bindtouchstart="canvasStart" bindtouchmove="canvasMove" bindtouchend="canvasEnd"></canvas>
</view>

如圖所示:在這裡插入圖片描述
2.編寫index.js的程式碼如下:

//index.js貪吃蛇主程式
//獲取應用範例
var app = getApp()
//控制蛇頭當前移動的位置
var l = 0;
var t = 0;
//蛇頭的大小
var w = 10;
var h = 10;

//手指的座標
var startX = 0;
var startY = 0;
var moveEndX = 0;
var moveEndY = 0;
var X = 0;
var Y = 0;
//蛇頭移動的方向
var direction = null;
var snakeDirection = "right";
//視窗的寬度和高度
var windowWidth = 0;
var windowHeight = 0;

//存放身體的位置資訊
var snakeBodys = [];

//存放食物的位置資訊
var foods = [];

//蛇頭物件
var snakeHead = {};

//是否刪除蛇的身體
var removeBodyBol = true;

Page({
  canvasStart:function (e){
    startX = e.touches[0].x;
    startY = e.touches[0].y;
  },
  canvasMove:function (e){
    moveEndX = e.touches[0].x;
    moveEndY = e.touches[0].y;
    X = moveEndX - startX;
    Y = moveEndY - startY;

    if ( Math.abs(X) > Math.abs(Y) && X > 0 ) {
        direction = "right";
    }
    else if ( Math.abs(X) > Math.abs(Y) && X < 0 ) {
        direction = "left";
    }
    else if ( Math.abs(Y) > Math.abs(X) && Y > 0) {
        direction = "bottom";
    }
    else if ( Math.abs(Y) > Math.abs(X) && Y < 0 ) {
        direction = "top";
    }
  },
  canvasEnd:function (e){
    switch (direction){
          case "left":
            if(snakeDirection != "right"){
              snakeDirection  = direction;
            }
            
            break;
          case "right":
            if(snakeDirection != "left"){
              snakeDirection  = direction;
            }
            break;
          case "top":
            if(snakeDirection != "bottom"){
              snakeDirection  = direction;
            }
            break;
          case "bottom":
            if(snakeDirection != "top"){
              snakeDirection  = direction;
            }
            break;
      }
    console.log(snakeDirection);
  },
  onLoad: function () {

    //隨機函數
    function rand(min,max){
      return parseInt(Math.random()*(max-min)+min);
    }
    //碰撞函數
    function collide(obj1,obj2){
      
      var l1 = obj1.x;
      var r1 = l1+obj1.w;
      var t1 = obj1.y;
      var b1 = t1+obj1.h;
      
      var l2 = obj2.x;
      var r2 = l2+obj2.w;
      var t2 = obj2.y;
      var b2 = t2+obj2.h;
      
      if (r1>l2&&l1<r2&&b1>t2&&t1<b2){
        return true;
      }else{
        return false;
      }
    }

    //食物的建構函式
    function Food(){
      this.x = rand(0,windowWidth-10);
      this.y = rand(0,windowHeight-10);
      this.w = 8;
      this.h = 8;
      this.color = "rgb("+rand(0,255)+","+rand(0,255)+","+rand(0,255)+")";
      this.resetPos = function (){
        this.x = rand(0,windowWidth-10);
        this.y = rand(0,windowHeight-10);
      }
    }

    //使用wx.createContext獲取繪圖上下文context
    var context = wx.createContext();
    
    var frameTime = 0;

    function move(){
      switch (snakeDirection){
          case "left":
            l -= w;
            break;
          case "right":
            l += w;
            break;
          case "top":
            t -= h;
            break;
          case "bottom":
            t += h;
            break;
      }
    }
    
    function animate(){
      frameTime++;
      if (frameTime%20==0){
        
        //把上一個位置存入身體陣列
        snakeBodys.push({
          x:l,
          y:t,
          w:w,
          h:h
        });

        //控制舌頭的位置移動
        move();

        //修改蛇頭物件屬性
        snakeHead = {
          x:l,
          y:t,
          w:w,
          h:h
        }
        //繪製食物
        for (var i=0; i<foods.length; i++){
          var food = foods[i];
          context.setFillStyle(food.color);
          context.beginPath();
          context.rect(food.x,food.y,food.w,food.h);
          context.closePath();
          context.fill();

          //食物跟蛇頭碰撞檢測
          if (collide(food,snakeHead)){
            console.log('裝上了');
            food.resetPos();
            removeBodyBol = false;
          }
        }

        //繪製蛇頭
        context.setFillStyle("#ff00ff");
        context.beginPath();
        context.rect(l,t,w,h);
        context.closePath();
        context.fill();

        //如果超過4截身體就刪除最老的那一截
        if (snakeBodys.length > 6){
          if (removeBodyBol){
            snakeBodys.shift();
          }else{
            removeBodyBol = true;
          }
        }

        //繪製身體
        for (var i=0; i<snakeBodys.length; i++){
          var snakeBodyObj = snakeBodys[snakeBodys.length-i-1];
          context.setFillStyle("#000000");
          context.beginPath();
          context.rect(snakeBodyObj.x,snakeBodyObj.y,snakeBodyObj.w,snakeBodyObj.h);
          context.closePath();
          context.fill();
        }
        wx.drawCanvas({
          canvasId: "firstCanvas",
          actions: context.getActions()
        });
      }
      requestAnimationFrame(animate);
    }
    //獲取頁面的寬度
    wx.getSystemInfo({
      success: function(res) {
        windowWidth = res.windowWidth;
        windowHeight = res.windowHeight;
        //在頁面中隨機初始化建立30個食物
        for (var i=0; i<30; i++){
          var foodObj = new Food();
          foods.push(foodObj);
        }
        animate();
      }
    })
  }
})

如圖所示:在這裡插入圖片描述
3.編寫index.wxss的程式碼如下:

page{
	height: 100%;
	width: 100%;
}
canvas{
	background-color: #ccc;
}

如圖所示:在這裡插入圖片描述
4.修改app.js的程式碼如圖所示:在這裡插入圖片描述