微信小程序落实的贪吃蛇游戏【附源码下载】,贪吃蛇源码下载

贪吃蛇是独非常简单的嬉戏,适合练手。

微信小序落实的贪吃蛇游戏【附源码下载】,贪吃蛇源码下载

本文实例讲述了微信小序落实之贪吃蛇游戏。分享给大家供大家参考,具体如下:

先来探视运行效果:

图片 1

现实代码如下:

界面布局 pages/snake/snake/snake.wxml:

<!--snake.wxml-->
<view class="control" bindtouchstart="tapStart" bindtouchmove="tapMove" bindtouchend="tapEnd">
<view class="score">
  <view class="title">snake</view>
  <view class="scoredetail">
    <view class="scoredesc">得分</view>
    <view class="scorenumber">{{score}}</view>
  </view>
  <view class="scoredetail">
    <view class="scoredesc">历史最高</view>
    <view class="scorenumber">{{maxscore}}</view>
  </view>
</view>
<view class="ground">
  <view wx:for="{{ground}}" class="rows" wx:for-item="cols">
    <view wx:for="{{cols}}" class="block block_{{item}}" >
    </view>
  </view>
</view>
<modal class="modal" hidden="{{modalHidden}}" no-cancel bindconfirm="modalChange">
 <view> 游戏结束,重新开始吗? </view>
</modal>
</view>

逻辑功能 pages/snake/snake/snake.js:

//snake.js
var app = getApp();
Page({
  data:{
    score: 0,//比分
    maxscore: 0,//最高分
    startx: 0,
    starty: 0,
    endx:0,
    endy:0,//以上四个做方向判断来用
    ground:[],//存储操场每个方块
    rows:28,
    cols:22,//操场大小
    snake:[],//存蛇
    food:[],//存食物
    direction:'',//方向
    modalHidden: true,
    timer:''
  } ,
  onLoad:function(){
    var maxscore = wx.getStorageSync('maxscore');
    if(!maxscore) maxscore = 0
    this.setData({
    maxscore:maxscore
    });
    this.initGround(this.data.rows,this.data.cols);//初始化操场
    this.initSnake(3);//初始化蛇
    this.creatFood();//初始化食物
    this.move();//蛇移动
  },
  //计分器
  storeScore:function(){
   if(this.data.maxscore < this.data.score){
   this.setData({
    maxscore:this.data.score
    })
    wx.setStorageSync('maxscore', this.data.maxscore)
   }
 },
 //操场
  initGround:function(rows,cols){
    for(var i=0;i<rows;i++){
      var arr=[];
      this.data.ground.push(arr);
      for(var j=0;j<cols;j++){
        this.data.ground[i].push(0);
      }
    }
  },
  //蛇
  initSnake:function(len){
    for(var i=0;i<len;i++){
      this.data.ground[0][i]=1;
      this.data.snake.push([0,i]);
    }
  },
  //移动函数
  move:function(){
    var that=this;
    this.data.timer=setInterval(function(){
      that.changeDirection(that.data.direction);
      that.setData({
        ground:that.data.ground
      });
    },400);
  },
  tapStart: function(event){
    this.setData({
      startx: event.touches[0].pageX,
      starty: event.touches[0].pageY
      })
  },
  tapMove: function(event){
    this.setData({
      endx: event.touches[0].pageX,
      endy: event.touches[0].pageY
      })
  },
  tapEnd: function(event){
    var heng = (this.data.endx) ? (this.data.endx - this.data.startx) : 0;
    var shu = (this.data.endy) ? (this.data.endy - this.data.starty) : 0;
    if(Math.abs(heng) > 5 || Math.abs(shu) > 5){
      var direction = (Math.abs(heng) > Math.abs(shu)) ? this.computeDir(1, heng):this.computeDir(0, shu);
      switch(direction){
      case 'left':
        if(this.data.direction=='right')return;
        break;
      case 'right':
        if(this.data.direction=='left')return;
        break;
      case 'top':
        if(this.data.direction=='bottom')return;
        break;
      case 'bottom':
        if(this.data.direction=='top')return;
        break;
      default:
    }
    this.setData({
    startx:0,
    starty:0,
    endx:0,
    endy:0,
    direction:direction
    })
  }
  },
  computeDir: function(heng, num){
  if(heng) return (num > 0) ? 'right' : 'left';
  return (num > 0) ? 'bottom' : 'top';
  },
  creatFood:function(){
    var x=Math.floor(Math.random()*this.data.rows);
    var y=Math.floor(Math.random()*this.data.cols);
    var ground= this.data.ground;
    ground[x][y]=2;
    this.setData({
      ground:ground,
      food:[x,y]
    });
  },
  changeDirection:function(dir){
    switch(dir){
    case 'left':
      return this.changeLeft();
      break;
    case 'right':
      return this.changeRight();
      break;
    case 'top':
      return this.changeTop();
      break;
    case 'bottom':
      return this.changeBottom();
      break;
    default:
    }
  },
  changeLeft:function(){
    var arr=this.data.snake;
    var len=this.data.snake.length;
    var snakeHEAD=arr[len-1][1];
    var snakeTAIL=arr[0];
    var ground=this.data.ground;
    ground[snakeTAIL[0]][snakeTAIL[1]]=0; 
    for(var i=0;i<len-1;i++){
        arr[i]=arr[i+1];  
    };
    var x=arr[len-1][0];
    var y=arr[len-1][1]-1;
    arr[len-1]=[x,y];
      this.checkGame(snakeTAIL);
    for(var i=1;i<len;i++){
      ground[arr[i][0]][arr[i][1]]=1;
    } 
  this.setData({
        ground:ground,
      snake:arr
    });
    return true;
  },
  changeRight:function(){
    var arr=this.data.snake;
    var len=this.data.snake.length;
    var snakeHEAD=arr[len-1][1];
    var snakeTAIL=arr[0];
    var ground=this.data.ground;
    ground[snakeTAIL[0]][snakeTAIL[1]]=0; 
    for(var i=0;i<len-1;i++){
        arr[i]=arr[i+1];  
    };
    var x=arr[len-1][0];
    var y=arr[len-1][1]+1;
    arr[len-1]=[x,y];
    this.checkGame(snakeTAIL);
    for(var i=1;i<len;i++){
      ground[arr[i][0]][arr[i][1]]=1;
    } 
    this.setData({
        ground:ground,
      snake:arr
    });
  //  var y=this.data.snake[0][1];
  //  var x=this.data.snake[0][0];
  //   this.data.ground[x][y]=0;
  //   console.log(this.data.ground[x]);
  //   console.log(this.data.snake);
  //   for(var i=0;i<this.data.snake.length-1;i++){
  //     this.data.snake[i]=this.data.snake[i+1];
  //   }
  //   this.data.snake[this.data.snake.length-1][1]++;
  //   for(var j=1;j<this.data.snake.length;j++){
  //     this.data.ground[this.data.snake[j][0]][this.data.snake[j][1]]=1;
  //   }
    return true;
  },
  changeTop:function(){
    var arr=this.data.snake;
    var len=this.data.snake.length;
    var snakeHEAD=arr[len-1][1];
    var snakeTAIL=arr[0];
    var ground=this.data.ground;
    ground[snakeTAIL[0]][snakeTAIL[1]]=0; 
    for(var i=0;i<len-1;i++){
        arr[i]=arr[i+1];  
    };
    var x=arr[len-1][0]-1;
    var y=arr[len-1][1];
    arr[len-1]=[x,y];
      this.checkGame(snakeTAIL);
    for(var i=1;i<len;i++){
      ground[arr[i][0]][arr[i][1]]=1;
    } 
    this.setData({
      ground:ground,
      snake:arr
    });
    return true;
  },
  changeBottom:function(){
    var arr=this.data.snake;
    var len=this.data.snake.length;
    var snakeHEAD=arr[len-1];
    var snakeTAIL=arr[0];
    var ground=this.data.ground;
    ground[snakeTAIL[0]][snakeTAIL[1]]=0; 
    for(var i=0;i<len-1;i++){
        arr[i]=arr[i+1];  
    };
    var x=arr[len-1][0]+1;
    var y=arr[len-1][1];
    arr[len-1]=[x,y];
    this.checkGame(snakeTAIL);
    for(var i=1;i<len;i++){
      ground[arr[i][0]][arr[i][1]]=1;
    } 
    this.setData({
      ground:ground,
      snake:arr
    });
    return true;
  },
  checkGame:function(snakeTAIL){
    var arr=this.data.snake;
    var len=this.data.snake.length;
    var snakeHEAD=arr[len-1];
    if(snakeHEAD[0]<0||snakeHEAD[0]>=this.data.rows||snakeHEAD[1]>=this.data.cols||snakeHEAD[1]<0){
        clearInterval(this.data.timer);
          this.setData({
          modalHidden: false,
            }) 
    }
    for(var i=0;i<len-1;i++){
      if(arr[i][0]==snakeHEAD[0]&&arr[i][1]==snakeHEAD[1]){
        clearInterval(this.data.timer);
          this.setData({
            modalHidden: false,
          })
      }
    }
    if(snakeHEAD[0]==this.data.food[0]&&snakeHEAD[1]==this.data.food[1]){
      arr.unshift(snakeTAIL);
      this.setData({
        score:this.data.score+10
      });
      this.storeScore();
      this.creatFood();
    }
  },
  modalChange:function(){
  this.setData({
      score: 0,
    ground:[],
    snake:[],
      food:[],
      modalHidden: true,
      direction:''
  })
  this.onLoad();
  }
});

附:总体实例源码点击这里本站下载

意在本文所述对大家微信小程序支付具有助。

http://www.bkjia.com/Javascript/1261116.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javascript/1261116.htmlTechArticle微信小程序实现的贪吃蛇游戏【附源码下载】,贪吃蛇源码下载
本文实例讲述了微信小序落实之贪吃蛇游戏。分享给大家供大家参考,具…

率先分析一下以此玩

1、蛇怎么画?

蛇是出于一个个聊方块构成的,那么我们得为此一个
list 记录每一个略带方块的坐标,显示的当儿将有所小方片写出即可。

2、蛇怎么动?

率先反馈就想蚯蚓蠕动一样,每一个方向前移动一格,但诸如此类做很麻烦,仔细思量生,其实除了头尾,蛇的别有向就从未动过,那便简单了,将下一格的坐标添加到
list 开头,并移除 list 的末尾一个因素,就一定给蛇向前移动了一格。

3、如何判断游戏了?

蛇移动过了游戏区的限定要遇到了和谐就算是输了,超出范围很轻看清,碰到自己也便于,只要判断下一格的坐标是否曾经包含在蛇的
list 中尽管足以了。

 

经纪清了这些问题,我们不怕可初步编码了。

事先看一下自我的玩乐截图

图片 2

 

本例中,回车键:开始玩,空格键:暂停 /
继续,方向键 或 WSAD 键:控制移动方向。

列吃一个食物加10分,每多100瓜分快加速一级,没有安装关卡,我玩至1100分,速度极其抢了,然后便
GAME OVER 了

"""贪吃蛇"""

import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 480
SIZE = 20


def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
    imgText = font.render(text, True, fcolor)
    screen.blit(imgText, (x, y))


def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('贪吃蛇')

    light = (100, 100, 100)  # 蛇的颜色
    dark = (200, 200, 200)   # 食物颜色

    font1 = pygame.font.SysFont('SimHei', 24)  # 得分的字体
    font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
    red = (200, 30, 30)                 # GAME OVER 的字体颜色
    fwidth, fheight = font2.size('GAME OVER')
    line_width = 1                      # 网格线宽度
    black = (0, 0, 0)                   # 网格线颜色
    bgcolor = (40, 40, 60)              # 背景色

    # 方向,起始向右
    pos_x = 1
    pos_y = 0
    # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
    # b 变量就是用于防止这种情况的发生
    b = True
    # 范围
    scope_x = (0, SCREEN_WIDTH // SIZE - 1)
    scope_y = (2, SCREEN_HEIGHT // SIZE - 1)
    # 蛇
    snake = deque()
    # 食物
    food_x = 0
    food_y = 0

    # 初始化蛇
    def _init_snake():
        nonlocal snake
        snake.clear()
        snake.append((2, scope_y[0]))
        snake.append((1, scope_y[0]))
        snake.append((0, scope_y[0]))

    # 食物
    def _create_food():
        nonlocal food_x, food_y
        food_x = random.randint(scope_x[0], scope_x[1])
        food_y = random.randint(scope_y[0], scope_y[1])
        while (food_x, food_y) in snake:
            # 为了防止食物出到蛇身上
            food_x = random.randint(scope_x[0], scope_x[1])
            food_y = random.randint(scope_y[0], scope_y[1])

    _init_snake()
    _create_food()

    game_over = True
    start = False       # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
    score = 0           # 得分
    orispeed = 0.5      # 原始速度
    speed = orispeed
    last_move_time = None
    pause = False       # 暂停

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_RETURN:
                    if game_over:
                        start = True
                        game_over = False
                        b = True
                        _init_snake()
                        _create_food()
                        pos_x = 1
                        pos_y = 0
                        # 得分
                        score = 0
                        last_move_time = time.time()
                elif event.key == K_SPACE:
                    if not game_over:
                        pause = not pause
                elif event.key in (K_w, K_UP):
                    # 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER
                    if b and not pos_y:
                        pos_x = 0
                        pos_y = -1
                        b = False
                elif event.key in (K_s, K_DOWN):
                    if b and not pos_y:
                        pos_x = 0
                        pos_y = 1
                        b = False
                elif event.key in (K_a, K_LEFT):
                    if b and not pos_x:
                        pos_x = -1
                        pos_y = 0
                        b = False
                elif event.key in (K_d, K_RIGHT):
                    if b and not pos_x:
                        pos_x = 1
                        pos_y = 0
                        b = False

        # 填充背景色
        screen.fill(bgcolor)
        # 画网格线 竖线
        for x in range(SIZE, SCREEN_WIDTH, SIZE):
            pygame.draw.line(screen, black, (x, scope_y[0] * SIZE), (x, SCREEN_HEIGHT), line_width)
        # 画网格线 横线
        for y in range(scope_y[0] * SIZE, SCREEN_HEIGHT, SIZE):
            pygame.draw.line(screen, black, (0, y), (SCREEN_WIDTH, y), line_width)

        if game_over:
            if start:
                print_text(screen, font2, (SCREEN_WIDTH - fwidth)//2, (SCREEN_HEIGHT - fheight)//2, 'GAME OVER', red)
        else:
            curTime = time.time()
            if curTime - last_move_time > speed:
                if not pause:
                    b = True
                    last_move_time = curTime
                    next_s = (snake[0][0] + pos_x, snake[0][1] + pos_y)
                    if next_s[0] == food_x and next_s[1] == food_y:
                        # 吃到了食物
                        _create_food()
                        snake.appendleft(next_s)
                        score += 10
                        speed = orispeed - 0.03 * (score // 100)
                    else:
                        if scope_x[0] <= next_s[0] <= scope_x[1] and scope_y[0] <= next_s[1] <= scope_y[1] \
                                and next_s not in snake:
                            snake.appendleft(next_s)
                            snake.pop()
                        else:
                            game_over = True

        # 画食物
        if not game_over:
            # 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了
            pygame.draw.rect(screen, light, (food_x * SIZE, food_y * SIZE, SIZE, SIZE), 0)

        # 画蛇
        for s in snake:
            pygame.draw.rect(screen, dark, (s[0] * SIZE + line_width, s[1] * SIZE + line_width,
                                            SIZE - line_width * 2, SIZE - line_width * 2), 0)

        print_text(screen, font1, 30, 7, f'速度: {score//100}')
        print_text(screen, font1, 450, 7, f'得分: {score}')

        pygame.display.update()


if __name__ == '__main__':
    main()

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图