js实现贪吃蛇小游戏 1

楔子

leetcode还是偏做题,今天临时起意,准备写一个单页面的小游戏--贪吃蛇。

纯前端完成,不需要搭建服务器,写一个html文件,直接打开即玩的。

本系列会详细介绍一下,每一步的步骤和构思方案。通俗易懂。

本编介绍前3步,后续会尽快更新。

1. 创建一个html文件

新建一个RetroSnaker.html文件,选个常用的编辑器(不行就记事本也可以)打开,补上最基础的html标签

<!DOCTYPE html>
<html>
<head>
 这里是文档的头部 ... ...
 ...
</head>
<body>
 这里是文档的主体 ... ...
 ...
</body>
</html>

2. 引入js标签,并分析场景

<script></script>

贪吃蛇游戏,我们都有接触过,主要就是一个地图、一条蛇和食物,3种对象。

用js定义以上三个类。

// 简单点,我们的地图是长方形的(有兴趣的可以考虑其他形状,最经典的应该还是长方形)
var Map = function(width, height){
 this.width = width;
 this.height = height;
}
// 蛇有个初始长度,一个初始的移动方向,一个初始的身体,一个头,然后会拥有运动的能力
var D_UP = 1, D_DOWN = 2, D_RIGHT = 3, D_LEFT = 4;
var Snaker = function(height, direction, map){
 this.direction = direction;
 // 初始身体是由长度生成的,我们假设从第二行开始,横着放
 this.body = [];
 for(var i = 0; i < height; i++){
 this.body.push([1, i]);
 }
}
Snaker.prototype.move = function(food){
 let first = this.body[0];
 if(direction === D_UP){
 first = [first[0] - 1, first[1]];
 }else if(direction === D_DOWN){
 first = [first[0] + 1, first[1]];
 }else if(direction === D_RIGHT){
 first = [first[0], first[1] + 1];
 }else{
 first = [first[0], first[1] - 1];
 }
 this.body.unshift(first);
 if(!food){
 this.body.pop();
 }
}
Snaker.prototype.isCollided = function(){
 let first = this.body[0];
 if(first[0] < 0 || first[0] >= this.map.height - 1 || first[1] < 0 || first[1] >= this.map.width - 1){
 return true;
 }
 for(var i = 1; i < this.body.length; i++){
 if(this.body[i][0] === first [0] && this.body[i][1] === first [1]){
 return true;
 }
 }
 return false;
}
// 食物先简单点,就一个位置
var Food = function(x, y){
 this.position = [x, y];
}

3.画一个棋盘的样式

<canvas id="mycanvas"></canvas>


var chess = document.getElementById("mycanvas");
 var context = chess.getContext('2d');
 var width = 15, height = 10, blockWidth = 30;
 chess.width = width * blockWidth ;
 chess.height = height * blockWidth ;
 function drawChessBoard() {
 for (var i = 0; i < width + 1; i++) {
 context.strokeStyle = "#D6D1D1";
 context.moveTo(i * blockWidth, 0);
 context.lineTo(i * blockWidth, blockWidth * height);
 context.stroke();
 }
 for (var i = 0; i < height + 1; i++) {
 context.strokeStyle = "#D6D1D1";
 context.moveTo(0, i * blockWidth);
 context.lineTo(blockWidth * width, i * blockWidth);
 context.stroke();
 }
 }
 drawChessBoard();//绘制棋盘

棋盘样式如下

举报
评论 0