昨天写了一个贪吃蛇的小游戏,在写完之后,因为自己平时喜欢打王者荣耀这一类的游戏,所以在想能否将这个游戏进阶一下,当完成一定的要求之后,他就晋级。于是写了下面的代码:
示例图如下:
这个是贪吃蛇初级版本:
这是贪吃蛇高阶版本:
这个是当贪吃蛇最终通关过后的版本:
他会有一个动态的烟花效果:
下面是代码:
初级贪吃蛇:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇初级</title>
<style>
*{
margin:0;
padding: 0;
}
td{
width: 48px;
height: 48px;
border: 1px solid black;
}
#pic{
width: 400px;
height: 400px;
opacity: 0.6;
position: absolute;
background-color: antiquewhite;
}
div{
position: absolute;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<h3 id="score">分数:0</h3>
<div id="pic"></div>
<script>
document.write("<table cellspacing='0'>")
for(var i=0;i<8;i++){
document.write('</tr>')
for(var j=0;j<8;j++){
document.write("<td></td>")
}
}
document.write("</table>")
var pic =document.getElementById("pic")
function createPic(type){
var Node =document.createElement("div")
Node.style.left =parseInt(Math.random()*8)*50+"px"
Node.style.top= parseInt(Math.random()*8)*50+"px"
pic.appendChild(Node)
switch(type){
case "head":
Node.style.backgroundColor="red"
break
case "food":
Node.style.backgroundColor="blue"
break
case "body":
Node.style.backgroundColor="yellow"
break
}
return Node
}
var Score =0
var snakeHead=createPic("head")
snakeHead.value="上"
var snakeFood=createPic("food")
var snakeArr=[] //存储身体元素
var snakeAll=[] //存储所有元素
var snakeScore=document.getElementById("score")
function move(){
if(snakeArr.length>0){
for(var i=snakeArr.length-1;i >= 0;i--){
switch(snakeArr[i].value){
case "上":
snakeArr[i].style.top =parseInt(snakeArr[i].style.top)-50+"px"
break
case "下":
snakeArr[i].style.top =parseInt(snakeArr[i].style.top)+50+"px"
break
case "左":
snakeArr[i].style.left =parseInt(snakeArr[i].style.left)-50+"px"
break
case "右":
snakeArr[i].style.left =parseInt(snakeArr[i].style.left)+50+"px"
break
}
if(i==0){
snakeArr[i].value=snakeHead.value //当i=0的时候,那个元素其实就是蛇头
}else{
snakeArr[i].value=snakeArr[i-1].value
}
}
}
switch(snakeHead.value){
case "上":
snakeHead.style.top =parseInt(snakeHead.style.top)-50+"px"
break
case "下":
snakeHead.style.top =parseInt(snakeHead.style.top)+50+"px"
break
case "左":
snakeHead.style.left =parseInt(snakeHead.style.left)-50+"px"
break
case "右":
snakeHead.style.left =parseInt(snakeHead.style.left)+50+"px"
break
}
if(parseInt(snakeHead.style.left)<0 || parseInt(snakeHead.style.top)<0 ||parseInt(snakeHead.style.left) >350 || parseInt(snakeHead.style.top) >350){
clearInterval(time)
alert("很抱歉,因为贪吃蛇撞到了墙,游戏结束!!!")
}
if(snakeArr.length>0){
for(var i=0;i<snakeArr.length;i++){
if(snakeHead.style.left ==snakeArr[i].style.left && snakeHead.style.top ==snakeArr[i].style.top){
clearInterval(time)
alert("你操作的贪吃蛇咬到自己了,游戏结束!!!")
}
}
}
if(snakeHead.style.left ==snakeFood.style.left &&snakeHead.style.top ==snakeFood.style.top){
Score+=10
snakeScore.innerHTML ="<h3>分数:"+Score+"</h3>"
var bodyNode =createPic("body")
snakeAll.push(snakeHead)
var finallyNode
if(snakeArr.length >0){
finallyNode=snakeArr[snakeArr.length-1]
}else{
finallyNode=snakeHead
}
switch(finallyNode.value){
case "上":
bodyNode.style.top=parseInt(finallyNode.style.top)+50+"px"
bodyNode.style.left=finallyNode.style.left
break
case "右":
bodyNode.style.left=parseInt(finallyNode.style.left)-50+"px"
bodyNode.style.top=finallyNode.style.top
break
case "下":
bodyNode.style.top=parseInt(finallyNode.style.top)-50+"px"
bodyNode.style.left=finallyNode.style.left
break
case "左":
bodyNode.style.left=parseInt(finallyNode.style.left)+50+"px"
bodyNode.style.top=finallyNode.style.top
break
}
bodyNode.value=finallyNode.value
snakeArr.push(bodyNode)
snakeAll.push(bodyNode)
var px =parseInt(Math.random()*8)*50
var py =parseInt(Math.random()*8)*50
for(var i=0;i<snakeAll.length;i++){
if((parseInt(snakeAll[i].style.left) ==px &&parseInt(snakeAll[i].style.top) ==py)){
px =parseInt(Math.random()*8)*50
py =parseInt(Math.random()*8)*50
}
}
snakeFood.style.left =px+"px"
snakeFood.style.top=py+"px"
if(Score >200){
clearInterval(time)
window.location="lastGame.html"
}
}
}
time =setInterval(move,500)
document.onkeydown =function(a){
switch(a.keyCode){
case 37:
if(snakeHead.value ="右" ){
snakeHead.value="左"
}
break
case 38:
if(snakeHead.value ="下"){
snakeHead.value="上"
}
break
case 39:
if(snakeHead.value ="左" ){
snakeHead.value="右"
}
break
case 40:
if(snakeHead.value ="上"){
snakeHead.value="下"
}
break
}
}
</script>
</body>
</html>
这是贪吃蛇高阶的版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇高级</title>
<style>
*{
margin: 0;
padding: 0;
}
td{
width: 48px;
height: 48px;
border: 1px solid black;
}
#map{
width: 700px;
height: 700px;
opacity: 0.4;
position: absolute;
background-color: rgb(29, 236, 10);
/* 背景颜色是这个 */
}
div{
position: absolute;
width: 50px;
height: 50px;
}
span{
position: relative;
width: 100px;
height: 100px;
}
h1{
margin-left: 300px;
}
button{
margin-left: 150px;
}
</style>
</head>
<body>
<span id="score1"><h1>分数:0</h1></span>
<span>
<button onclick="changTime('100')">快</button>
<button onclick="changTime('300')">中</button>
<button onclick="changTime('1000')">慢</button>
</span>
<div id="map"></div>
<script>
//首先创建地图 地图的规模是14*14即一行14格,共计14行
document.write("<table cellspacing ='0'");
for(var i=0;i<14;i++){
document.write("</tr>");
for(var j=0;j<14;j++){
document.write("<td></td>");
}
}
document.write("</table>")
var map =document.getElementById("map") //获取地图的标签
function createDiv(type){
var node =document.createElement("div") // 一个创建函数,主要是创建一个小格
node.style.left=parseInt(Math.random()*14)*50+"px" //随机生成一个距离左边的位置
node.style.top=parseInt(Math.random()*14)*50+"px" //随机生成一个距离右边的位置
map.appendChild(node) //将创建的div 50*50的一个颜色为传入的color的小格,添加到map地图中去
switch(type){ //给创建的新的元素赋“含义” 红色的是蛇头 蓝色的是食物 黄色的是身体
case "head":
node.style.backgroundColor="red"
break;
case "food":
node.style.backgroundColor="blue"
break;
case "body":
node.style.backgroundColor="yellow"
break;
}
return node
}
var arrAll =[] //放置蛇身体的元素
var NodeAll=[] //放置所有的元素
var score =0; //用来计分的
var headNode =createDiv("head") //红色的是蛇头的颜色
var spanScore =document.getElementById("score1") //获取计分数的,目的是当吃了一个食物后,就能够将分数进行更新
var footNode =createDiv("food") //蓝色的是食物的部分
headNode.value="下" //初始化蛇头的运动状态
//创建函数,此函数主要功能是贪吃蛇的移动
function move(){
//贪吃蛇移动身体
if(arrAll.length>0){
for(var i=arrAll.length-1;i >= 0;i--){
switch(arrAll[i].value){
case "上":
arrAll[i].style.top =parseInt(arrAll[i].style.top)-50+"px"
break
case "下":
arrAll[i].style.top =parseInt(arrAll[i].style.top)+50+"px"
break
case "左":
arrAll[i].style.left =parseInt(arrAll[i].style.left)-50+"px"
break
case "右":
arrAll[i].style.left =parseInt(arrAll[i].style.left)+50+"px"
break
}
if(i==0){
arrAll[i].value=headNode.value //当i=0的时候,那个元素其实就是蛇头
}else{
arrAll[i].value=arrAll[i-1].value
}
}
}
//确定蛇头的移动方向,根据蛇头的移动方向,来确定移动方向
switch(headNode.value){
case "上":
headNode.style.top =parseInt(headNode.style.top)-50+"px"
break
case "下":
headNode.style.top =parseInt(headNode.style.top)+50+"px"
break
case "左":
headNode.style.left =parseInt(headNode.style.left)-50+"px"
break
case "右":
headNode.style.left =parseInt(headNode.style.left)+50+"px"
break
}
//这个判断是如果蛇咬到了自己,那么就停止游戏
if(arrAll.length>0){
for(var i=0;i<arrAll.length;i++){
if(headNode.style.left ==arrAll[i].style.left && headNode.style.top ==arrAll[i].style.top){
clearInterval(time)
alert("你操作的贪吃蛇咬到自己了,游戏结束!!!")
}
}
}
//如果蛇碰到四周的墙壁,那么蛇就会死亡
if(parseInt(headNode.style.left) <0 ||parseInt(headNode.style.left)>650 || parseInt(headNode.style.top) <0 ||parseInt(headNode.style.top)>650){
//判断的条件是地图的四条边框线
clearInterval(time) //在这里是清除定时器
alert("你操作的贪吃蛇撞墙了,游戏结束!!!刷新重新开始游戏")
switch(headNode.value){
case "上":
headNode.style.top =0+"px"
break
case "下":
headNode.style.top =650+"px"
break
case "左":
headNode.style.left =0+"px"
break
case "右":
headNode.style.left =650+"px"
break
}
//这个switch的作用是不让蛇头在死亡后再次移动
}
//重合检测 保证贪吃蛇不能够重合
if(headNode.style.left ==footNode.style.left && headNode.style.top ==footNode.style.top){
score =score +10
spanScore.innerHTML="<h1>分数:"+score+"</h1>"
var bodyNode =createDiv("body")
NodeAll.push(headNode)
var lastNode
if(arrAll.length >0){
lastNode=arrAll[arrAll.length-1]
}else{
lastNode=headNode
}
switch(lastNode.value){
case "上":
bodyNode.style.top=parseInt(lastNode.style.top)+50+"px"
bodyNode.style.left=lastNode.style.left
break
case "右":
bodyNode.style.left=parseInt(lastNode.style.left)-50+"px"
bodyNode.style.top=lastNode.style.top
break
case "下":
bodyNode.style.top=parseInt(lastNode.style.top)-50+"px"
bodyNode.style.left=lastNode.style.left
break
case "左":
bodyNode.style.left=parseInt(lastNode.style.left)+50+"px"
bodyNode.style.top=lastNode.style.top
break
}
bodyNode.value=lastNode.value
arrAll.push(bodyNode)
NodeAll.push(bodyNode)
var px =parseInt(Math.random()*14)*50
var py =parseInt(Math.random()*14)*50
for(var i=0;i<NodeAll.length;i++){
if((parseInt(NodeAll[i].style.left) ==px &&parseInt(NodeAll[i].style.top) ==py)){
px =parseInt(Math.random()*14)*50
py =parseInt(Math.random()*14)*50
}
}
footNode.style.left =px+"px"
footNode.style.top=py+"px"
}
if(score>=300){
clearInterval(time)
window.open("finally.html")
}
}
function changTime(speed){
time =setInterval(move,speed)
}
//按住键盘的值,函数做出相应的反应 37对应的是左 38对应上 39对应右 40对应下
document.onkeydown=function(e){
switch(e.keyCode){
case 37:
if(headNode.value ="右" ){
headNode.value="左"
}
break
case 38:
if(headNode.value ="下"){
headNode.value="上"
}
break
case 39:
if(headNode.value ="左" ){
headNode.value="右"
}
break
case 40:
if(headNode.value ="上"){
headNode.value="下"
}
break
}
}
</script>
</body>
</html>
这是贪吃蛇最后通关过后的版本:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇最终通关</title>
</head>
<style>
body{
background: #494A5F;
color: #D5D6E2;
font-weight: 500;
font-size: 1.05em;
font-family: "Microsoft YaHei","Segoe UI", "Lucida Grande", Helvetica, Arial,sans-serif;
}
.htmleaf-header{
padding: 1em 190px 1em;
letter-spacing: -1px;
text-align: center;
}
#myclock{
background: #919191;
color: rgb(0, 255, 0);
text-align: center;
width: 928px;
height: 123px;
font-size:74px;
font-weight:bold;
font-family:"microsoft yahei","微软雅黑",serif;
}
</style>
<body >
<div class="htmleaf-container">
<header class="htmleaf-header">
<h1><input id="myclock" type="text" value="恭喜你通关了贪吃蛇游戏!!!" /></h1>
</header>
</div>
<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery.fireworks.js"></script>
<script type="text/javascript">
$('.htmleaf-container').fireworks({
sound: false,
opacity: 0.7,
width: '100%',
height: '90%'
});
</script>
</body>
</html>
通关后的烟花是有js的
(function ($) {
$.fn.fireworks = function(options) {
options = options || {};
var fireworksField = this,
particles = [],
rockets = [],
MAX_PARTICLES = 400,
SCREEN_WIDTH = options.width,
SCREEN_HEIGHT = options.height;
// var sounds = [], audio;
var canvas = document.createElement('canvas');
canvas.id = 'fireworksField';
canvas.style.width = SCREEN_WIDTH + 'px';
canvas.style.height = SCREEN_HEIGHT + 'px';
canvas.style.position = 'absolute';
canvas.style.top = '0px';
canvas.style.left = '0px';
canvas.style.opacity = options.opacity;
var context = canvas.getContext('2d');
function Particle(pos) {
this.pos = {
x: pos ? pos.x : 0,
y: pos ? pos.y : 0
};
this.vel = {
x: 0,
y: 0
};
this.shrink = 0.97;
this.size = 2;
this.resistance = 1;
this.gravity = 0;
this.flick = false;
this.alpha = 1;
this.fade = 0;
this.color = 0;
}
Particle.prototype.update = function() {
// apply resistance
this.vel.x *= this.resistance;
this.vel.y *= this.resistance;
// gravity down
this.vel.y += this.gravity;
// update position based on speed
this.pos.x += this.vel.x;
this.pos.y += this.vel.y;
// shrink
this.size *= this.shrink;
// fade out
this.alpha -= this.fade;
};
Particle.prototype.render = function(c) {
if (!this.exists()) {
return;
}
c.save();
c.globalCompositeOperation = 'lighter';
var x = this.pos.x,
y = this.pos.y,
r = this.size / 2;
var gradient = c.createRadialGradient(x, y, 0.1, x, y, r);
gradient.addColorStop(0.1, "rgba(255,255,255," + this.alpha + ")");
gradient.addColorStop(0.8, "hsla(" + this.color + ", 100%, 50%, " + this.alpha + ")");
gradient.addColorStop(1, "hsla(" + this.color + ", 100%, 50%, 0.1)");
c.fillStyle = gradient;
c.beginPath();
c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size : this.size, 0, Math.PI * 2, true);
c.closePath();
c.fill();
c.restore();
};
Particle.prototype.exists = function() {
return this.alpha >= 0.1 && this.size >= 1;
};
// The Rocket Object
function Rocket(x) {
Particle.apply(this, [{
x: x,
y: SCREEN_HEIGHT}]);
this.explosionColor = 0;
}
Rocket.prototype = new Particle();
Rocket.prototype.constructor = Rocket;
Rocket.prototype.explode = function() {
var count = Math.random() * 10 + 80;
for (var i = 0; i < count; i++) {
var particle = new Particle(this.pos);
var angle = Math.random() * Math.PI * 2;
var speed = Math.cos(Math.random() * Math.PI / 2) * 15;
particle.vel.x = Math.cos(angle) * speed;
particle.vel.y = Math.sin(angle) * speed;
particle.size = 10;
particle.gravity = 0.2;
particle.resistance = 0.92;
particle.shrink = Math.random() * 0.05 + 0.93;
particle.flick = true;
particle.color = this.explosionColor;
particles.push(particle);
}
};
Rocket.prototype.render = function(c) {
if (!this.exists()) {
return;
}
c.save();
c.globalCompositeOperation = 'lighter';
var x = this.pos.x,
y = this.pos.y,
r = this.size / 2;
var gradient = c.createRadialGradient(x, y, 0.1, x, y, r);
gradient.addColorStop(0.1, "rgba(255, 255, 255 ," + this.alpha + ")");
gradient.addColorStop(1, "rgba(0, 0, 0, " + this.alpha + ")");
c.fillStyle = gradient;
c.beginPath();
c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size / 2 + this.size / 2 : this.size, 0, Math.PI * 2, true);
c.closePath();
c.fill();
c.restore();
};
var loop = function() {
// update screen size
if (SCREEN_WIDTH != window.innerWidth) {
canvas.width = SCREEN_WIDTH = window.innerWidth;
}
if (SCREEN_HEIGHT != window.innerHeight) {
canvas.height = SCREEN_HEIGHT = window.innerHeight;
}
// clear canvas
context.fillStyle = "rgba(0, 0, 0, 0.05)";
context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
var existingRockets = [];
for (var i = 0; i < rockets.length; i++) {
// update and render
rockets[i].update();
rockets[i].render(context);
// calculate distance with Pythagoras
var distance = Math.sqrt(Math.pow(SCREEN_WIDTH - rockets[i].pos.x, 2) + Math.pow(SCREEN_HEIGHT - rockets[i].pos.y, 2));
// random chance of 1% if rockets is above the middle
var randomChance = rockets[i].pos.y < (SCREEN_HEIGHT * 2 / 3) ? (Math.random() * 100 <= 1) : false;
/* Explosion rules
- 80% of screen
- going down
- close to the mouse
- 1% chance of random explosion
*/
if (rockets[i].pos.y < SCREEN_HEIGHT / 5 || rockets[i].vel.y >= 0 || distance < 50 || randomChance) {
rockets[i].explode();
} else {
existingRockets.push(rockets[i]);
}
}
rockets = existingRockets;
var existingParticles = [];
for (i = 0; i < particles.length; i++) {
particles[i].update();
// render and save particles that can be rendered
if (particles[i].exists()) {
particles[i].render(context);
existingParticles.push(particles[i]);
}
}
// update array with existing particles - old particles should be garbage collected
particles = existingParticles;
while (particles.length > MAX_PARTICLES) {
particles.shift();
}
};
var launchFrom = function(x) {
if (rockets.length < 10) {
var rocket = new Rocket(x);
rocket.explosionColor = Math.floor(Math.random() * 360 / 10) * 10;
rocket.vel.y = Math.random() * -3 - 4;
rocket.vel.x = Math.random() * 6 - 3;
rocket.size = 8;
rocket.shrink = 0.999;
rocket.gravity = 0.01;
rockets.push(rocket);
}
};
var launch = function() {
launchFrom(SCREEN_WIDTH / 2);
};
// Append the canvas and start the loops
$(fireworksField).append(canvas);
setInterval(launch, 800);
setInterval(loop, 1000 / 50);
return fireworksField;
};
}(jQuery));