JS实现贪吃蛇

更新日期: 2019-05-18阅读: 2.4k标签: 游戏

贪吃蛇游戏是一款经典的益智游戏,有PC和手机等多平台版本。既简单又耐玩。该游戏通过控制蛇头方向吃蛋,从而使得蛇变得越来越长。下面使用js来实现贪吃蛇的游戏


把以下代码保存成Snake.html文件,使用Google或360浏览器打开 :

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8" />
  <title>Snake</title>
<style>
</style>
</head>

<body>
<div style="position: relative">

  <div style="width: 400px; font-size: 22px; border: 3px solid black;">
    分数:<span id="score"></span>
  </div>

  <canvas id="myCanvas">your browser does not support the canvas</canvas>

  <div id="help" style="position: absolute; left: 420px; top: 40px;">
    Esc: 重新开始</br>
    Enter: 开始/暂停/继续</br>
    方向键: 改变蛇的移动方向</br>
    Ctrl: 切换控制模式(影响手感)</br>
    数字1: 加速</br>
    数字2: 减速</br>
  </div>

  <div id="gameStates" style="position: absolute; left: 420px; top: 200px; color: red">
    控制模式: <span id="controlMode"></span></br>
    运动状态: <span id="pause"></span></br>
    蛇的方向: <span id="snakeDir"></span></br>
    蛇的速度: <span id="snakeSpeed"></span></br>
    蛇的长度: <span id="snakeLength"></span></br>
    <span id="info"></span>
  </div>

</div>
</body>

<script type="text/javascript">
/*
 By Problue,2015.10.15
*/
var KEY_L = 37;
var KEY_U = 38;
var KEY_R = 39;
var KEY_D = 40;
var KEY_RESET = 27 
var KEY_PAUSE = 13;
var KEY_CHANGE_CONTROL_MODE = 17;
var KEY_INC_SPEED = 49;
var KEY_DEC_SPEED = 50;
var MAP_R = 20;
var MAP_C = 20;
var SNAKE_LENGTH_MAX = MAP_R * MAP_C;
var OBJ_SIZE = 20;
var OBJ = {
  EMPTY: 0,
  SNAKE_HEAD: 1,
  SNAKE_BODY: 2,
  SNAKE_TAIL: 3,
  FOOD: 4,
  STONE: 5
};
var colors = ['white', 'midnightblue', 'darkblue', 'mediumblue', 'midnightblue', 'dimgray'];

var mapData = "0000000000000000000000000000000000000000000000000000000000005000000050000005500000000000000000005000000550000000055000000005000000000050000000000550000550000000000005000000500000000000000000000000000000000000000000000000000000050000500000000000000550055000000000000500000000500000000005500000055000000005000000000000000000055000000000050005000000000000000000000000000000000000000000000000000000000000";

var map = [];

var snake = new Snake();
var food = new Point(0, 0);
//var time;

var pause;
var over;
var controlQueueMode;
var controlQueue = new Queue();
var score;

function Snake() {
  this.nodes = [];
  this.dir = 0;
  this.msSpeed = 0;
}

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.clone = function() {
  return new Point(this.x, this.y);
}

Point.prototype.equals = function(other) {
  if(other === this)
    return true;
  if(!(other instanceof Point))
    return false;
  return this.x == other.x && this.y == other.y;
}

function Queue() {
  this.arr = [];
  this.head = 0;
  this.tail = 0;
}

Queue.prototype.enQueue = function(elem) {
  this.tail++;
  this.arr[this.tail] = elem;
}

Queue.prototype.deQueue = function() {
  this.head++;
  return this.arr[this.head];
}

Queue.prototype.empty = function() {
  return this.head >= this.tail;
}

Queue.prototype.clear = function() {
  this.arr.length = 0;
  this.head = 0;
  this.tail = 0;
}

start();

function start() {
  initGame();
  initMap();
  initSnake();
  drawMap();
  showGameStates();
  updateScore();
  drawSnake();
  randFood();
  drawObj(food, OBJ.FOOD);
}

function initGame() {
  canvas = document.getElementById('myCanvas');
  cxt = canvas.getContext('2d');
  canvas.width = MAP_C * OBJ_SIZE;
  canvas.height = MAP_R * OBJ_SIZE;
  canvas.style.border = '3px solid black';
  document.onkeydown = keydown;
  //time = +new Date;
  pause = true;
  over = 0;
  controlQueueMode = true;
  score = 0;
}

function initMap() {
  for(var r = 0; r < MAP_R; r++) {
    map.push([]);
    for(var c = 0; c < MAP_C; c++) {
      var obj = mapData[r * MAP_C + c] - 0;
      map[r][c] = obj;
    }
  }
}

function initSnake() {
  snake.nodes.length = 0;
  snake.nodes.push(new Point(2, 0));
  snake.nodes.push(new Point(1, 0));
  snake.nodes.push(new Point(0, 0));
  snake.dir = KEY_R;
  snake.msSpeed = 150;
}

function keydown(event) {
  var key = window.event ? event.keyCode : event.which;
  switch(key) {
  case KEY_U:
    if(snake.dir != KEY_D) {
      snake.dir = key;
      controlQueue.enQueue(snake.dir);
    }
    break;
  case KEY_D:
    if(snake.dir != KEY_U) {
      snake.dir = key;
      controlQueue.enQueue(snake.dir);
    }
    break;
  case KEY_L:
    if(snake.dir != KEY_R) {
      snake.dir = key;
      controlQueue.enQueue(snake.dir);
    }
    break;
  case KEY_R:
    if(snake.dir != KEY_L) {
      snake.dir = key;
      controlQueue.enQueue(snake.dir);
    }
    break;
  case KEY_RESET:
    start();
    break;
  case KEY_PAUSE:
    pause = !pause;
    if(!pause) {
      controlQueue.clear();
      move();
    }
    break;
  case KEY_CHANGE_CONTROL_MODE:
    controlQueueMode = !controlQueueMode;
    controlQueue.clear();
    break;
  case KEY_INC_SPEED:
    snake.msSpeed -= 10;
    break;
  case KEY_DEC_SPEED:
    snake.msSpeed += 10;
    break;
  default: ;
  }
  showGameStates();
}

function moveStep() {
  showGameStates();
  var newHead = snake.nodes[0].clone();
  var oldTail = snake.nodes[snake.nodes.length - 1].clone();

  switch(snake.dir) {
  case KEY_U:
    newHead.y--;
    break;
  case KEY_R:
    newHead.x++;
    break;
  case KEY_L:
    newHead.x--;
    break;
  case KEY_D:
    newHead.y++;
    break;
  }

  var coord = '坐标(' + snake.nodes[0].x + ',' + snake.nodes[0].y + ')是';
  info(coord + '空');
  if((newHead.x > MAP_C - 1 || newHead.x < 0) ||
     (newHead.y > MAP_R - 1 || newHead.y < 0)) {
    info(coord + '墙壁');
    over = 1;
    return;
  }

  if(isInSnake(newHead)) {
    info(coord + '自己');
    over = 2;
    return;
  }
  
  var thing = map[newHead.y][newHead.x];

  if(thing == OBJ.STONE) {
    info(coord + '石头');
    over = 3;
    return;
  }
  
  if(thing == OBJ.FOOD) {
    info(coord + '食物');
    snake.nodes.push(new Point(0, 0));
    map[newHead.y][newHead.x] = OBJ.EMPTY;
    randFood();
    drawObj(food, OBJ.FOOD);
    updateScore();
    showGameStates();
  }

  for(var i = snake.nodes.length - 1; i >= 1; i--)
    snake.nodes[i] = snake.nodes[i - 1].clone();
  snake.nodes[0] = newHead;
  drawObj(oldTail, OBJ.EMPTY);
  drawSnake();
}

function move() {
  if(pause)
    return;

  if(controlQueueMode && !controlQueue.empty())
    snake.dir = controlQueue.deQueue();

  moveStep();

  if(over) {
    over = 0;
    var turn = [];
    turn[KEY_U] = KEY_R;
    turn[KEY_D] = KEY_L;
    turn[KEY_L] = KEY_U;
    turn[KEY_R] = KEY_D;
    snake.dir = turn[snake.dir];
  }

  setTimeout(move, snake.msSpeed);
}

function isInSnake(point) {
  for(var i = 0; i < snake.nodes.length; i++)
    if(snake.nodes[i].equals(point))
      return true;
  return false;
}

function randFood() {
  function randInt(n, m) {
    return Math.floor(Math.random() * (m - n)) + n;
  }
  function smart(pt) {
    if(pt.x == snake.nodes[0].x) {
      if(snake.dir == KEY_U)
        return pt.x - snake.nodes[0].x < 0;
      if(snake.dir == KEY_D)
        return pt.x - snake.nodes[0].x > 0;
    }
    if(pt.y == snake.nodes[0].y) {
      if(snake.dir == KEY_L)
        return pt.y - snake.nodes[0].y < 0;
      if(snake.dir == KEY_R)
        return pt.y - snake.nodes[0].y > 0;
    }
    return false;
  }
  do
  {
    food.x = randInt(0, MAP_C);
    food.y = randInt(0, MAP_R);
  } while(isInSnake(food) || smart(food) ||
    map[food.y][food.x] != OBJ.EMPTY);
  map[food.y][food.x] = OBJ.FOOD;
}

function info(str) {
  $('info').innerHTML = str;
}

function showGameStates() {
  $('pause').innerHTML = pause ? '静止' : '移动';
  $('controlMode').innerHTML = controlQueueMode ? '队列' : '普通';
  var toText = [];
  toText[KEY_L] = '左';
  toText[KEY_U] = '上';
  toText[KEY_R] = '右';
  toText[KEY_D] = '下';
  $('snakeDir').innerHTML = toText[snake.dir];
  $('snakeSpeed').innerHTML = snake.msSpeed + 'ms/' + OBJ_SIZE + 'px';
  $('snakeLength').innerHTML = snake.nodes.length;
}

function updateScore() {
  $('score').innerHTML = score++;
}


function drawMap() {
  var pt = new Point(0, 0);
  for(var r = 0; r < MAP_R; r++) {
    for(var c = 0; c < MAP_C; c++) {
      if(map[r][c] == OBJ.STONE) {
        pt.x = c;
        pt.y = r;
        drawObj(pt, OBJ.STONE);
      }
    }
  }
}

function drawSnake() {
  drawObj(snake.nodes[0], OBJ.SNAKE_HEAD);
  for(var i = 1; i < snake.nodes.length - 1; i++)
    drawObj(snake.nodes[i], OBJ.SNAKE_BODY);
  drawObj(snake.nodes[snake.nodes.length - 1], OBJ.SNAKE_TAIL);
}

function drawObj(point, type) {
  cxt.fillStyle = colors[type];
  cxt.fillRect(point.x * OBJ_SIZE, point.y * OBJ_SIZE,
    OBJ_SIZE, OBJ_SIZE);
}

function $(id) {
  return document.getElementById(id);
}
</script>

</html>


链接: https://fly63.com/article/detial/3363

如何使用SVG动画来制作游戏

在使用过一段时间的SVG动画之后,我相当清楚如何利用它来制作动画片段或者网页布局。一些动画库平台,例如Greensock,和原生的CSS动画简直是绝配。于是我便打算深入地研究一下,看看我能否用这些来制作一款简单的游戏

web游戏框架有哪些?_h5游戏开发引擎推荐

随着浏览器功能越来越强大,在网页端实现各种小游戏已经是家常便饭。微信小游戏出现后,游戏(特别是小型游戏)的开发已经进入了一个相当火爆的时期。那么作为一个普通的前端开发者,如何取选择一个合适的游戏开发框架来学习和提高开发效率呢?

three.js中物体旋转实践之房门的打开与关闭

看这篇博客,默认你已经知道了3D模型实现三维空间内旋转的实现方式(矩阵、欧拉角、四元数)。ok,下面正式切入主题,房门的打开和关闭,先上图:

js实现贪吃蛇小游戏

需要用到html、css、javascript 和 DOM 这些知识点就可以了。主要是js,其他只是一些基本的知识。js貌似也不是很难。但是问题就在这里,即使知识点都会了,但是还是无法综合运用把东西做出来

JS实现俄罗斯方块

《俄罗斯方块》的基本规则是移动、旋转和摆放游戏自动输出的各种方块,使之排列成完整的一行或多行并且消除得分。 下面使用js来实现俄罗斯方块

HTML5+Js实现拼图小游戏

当时初学游戏开发,经验浅薄,所以没有好好专研游戏里的算法和代码的缺陷,导致游戏出现了很多bug,甚至拼图打乱后很可能无法复原。最近经常有朋友问起这个游戏,希望我能把代码里的bug改一下方便初学者学习

html5游戏引擎有哪些?如何选择

如果您是游戏开发人员,并且正在寻找JavaScript和HTML5无缝协作的游戏引擎。 虽然市场上有很多免费和付费的游戏引擎,但一款让专业游戏开发者满意的游戏引擎,必须包含独特的东西

原生JavaScript实现贪吃蛇游戏

创建JavaScript贪吃蛇游戏需要使用 HTML 制作结构,使用 CSS 制作样式,使用 JavaScript 制作游戏逻辑。下面是一个简单的贪吃蛇游戏示例:

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!