jQuery(function ($){
var playGround = {
x : 600,
y : 360
}
var step = 20;
var score = 0;
var timer;
var bodyArry = [];
var $head = $("#head");
var $gameBox = $("#gameBox");
var $egg;
var typeY = 0;
var typeX = 1;
// 绑定
$(document).bind("keydown",function(evt){
console.log(evt.keyCode);
move(evt.keyCode);
});
$("#reStart").bind("click",function(){
reStart();
})
function reStart(){
window.location.reload();
}
function addEgg(){
eggX = Math.round(Math.random() * (playGround.x/20-1)) *
step;
eggY = Math.round(Math.random() * (playGround.y/20-1)) *
step;
addBody(eggX, eggY, "egg");
}
function eatEgg(){
// 吃蛋,
if($head.css("top") == $egg.css("top")
&& $head.css("left") == $egg.css("left") ){
// 转化为身体
$egg.removeClass("egg").addClass("snakeBody");
bodyArry.push($egg);
// 加分
$("#score").html(++score);
// 加蛋
addEgg();
}
}
function initGame(){
addBody(180,200);
addBody(160,200);
addEgg();
snakeRun(true);
}
function move(key){
if(key == 38){ //上
typeX = 0;
typeY = -1;
}else if(key == 39){ //右
typeX = 1;
typeY = 0;
}else if(key == 40){ //下
typeX = 0;
typeY = 1;
}else if(key == 37){ //左
typeX = -1;
typeY = 0;
}else if(key == 32){ //左
snakeRun(false);
}else if(key == 82 || key ==13){ //左
snakeRun(true);
}else{
if(key){
return;
}
}
// debugger;
var moveY = typeY * step;
var moveX = typeX * step;
// 保存头部走动前位置
var headOldY = +$head.css("top").split("px")[0];
var headOldX = +$head.css("left").split("px")[0];
// 头部走动一步
$head.css("top","+="+moveY+"px");
$head.css("left","+="+moveX+"px");
// 尾部移动到原来头的位置
bodyArry[bodyArry.length-1].css("top",headOldY+"px");
bodyArry[bodyArry.length-1].css("left",headOldX+"px");
if(bodyArry.length>1){
bodyArry.unshift(bodyArry[bodyArry.length-1]);
bodyArry.pop();
}
// 判断游戏是否结束
if(gameOver()){
clearInterval(timer);
adAlert("gameOver!!!", function(){
reStart();
});
}
// 是否吃蛋
eatEgg();
}
function gameOver (){
// 1.撞墙
var headY = +$head.css("top").split("px")[0];
var headX = +$head.css("left").split("px")[0];
console.log("x:"+headX+",y:"+headY);
if(headY < 0 || headY > playGround.y-1 || headX < 0
|| headX > playGround.x-1){
return true;
}
// 2.撞自己
for (var i = 0; i < bodyArry.length; i++) {
if( $head.css("top") == bodyArry[i].css("top") &&
$head.css("left") == bodyArry[i].css("left")){
return true;
};
};
return false;
}
var n = 1;
function addBody(x, y, type){
var type = type || "snakeBody";
var html = " ";
n++;
var $snakeBody = $(html);
$snakeBody.css("top",y+"px");
$snakeBody.css("left",x+"px");
$gameBox.append($snakeBody);
if(type != "egg"){
bodyArry.push($snakeBody);
}else{
$egg = $snakeBody;
}
}
function snakeRun(bool){
if(bool){
timer = setInterval(function(){
move();
},400);
}else{
clearInterval(timer);
}
}
function myAlert(str , fun){
$("#myAlert-content").html(str);
$("#myAlert-bk").show();
$("#myAlert").show();
$("#myAlert-btn-ok").unbind("click").bind("click",function(){
$("#myAlert-bk").hide();
$("#myAlert").hide();
// 重启游戏
if(typeof fun == "function")fun();
})
}
adAlert("你准备好了吗?",function(){
initGame();
})
})
对话框