html贪吃蛇20行,20贪吃蛇.html

canvas

body {

text-align: center;

padding-top: 20px;

}

canvas {

margin: 0 auto;

box-shadow: 0 0 40px #333;

}

你的浏览器太low了~

window.onload = function () {

var canvas = document.getElementById('canvas')

if (canvas.getContext) {

var cvsCtx = canvas.getContext('2d')

var isEatFood = false; // 是否吃到食物

function Rect(x, y, width, height, color) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

this.color = color;

this.draw = function () { // 也可以定义成Rect.prototype.draw里;区别:this挂载在对象本身下面,prototype.XXX是挂在在原型链里边

cvsCtx.beginPath();

cvsCtx.fillStyle = this.color;

cvsCtx.fillRect(this.x, this.y, this.width, this.height);

cvsCtx.strokeStyle = 'green';

cvsCtx.strokeRect(this.x, this.y, this.width, this.height);

cvsCtx.closePath();

}

}

// 创建snake对象

function Snake(hx, hy, w, h) {

this.hx = hx;

this.hy = hy;

this.w = w;

this.h = h;

// 画蛇头

this.head = new Rect(this.hx, this.hy, this.w, this.h, 'red');

// 画蛇身

this.body = new Array();

var bx = this.hx - this.w;

var by = this.hy;

for (var i = 0; i < 3; i++) {

var rect = new Rect(bx, by, this.w, this.h, 'gray');

this.body.push(rect)

bx -= this.w;

}

}

Snake.prototype.sDraw = function () {

// 绘制蛇头

this.head.draw();

// 绘制蛇身

for (var i = 0; i < this.body.length; i++) {

this.body[i].draw();

}

}

Snake.prototype.move = function() {

console.log('move', this)

// // 加头

// var rect = new Rect(this.head.x, this.head.y, this.head.width, this.head.height);

// this.body.splice(0, 0, rect);

// // 去尾:如果吃到食物不去尾,没有吃到食物就去尾

// if(!isEatFood){

// this.body.pop();

// }else{

// isEatFood = false

// }

// switch(this.direction){

// case 0:{

// this.head.x -= this.head.width;

// this.sDraw()

// break;

// }

// }

}

var snake = new Snake(canvas.width / 2, canvas.height /2, 40, 40);

snake.sDraw();

document.onkeydown = function(e) {

var e = event || window.event;

// 37-40:左上右下

switch(e.keyCode) {

case 37: {

snake.direction = 0;

snake.move();

break;

}

// case 38: {

// }

// case 39: {

// }

// case 40: {

// }

}

}

// 贪吃蛇步骤

// 1、先画蛇:一个蛇头、n个蛇身

// 2、蛇动起来: 监听鼠标键盘事件

// 3、随机投放食物

// 3.1 坐标位置

// 3.2 食物是否投放到了蛇头或蛇身上

// 4、吃食物

// 4.1 碰撞检测

// 4.2 将食物添加到蛇身上

// 5、边缘检测

// 5.1 碰撞检测

// 5.2 gameover

} else {

alert('你的浏览器太low了~')

}

}

一键复制

编辑

Web IDE

原始数据

按行查看

历史

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值