码迷,mamicode.com
首页 > Web开发 > 详细

前端JS-- 贪吃蛇游戏

时间:2014-07-22 22:37:32      阅读:404      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   os   width   

同样是前端,可惜我做的不是游戏前端,有些小遗憾。

不过靠着自己比常人多出的一点点学习能力,还是挤出不少时间自学了一些小玩意(姑且称他为小玩意吧)。

都是自己摸索着做的,代码很简单,刚刚工作半个月,很无奈。给自己以后留点回忆的线索吧。

(因为是公司是香港那边的,所以都是繁体系统,无奈只能使用我那蹩脚的英语注释了。。。。更无奈的是给自己取了个很那个名字--snow)

代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> snake game test </TITLE>
</HEAD>
<style>
    div{
        width:20px;
        height:20px;
        position:absolute;
        border:1px solid black;
        }
    a{
        font-family:tmb;
        font-size:18px;
        color:green;
    }
    .normal{
        background:white;
    }
    .snaker{
        background:red;
    }
    .food{
        background:black;
    }
</style>
<script>
/*
    @date:2014-07-21
    @author: snow.he

*/
    var rows=20,
        cols=20,
        arr =[];
    
    var map_top =100,
        map_left=80;
    
    var snake={dir: 39,snake_body:[]};
    var firstLen =5;
    var firstDir =39;

    var firstRows =5;

    var snow;

    var len;
    var isplay=true;

//share function
function $(str){
    return document.getElementById(str);
}

// init
function init(){
    initMap();
    initSnake();
    initData();
    showSnake();
    setNewFood();
    changeMove();
}

function initData(){
    var firstLev = 1;
    var firstScore =0;
    var continue_sta = false;
    if(localStorage.lev&&localStorage.score){
        if(confirm("are you continue last time?")){
            continue_sta = true;
        }
    }
    if(continue_sta){
        $("lev").text =localStorage.Lev;
        $("score").text = localStorage.score;
    }else{
        $("lev").text = firstLev ;
        $("score").text = firstScore;
    }
}

function initMap(){
    for(i=0;i<rows;i++)
    {
     arr[i]=[];
 
    for(j=0;j<cols;j++)
    {
        arr[i][j]=document.createElement(‘div‘);
        arr[i][j].style.top=map_top+i*24+‘px‘;
        arr[i][j].style.left=map_left+j*24+‘px‘;
   
        arr[i][j].className=‘normal‘;
   
        document.body.appendChild(arr[i][j]);
    }
    }
}
  /*
  left - A:65,left:37,4:100
  right - D:68,right:39,6:102
  up - W:87,up:38,8:104
  down - S:83,down:40,2:98
  */

function showSnake(){
//        console.log(snake);
    for(var i=0;i<snake.snake_body.length;i++){
        arr[snake.snake_body[i][0]][snake.snake_body[i][1]].className ="snaker";
    }
}

function initSnake(){
        snake.dir = firstDir;
        snake.snake_body =[];
    for(var i=0;i<firstLen;i++){
        var temp =[];
        temp.push(firstRows);
        temp.push(i);
        snake.snake_body.push(temp);
    }
}

//if the snake eat a food, take a new food
function setNewFood(){
    var X,Y;
    X =Math.floor(Math.random()*rows);
    Y =Math.floor(Math.random()*cols);

    arr[X][Y].className ="food";
}

//clear map
function clearSnake(){
    for(var i=0;i<rows;i++){
        for(var j=0;j<cols;j++){
        if(arr[i][j].className == "snaker"){
            arr[i][j].className ="normal";
            }
        }
    }
    //the second function to clear map,but have bug
/*
    for(var i=0;i<snake.snake_body.length;i++){
        arr[snake.snake_body[i][0]][snake.snake_body[i][1]-1].className ="normal";
        console.log(snake.snake_body[i][0]+"&&"+(snake.snake_body[i][1]-1));
    }
*/
}

// check snake can move
function isCanMoveit(dir,len){
    var status =true;
    switch(dir){
        case 39:
            if(snake.snake_body[len-1][1] >= cols-1  ){
            //arr[parseInt(snake.snake_body[len-1][0])+1][snake.snake_body[len-1][1]].className =="snaker"
            //    console.log(snake.snake_body[len-1][0]+"&:"+len-1+","+snake.snake_body[len-1][0]);
                status =false;
            };break;
        case 37:
            if(snake.snake_body[len-1][1] <= 0 ){
                status =false;
            };break;
        case 38:
            if(snake.snake_body[len-1][0] <= 0 ){    
                status =false;
            };break;
        case 40:
            if(snake.snake_body[len-1][0] >= rows-1 ){
                status=false;
            };break;
    }
    return status;
}

// snake‘s body move
function snakeBodyMove(len){
        var midX,midY;
        var midX2,midY2;
        midX = snake.snake_body[len-1][0];
        midY = snake.snake_body[len-1][1];    
    for(var i=parseInt(len-1);i>0;i--){
        midX2 = midX;
        midY2 = midY;
        midX = snake.snake_body[i-1][0];
        midY = snake.snake_body[i-1][1];
        snake.snake_body[i-1][0] =midX2;
        snake.snake_body[i-1][1] =midY2;

    }
}

//snake eat food
function eatFood(x,y){
    var temp=[];
    temp.push(x);
    temp.push(y);
    arr[x][y].className = "snaker";
    snake.snake_body.push(temp);
    setNewFood();
    len = snake.snake_body.length;
    keepScore();
}

//check snake can eat food
function isEatFood(dir){
 len = snake.snake_body.length;
    var isFood = false;
    try{
     switch(dir){
        case 39:
            if(arr[snake.snake_body[len-1][0]][snake.snake_body[len-1][1]+1].className == "food"){
                eatFood(snake.snake_body[len-1][0],snake.snake_body[len-1][1]+1);
            };break;
        case 37:
            if(arr[snake.snake_body[len-1][0]][snake.snake_body[len-1][1]-1].className == "food"){
                eatFood(snake.snake_body[len-1][0],snake.snake_body[len-1][1]-1);
            };break;
        case 38:
            if(arr[snake.snake_body[len-1][0]-1][snake.snake_body[len-1][1]].className == "food"){
                eatFood(snake.snake_body[len-1][0]-1,snake.snake_body[len-1][1]);
            };break;
        case 40:
            if(arr[snake.snake_body[len-1][0]+1][snake.snake_body[len-1][1]].className == "food"){
                eatFood(snake.snake_body[len-1][0]+1,snake.snake_body[len-1][1]);
            };break;
     }
    }catch(e){
        gameOver();
    }
}

//keep the player‘ score
function keepScore(){
    $("score").text = parseInt($("score").text)+100;
    localStorage.snakeScore = $("score").text;
    if(parseInt($("score").text) >= parseInt($("lev").text)*900){
        keepLev();
    }
}

//keep the player‘s level
function keepLev(){
    $("lev").text = parseInt($("lev").text)+1;
    localStorage.snakeLev = $("lev").text;
    changeMove();
}

//change the snake move velocity
function changeMove(){
    if(snow){
        clearInterval(snow);
        }
    var V = parseInt($("lev").text);
    if(V<7){
        snow = setInterval(moveFront,(500-V*50));
    }else{
        snow = setInterval(moveFront,180);
    }
}

// snake move
function moveFront(){
     len = snake.snake_body.length;
    var isCanMove;
    isCanMove = isCanMoveit(snake.dir,len);
    if(isCanMove){
        isEatFood(snake.dir);
        snakeBodyMove(len);
        switch(snake.dir){
            case 39:
                snake.snake_body[len-1][1]++;
                break;
            case 37:
                snake.snake_body[len-1][1]--;
                break;
            case 38:
                snake.snake_body[len-1][0]--;
                break;
            case 40:
                snake.snake_body[len-1][0]++;
                break;
        }
        
    }
    else{
        gameOver();
    }
    clearSnake();
    showSnake();
}

// handle the player‘s key
window.onkeydown =function(ev){
    var oEvent=ev||event;
    var canUser = true;
    if(oEvent.keyCode<=40 && oEvent.keyCode>=37){
        switch(oEvent.keyCode){
            case 37:
                if(snake.dir == 39){ canUser = false;};break;
            case 38:
                if(snake.dir == 40){ canUser = false;};break;
            case 39:
                if(snake.dir == 37){ canUser = false;};break;
            case 40:
                if(snake.dir == 38){ canUser = false;};break;
        }
        if(canUser){
            snake.dir = oEvent.keyCode;
        }
    }
    if(oEvent.keyCode == 32){
            if(isplay){
                clearInterval(snow);
                isplay = false;
            }else{
                changeMove();
                isplay = true;
            }
        }
}

//game over
function gameOver(){
    clearInterval(snow);
    if(confirm("are you continue?")){
        init();
    }
}

</script>
<BODY onload="init()">

<div id="testttt" style="left:100px;top:20px;height:30px;width:420px;border:0px;">
    <div style="width:150px;border:0px;">Lv:<a id="lev">1</a></div>
    <div style="width:240px;left:150px;border:0px;">Score:<a id="score">00</a></div>
</div>
</BODY>
</HTML>

 

 

 

 

 

都是上班时间做的,下班不学,没办法,人太懒。

漫漫长路,希望能够走得远一点。便在此处记录自己的成长历程吧

前端JS-- 贪吃蛇游戏,布布扣,bubuko.com

前端JS-- 贪吃蛇游戏

标签:style   blog   color   使用   os   width   

原文地址:http://www.cnblogs.com/lovetosleep/p/3861030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!