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
原始数据
按行查看
历史