原生JS实战:经典贪吃蛇(开局10倍速度,来看看你最高能得多少分!)
本文是苏福的原创文章,转载请注明出处:苏福CNblog:http://www.cnblogs.com/susufufu/p/5875523.html
该程序是本人的个人作品,写的不好,未经本人允许,请不要用于其它用途!
贪吃蛇的游戏相信80后的朋友小时候都玩过,记得我小时候还攒了二十多块钱买了个游戏机(一个礼拜2块的零花钱!),可以玩飞机、俄罗斯方块、贪吃蛇等,刚开始玩的真过瘾,无奈太费电池,玩不起,放一段时间居然屏幕不行了!哎!
点击查看演示:
苏福的作品:贪吃蛇
body{background-color: gray}
#main{
position: absolute;
left: 0;
right: 0;
bottom: 0;
margin: auto;
top: 40px;
width: 600px;
height: 400px;
background-color: #336699;
}
#game-window{
position: absolute;
left: 0;
top: 0;
width: 600px;
height: 400px;
overflow: hidden;
}
#begin-btn{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 40px;
line-height: 40px;
font-size: 20px;
background-color: powderblue;
text-align: center;
cursor: pointer;
}
.block{
position: absolute;
left: -10px;
margin: auto;
width: 10px;
height: 10px;
background-color: powderblue;
-webkit-box-shadow: inset 0 0 1px black;
-moz-box-shadow: inset 0 0 1px black;
box-shadow: inset 0 0 1px black;
}
#snake-head{
background-color: palegreen;
}
#snake-body{
background-color: palegreen;
}
#score-info{
position: absolute;
top: -25px;
width: 100%;
height: 25px;
line-height: 25px;
background-color: powderblue;
overflow: hidden;
}
.score-info-item{
float: left;
width: 145px;
height: 25px;
margin-left: 1px;
text-align: left;
white-space: nowrap;
overflow: hidden;
}
window.onload = function () {
//====公共函数
function id(id){return document.getElementById(id)}
function getRandom(max){return Math.floor((Math.random()*max)/10)*10}
function getElemXY(elem){
return{
x:parseInt(elem.style.left),
y:parseInt(elem.style.top)
}
}
function setElemXY(elem,x,y){
elem.style.left = x+'px';
elem.style.top = y+'px';
}
function clear() {
gameWindow.innerHTML = '';
scoreInfo.innerHTML = '成绩: 0';
speedInfo.innerHTML = '速度: 5';
levelInfo.innerHTML = '等级: 1';
maxScoreInfo.innerHTML = '最高成绩: '+maxScore;
}
//====公共变量
var beginBtn = id('begin-btn'),
scoreInfo = id('score'),
speedInfo = id('speed'),
levelInfo = id('level'),
maxScoreInfo = id('max-score'),
maxScore = 0,
block = document.querySelector('.block'),
timeId,
gameWindow = id('game-window');
//====游戏入口
beginBtn.onclick = function (){
clear();
beginBtn.style.display = 'none';
var s = new Snake();
s.moving();
};
//按下方向键,改变蛇头的移动方向
document.onkeydown = function (event){
var e = event||window.event;
var key = e.keyCode;
switch (key){
case 38:
if(Snake.headDirection.x === 0){return;} //判断是否是垂直移动
Snake.headDirection.y = 1;
Snake.headDirection.x = 0;
break;
case 40:
if(Snake.headDirection.x === 0){return;}
Snake.headDirection.y = -1;
Snake.headDirection.x = 0;
break;
case 37:
if(Snake.headDirection.y === 0){return;} //判断是否是水平移动
Snake.headDirection.x = 1;
Snake.headDirection.y = 0;
break;
case 39:
if(Snake.headDirection.y === 0){return;}
Snake.headDirection.x = -1;
Snake.headDirection.y = 0;
break;
}
};
//====Snake类
var Snake = function () {
this.score = 0;
this.speed = 10;
this.levle = 0;
this.snakeHead = this.createBlock('snake-head',block);
this.snake = [this.snakeHead]; //将蛇头作为蛇体的第一个元素
this.food = this.createBlock('food',block);
};
//蛇头的移动方向,x,y的取值为-1 0 1
Snake.headDirection = {x:1,y:0};
//创建蛇节
Snake.prototype.createBlock = function (id,block) {
var bk = block.cloneNode(false),x = getRandom(600),y = getRandom(400);
bk.id = id;
setElemXY(bk,x,y);
gameWindow.appendChild(bk);
return bk;
};
//移动蛇身,并判断是否吃到食物,或吃到自己,或撞墙
Snake.prototype.moving = function () {
//吃到食物
var head = getElemXY(this.snakeHead), food = getElemXY(this.food);
if(head.x === food.x && head.y === food.y){
this.eat(this.food);
this.food = this.createBlock('food',block);
}
//撞墙
var x = Snake.headDirection.x, y = Snake.headDirection.y;
if(x === 0){
y === 1 ? head.y-=10 : head.y+=10;
if(head.y400){this.gameOver();return;}
}
if(y === 0){
x === 1 ? head.x-=10 : head.x+=10;
if(head.x600){this.gameOver();return;}
}
var len = this.snake.length;
for(var i = len-1 ; i>0 ; i--){
var nowXY = getElemXY(this.snake[i]);
if(head.x === nowXY.x && head.y === nowXY.y){this.gameOver();return;} //吃到自己
var preXY = getElemXY(this.snake[i-1]);
setElemXY(this.snake[i],preXY.x,preXY.y); //将每个蛇节都移到它的前一个的位置
}
setElemXY(this.snakeHead,head.x,head.y); //舌头移动到新位置
timeId = setTimeout(function () {
this.moving();
}.bind(this),1000/this.speed);
};
//游戏结束
Snake.prototype.gameOver = function(){
beginBtn.style.display = 'block';
clearTimeout(timeId);
timeId = null;
};
//吃食物,并更新游戏成绩
Snake.prototype.eat = function (food) {
this.levle++;
this.speed+=0.4;
this.score+=5*this.speed;
levelInfo.innerHTML = '等级: '+this.levle;
speedInfo.innerHTML = '速度: '+this.speed.toFixed(2);
scoreInfo.innerHTML = '成绩: '+this.score;
maxScore = Math.max(maxScore,this.score);
maxScoreInfo.innerHTML = '最高成绩: '+maxScore;
var oldLast = getElemXY(this.snake[this.snake.length-1]);
setElemXY(food,oldLast.x,oldLast.y);
this.snake.push(food);
};
}
</script>
开始游戏
贪吃蛇没什么游戏规则,就是转转转、吃吃吃!我就定义了一个类Snake,想用面向对象来写,不知道写的像不像!请前辈多多指点
//====Snake类
var Snake = function () {
this.score = 0;
this.speed = 10;
this.levle = 0;
this.snakeHead = this.createBlock('snake-head',block);
this.snake = [this.snakeHead]; //将蛇头作为蛇体的第一个元素
this.food = this.createBlock('food',block);
};
这个游戏的设计难点有这几个:
- 蛇的移动方向随方向键的改变
- 蛇身各个部分的移动
- 蛇身移动过程中不断的判断是否撞墙、是否吃到食物。
蛇的移动方向的改变我定义了一个静态属性Snake.headDirection = {x:1,y:0};,用来保存当前状态,x、y的取值范围为1、0、-1,x和y不会同时为零,x为零时表示当前垂直移动,可以往左(y:1)或往右(y:-1),y为零时表示水平移动,可以往上(x:1)或往下(x:-1)。为此我把方向键的事件回调函数设计成类似状态机的函数:
document.onkeydown = function (event){
var e = event||window.event;
var key = e.keyCode;
switch (key){
case 38:
if(Snake.headDirection.x === 0){return;} //判断是否是垂直移动
Snake.headDirection.y = 1;
Snake.headDirection.x = 0;
break;
case 40:
if(Snake.headDirection.x === 0){return;}
Snake.headDirection.y = -1;
Snake.headDirection.x = 0;
break;
case 37:
if(Snake.headDirection.y === 0){return;} //判断是否是水平移动
Snake.headDirection.x = 1;
Snake.headDirection.y = 0;
break;
case 39:
if(Snake.headDirection.y === 0){return;}
Snake.headDirection.x = -1;
Snake.headDirection.y = 0;
break;
}
};
下面是创建蛇头或蛇身的共有函数,因为蛇头、蛇身都是由一样的方块组成,这里我预先在HTML文件里就创建了一个方块<span class="block"></span>,通过css把它藏在标题栏的下面,然后以后碰到要创建蛇头、蛇身的时候就克隆一个并在给定随机位置后添加到游戏窗口,省的每次都运行创建元素的代码:具体看代码注释
Snake.prototype.createBlock = function (id,block) {
var bk = block.cloneNode(false),x = getRandom(600),y = getRandom(400);
bk.id = id;
setElemXY(bk,x,y); //该方法用来设置元素的lef、top
gameWindow.appendChild(bk);
return bk;
};
接下来是蛇的移动、吃食物、撞墙:当蛇头的位置等于食物的位置时,启动吃食物函数;当蛇头的下次移动的坐标在游戏窗口之外时,就判定撞墙,游戏结束;
//移动蛇身,并判断是否吃到食物,或吃到自己,或撞墙
Snake.prototype.moving = function () {
//吃到食物
var head = getElemXY(this.snakeHead), food = getElemXY(this.food);
if(head.x === food.x && head.y === food.y){
this.eat(this.food);
this.food = this.createBlock('food',block);
}
//移动、撞墙
var x = Snake.headDirection.x, y = Snake.headDirection.y;
//x等于0说明当前垂直移动,如果y等于1,说明在向左移动,所以head.y即元素的left-10px;y等于零时同理
if(x === 0){
y === 1 ? head.y-=10 : head.y+=10;
if(head.y<0||head.y>400){this.gameOver();return;}
}
if(y === 0){
x === 1 ? head.x-=10 : head.x+=10;
if(head.x<0||head.x>600){this.gameOver();return;}
}
var len = this.snake.length;
for(var i = len-1 ; i>0 ; i--){
var nowXY = getElemXY(this.snake[i]);
if(head.x === nowXY.x && head.y === nowXY.y){this.gameOver();return;} //吃到自己
var preXY = getElemXY(this.snake[i-1]);
setElemXY(this.snake[i],preXY.x,preXY.y); //将每个蛇节都移到它的前一个的位置
}
setElemXY(this.snakeHead,head.x,head.y); //舌头移动到新位置
timeId = setTimeout(function () {
this.moving();
//这里用bind绑定this,不然无法调用this.moving(),不支持bind的话只能外层加个匿名函数来传参了
}.bind(this),1000/this.speed);
};
下面是吃食物函数,这个函数比较简单,主要看后面几行代码,将食物的位置改为蛇身的最后一个节点的位置,并把它添加进蛇的数组,便于整体移动
//吃食物,并更新游戏成绩
Snake.prototype.eat = function (food) {
this.levle++;
this.speed+=0.4;
this.score+=5*this.speed;
levelInfo.innerHTML = '等级: '+this.levle;
speedInfo.innerHTML = '速度: '+this.speed.toFixed(2);
scoreInfo.innerHTML = '成绩: '+this.score;
maxScore = Math.max(maxScore,this.score);
maxScoreInfo.innerHTML = '最高成绩: '+maxScore;
var oldLast = getElemXY(this.snake[this.snake.length-1]);
setElemXY(food,oldLast.x,oldLast.y);
this.snake.push(food);
};
基本上就是以上这些代码了,其它还有几个简单的公共函数,就不说了,自己查看源码。
这里我要说的一点心得:给函数、变量命名的时候一定要语义化,一看就能大概知道这个函数、变量是干什么的,这样才不会自乱阵脚,更别提和别人合作了!(不要用拼音,你不觉得low的话也行,我是不懂就查翻译,多多少少也能提高点英语水平吧,呵呵,我英语水平也是很菜,惭愧!)
原生JS实战:经典贪吃蛇(开局10倍速度,来看看你最高能得多少分!)的更多相关文章
- 原生js写的贪吃蛇网页版游戏特效
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <bo ...
- canvas原生js写的贪吃蛇
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 20行JS代码实现贪吃蛇
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- JS高级---案例贪吃蛇,把封装的函数移动到js文件中
案例贪吃蛇,把封装的函数移动到js文件中 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...
- 原生JS实战:分享一个首页进度加载动画!
本文是苏福的原创文章,转载请注明出处:苏福CNblog:http://www.cnblogs.com/susufufu/p/5871134.html 该程序是本人的个人作品,写的不好,可以参考,但未经 ...
- 用js写一个贪吃蛇小游戏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 原生JS实战:写了个斗牛游戏,分享给大家一起玩!
本文是苏福的原创文章,转载请注明出处:苏福CNblog:http://www.cnblogs.com/susufufu/p/5869953.html 该程序是本人的个人作品,写的不好,未经本人允许,请 ...
- js面向对象案例 贪吃蛇
食物对象 (function () { //map:所在的父盒子,obj自身的一些属都具有默认值 function Food(map, obj) { obj = obj || {}; //没有则使用默 ...
- 原生JavaScript实现的贪吃蛇
github代码地址:https://github.com/McRayFE/snake 涉及到的知识点: 键盘事件 setInterval()定时器 javascript中数组的使用 碰撞的检测 of ...
随机推荐
- dd
1.属性 关键:get,set public class Account { private string id; private decimal money; public string Id { ...
- 列出场景对象Lightmap属性
首先上效果图: 编辑器代码: using UnityEngine; using UnityEditor; using System.Collections; public class Lightmap ...
- UGUI 之获取当前控件的高度
当Canvas Scaler选择Constant Pixel Size 当前的分辨率会被被固定,可以用RectTransform类里面的.rect变量值获取 height或Width. 在次情况下获取 ...
- nodejs+easyui(抽奖活动后台)增删改查
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfAAAAJACAIAAAD97KNZAAAgAElEQVR4nO2daXxb5Z2o7w+dO1/ufL ...
- MVC4做网站后台:栏目管理1、添加栏目-续
栏目类型跟原来一样分为常规栏目.单页栏目和外部链接.根据栏目类型的不同要隐藏相应的表单和验证(服务器端验证).另外一个是父栏目必须是常规栏目才行,easyui-combotree要用到树形json数据 ...
- ASP.NET sync over async(异步中同步,什么鬼?)
async/await 是我们在 ASP.NET 应用程序中,写异步代码最常用的两个关键字,使用它俩,我们不需要考虑太多背后的东西,比如异步的原理等等,如果你的 ASP.NET 应用程序是异步到底的, ...
- js 把数字转成2 ,8,16进制的方法
直接上代码 <!DOCTYPE html> <html> <body> <script> var myNumber = 128; document.wr ...
- 开启了HA的XenServer如何关闭虚拟机?
可开启了HA很方便,在主机自己坏掉的情况下其中的虚拟机能自己飘到活的机器上并被运行起来,不过如果手动的需要关闭虚拟机的话在这情况下,该虚拟机会自己"复活"即便我们选的是关机. 此时 ...
- Azure Application Gateway (3) 设置URL路由
<Windows Azure Platform 系列文章目录> 在之前的文章中,笔者介绍了Azure Web App可以设置URL路由.如下图: 在这里笔者简单介绍一下,首先我们还是创建以 ...
- 一步一步开发Game服务器(二)完成登陆,聊天
我知道这样的文章在博客园已经多的大家都不想看了,但是这是我的系列文章开始,请各位大神见谅了. 多线程,线程执行器,(详见),socket通信相关 (详见) 本人blog相关文章测试代码,示例,完整版s ...