1. 程式人生 > >純JS寫的貪吃蛇遊戲(大二暑假實習)

純JS寫的貪吃蛇遊戲(大二暑假實習)

此遊戲是大二暑假實習無聊,然後弄的,剛翻檔案看到了,所以想和你們分享一下。。。








<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>貪吃蛇遊戲</title>
	<script type="text/javascript" src='jquery.min.js'></script>
	<style>
	*{
		padding: 0;
		margin: 0;
	}
	html{
		margin: 0 auto;
		width: 87%;
		height: 100%;
		overflow:hidden;
		background: red;
		background: url(bg.png);
		background-size: cover;
		background-repeat: no-repeat;
	}
	body{
		width: 100%;
		height: 100%;
		position: relative;
	}
	div{
        width: 34px;
        height: 34px;
        float: left;
        border: 1px solid rgba(190,119,41,0.2);
    }
	#demo{
		position: fixed;
		top:-8px;
		left:285px;
		width: 930px;
		height: 700px;
		border: none;
		border-radius: 20px;
	}
    .out {
        visibility: hidden;
    }
    .in {
        background:url(1.png);
    }
    .h-right{
        background:url(head.png);
        background-repeat: no-repeat;
        background-size: cover;
        transform: rotate(180deg);
    }
    .h-left{
        background:url(head.png);
        background-repeat: no-repeat;
        background-size: cover;  
    }
    .h-up{
        background:url(head.png);
        background-repeat: no-repeat;
        background-size: cover;  
        transform: rotate(90deg);
    }
    .h-down{
        background:url(head.png);
        background-repeat: no-repeat;
        background-size: cover; 
        transform: rotate(-90deg); 
    }
    .f-left{
        background:url(fail.png);
        background-repeat: no-repeat;
        background-size: cover; 
    }
    .f-right{
        background:url(fail.png);
        background-repeat: no-repeat;
        background-size: cover; 
        transform: rotate(180deg); 
    }
    .f-up{
        background:url(fail.png);
        background-repeat: no-repeat;
        background-size: cover; 
         transform: rotate(90deg); 
    }
    .f-down{
        background:url(fail.png);
        background-repeat: no-repeat;
        background-size: cover; 
         transform: rotate(-90deg); 
    }
    .body{
        background:url(body.png);
        background-repeat: no-repeat;
        background-size: cover;
    }
    .food{
        background:url(food.gif);
        background-repeat: no-repeat;
        background-size: cover;
    }
    .food1{
        background:url(food1.gif);
        background-repeat: no-repeat;
        background-size: cover;
    }
    .food2{
        background:url(food2.png);
        background-repeat: no-repeat;
        background-size: cover;
    }
    .boom{
        background:url(boom.png);
        background-repeat: no-repeat;
        background-size: cover;
    }
    .red{
        background: red;
    }
    .btn{
        color: white;
        font-size: 15px;
        position: absolute;
        top: 557px;
        padding: 30px 0;
        border-radius: 50%;
        left: 27px;
        height: 30px;
        line-height: 30px;
        width: 100px;
        text-align: center;
        cursor: pointer;
        border:none;
        transition: 0.2s;
    }
    .btn:hover{
        opacity: 0.8;
        font-size: 18px;
        transform: rotate(360deg);
        transition: 0.1s;
    }
    .grade{
        color: black;
        font-size: 20px;
        position: absolute;
        top: 417px;
        left: 19px;
        width: 110px;
        height: 110px;
        line-height: 110px;
        border-radius: 50%;
        text-align: center;
        cursor: pointer;
        border:none;
        background: url(fly.gif) -105px -35px;
    }
    .grade>span{
    	opacity: 0.8;
    }
    .grade:hover{
    	background: white;
    	opacity: 0.6;
    	transition: 2s;
    }

    .grade:hover span{
    	color: black;
    	display: block;
    	font-size: 30px;
    	transition: 0.2s;
    }
    .time{
        color: white;
        position: absolute;
        top: 32px;
        left: 155px;
        cursor: pointer;
        transition: 1s;
    }
    .time:hover{
    	transform:scale(1.2);
    	transition: 1s;
    }
    .sttt{
    	position: absolute;
    	width: 100px;
    	height: 330px;
    	top: 83px;
    	left: 118px;
    	border: none;
    }
    .sttt>div{
    	width: 100%;
    	height: 94px;
    	margin-top: 10px;
    	cursor: pointer;
    	overflow: hidden;
    	border: none;
    }

    .sttt>div span{
    	display: block;
    	color: white;
    	border-radius: 50%;
    	padding: 1px;
    	width: 30px;
    	text-align: center;
    	line-height: 30px;
    	height: 30px;
    	background: url(countbg.gif);
    }

    .sttt>div:hover span{
    	font-size: 24px;
    }

    .sttt>div img{
    	display: none;
    }

    .sttt>div:hover img{
		display: block;
    }
    .star{
    	position: absolute;
    	top: -25px;
    	left: -40px;
    	width: 9%;
    	height: 10%;
    }
    .sccc{
    	position: absolute;
    	width: 100px;
    	height: 350px;
    	top: 26px;
    	right:5px;
    	border:none;
    }
    .sccc>div{
    	width: 100%;
    	height: 94px;
    	cursor: pointer;
    	overflow: hidden;
    	border-radius: 50%;
    	border: none;
    	margin-top: 28px;
    }
    .tip{
    	width: 55%;
    	height: 465px;
    	z-index: 9999999;
    	position: absolute;
    	left: 27%;
    	top: 15%;
    	border-radius: 20px;
    	color: black;
		text-align:center;
		background: white;
		overflow: hidden;
		display: none;
	    }
		.tip p:first-child img{
			width: 85%;
		}
	    .tip p:first-child{
	    	position: relative;
	    }

	    .tip p:first-child a{
			position: absolute;
			right: 0px;
			text-decoration: none;
	    }
	    .set{
	    	width: 55%;
	    	height: 465px;
	    	z-index: 999;
	    	position: absolute;
	    	left: 27%;
	    	top: 15%;
	    	border-radius: 20px;
	    	color: white;
			text-align:center;
			background:url(set.jpg) -56px 2px;
			background-size: cover;
			background-repeat: no-repeat;
			overflow: hidden;
			border:none;
			text-align: center;
			box-shadow:10px 10px 10px rgba(0,0,0,0.5);
	    }
	    .set p:first-child{
	    	position: relative;
	    }
	    .set p:first-child img{
	    	width: 30px;
	    	height: 30px;
	    	position: absolute;
	    	right: 4px;
	    	top: 4px;
	    	cursor: pointer;
	    	transition: 1s;
	    }
	    .set p:first-child img:hover{
	    	transform: scale(1.2);
	    	transition: 1s;
	    }
	    .set .wrap{
	    	width: 35%;
	    	height: 225px;
	    	margin: 198px 225px;
	    	border:none;
	    	font-size: 18px;
	    }
	    .set .wrap p{
	    	height: 50px;
	    	line-height: 50px;
	    	margin-bottom: 10px;
	    	cursor: pointer;
	    	letter-spacing:8px;
	    }
	     .set .wrap p:first-child{
	    	height: 50px;
	    	line-height:55px;
	    }
	    .set .wrap p:last-child{
	    	height: 40px;
	    	line-height: 40px;
	    }
	    .set .wrap p:hover{
	    	color: blue;
	    	transform: scale(1.1);
	    	transition: 0.4s;
	    	font-weight: bold;
	    }
	</style>
</head>
<body>
	 <div id="demo"></div>
     <div class="btn" id="btn">開始遊戲</div>
     <div class="grade"><span>0分</span></div>
     <div class="time" id="divTime">01:00</div>
     <div class="sttt">
     	<div><span id="count1">0</span><img src="cc.gif" alt="" style="margin-left:-6px;margin-bottom: 25px;"></div>
     	<div><span id="count2">0</span><img src="aa.gif" style="margin-right: 250px;"></div>
     	<div><span id="count3">0</span><img src="bb.gif" style="margin-right: 250px;"></div>
     </div>
     <div class="sccc">
     	<div onclick="setshow()"><img src="cc.gif" alt="" style="margin-left:-6px;margin-bottom: 25px;"	></div>
     	<div onclick="sub()"><img src="aa.gif" style="margin-right: 250px;" title="減速"></div>
     	<div onclick="add()"><img src="aa.gif" style="margin-right: 250px; margin-top: 0px;" title="加速"></div>
     </div>
     <img src="star.gif" alt="" class="star">
     <div class="tip" id="set1">
     	<p><img src="set1.gif" alt="" style="width: 330px;"><a href="javascript:set1hide()"><img src="x.gif" alt=""></a></p>
     	<br>
     	<p>簡單: <input type="radio" name="level" checked onclick="gamelevel(this)" value="l1"></p>
     	<br>
     	<p>中等: <input type="radio" name="level" onclick="gamelevel(this)" value="l2"></p>
     	<br>
     	<p>較難: <input type="radio" name="level" onclick="gamelevel(this)" value="l3"></p>
     </div>
      <div class="tip" id="set2">
     	<p><img src="set2.gif" alt="" style="width: 330px;"><a href="javascript:set2hide()"><img src="x.gif" alt=""></a></p>
     	<p><img src="tip1.png" alt=""></p>
     </div>
      <div class="tip" id="set3">
     	<p><img src="set3.gif" alt="" style="width: 330px;"><a href="javascript:set3hide()"><img src="x.gif" alt=""></a></p>
     	<br>
     	<p>開: <input type="radio" checked name="voice" value="on" onclick="cmusic(this)"></p>
     	<br>
     	<p>關: <input type="radio" name="voice" value="off" onclick="cmusic(this)"></p>
     	<span id="musicControl">
        <a id="play">
            <audio id="music" loop="loop" autoplay="autoplay">
                <source src="bgmusic.mp3" type="audio/mpeg">
            </audio>
        </a>
 		</span>
     </div>
      <div class="tip" id="set4">
     	<p><img src="set4.gif" alt="" style="width: 330px;"><a href="javascript:set4hide()"><img src="x.gif" alt=""></a></p>
     	<br>
     	<p><h2 id="maxgrader"></h2></p>
     </div>
     <div class="tip" id="end">
     	<p><img src="end.gif" alt="" style="width: 330px;"><a href="javascript:endhide()"><img src="x.gif" alt=""></a></p>
     	<br>
     	<p><h2 id="endcount"></h2></p>
     </div>
     <div class="set">
     	<p><img src="set-x.png" alt="" onclick="setclose()"></p>
     	<div class="wrap">
     	<p onclick="set1show()">遊戲模式</p>
     	<p onclick="set2show()">遊戲說明</p>
     	<p onclick="set3show()">聲音設定</p>
     	<p onclick="set4show()">最高記錄</p>
     	</div>
     </div>
</body>
 <script type="text/javascript">
    var arryRoad = new Array();
    var arrSnake = new Array();
    function bulid(num,y, outStyle, inStyle) {
        for (var i = 1; i <= num * y; i++) {
            if (i <= y - 1 || i > y * (num - 1)) {
                $('<div class="' + outStyle + '">' + i+ '</div>').appendTo($('#demo'));
            } else if (i % y == 0 || i % y == 1) {
                $('<div class="' + outStyle + '">' + i + '</div>').appendTo($('#demo'));
            } else {
                $('<div class="' + inStyle + '">' +  + '</div>').appendTo($('#demo'));
                arryRoad.push(i - 1);
            }
        }
    }
    //計算時間
    var timeIndex=0;
    function timee(){
        var minutes = 0;
        var seconds = 59-parseInt(timeIndex % 60);
        if (seconds==0) {
        	stoptime();
        }
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        $("#divTime").text(minutes + ":" + seconds);
        timeIndex++;
    }
	

    //建牆
    bulid(19,25, 'out', 'in');
    arrSnake = [38,37,36];
    var snake = new Object();//我們進行例項化了一個snake物件。
    snake.direction = 'right';//給snake建立了一個方向,讓他預設像右移動。
    snake.speed=300;
    snake.level='l1';
    snake.timmer = null;//我們還給蛇建立了一個計時器。這個計時器肯定用來讓我們的貪吃蛇自己運動的啦!
    var timmer = null;
    /*--最高成績---*/
    function maxgrader(a,b){
    	if(b=='l1'){
    		if (localStorage.count1)
		    {
				if(a>Number(localStorage.count1)){
					localStorage.count1=a;
				}
		    }
		    else
		    {
			    localStorage.count1=0;
		    }
		    return localStorage.count1;
    	}else if(b=='l2'){
    		if (localStorage.count2)
		    {
				if(a>Number(localStorage.count2)){
					localStorage.count2=a;
				}
		    }
		    else
		    {
			    localStorage.count2=0;
		    }
		    return localStorage.count2;
    	}else if(b=='l3'){
    		if (localStorage.count3)
		    {
				if(a>Number(localStorage.count3)){
					localStorage.count3=a;
				}
		    }
		    else
		    {
			    localStorage.count3=0;
		    }
		    return localStorage.count3;
    	}
	    
    }

    function counttime(){
    timmer = setInterval(function() {
           timee();
    },1000);
    }

    function stoptime(){
        clearInterval(timmer);
    }

    function move(direction) {
        var num = 1;
        switch (direction) {
            case 'left':
                num = -1;//向左是-1; 
                break;
            case 'right':
                num = 1;//向右是+1;
                break;
            case 'up':
                num = -25;
                break;
            case 'down':
                num = 25;//向下是+15,同上~
                break;
        }
        var zb = parseInt(arrSnake[0]) + num;//我們申明一個變數zb,這個座標是移動的一下個點的位置
        var lastzb = arrSnake[arrSnake.length - 1]; //同上
        var itclassName = $('#demo').children().eq(zb).attr("class").toString();
        var endgrate = parseInt($(".grade span").html());
        if (itclassName == "out" || itclassName == 'body') {
             endshow("==你撞牆啦==",endgrate);
             $("#btn").html("再玩一次");
             stoptime();
             clearInterval(snake.timmer);//別忘了清除計時器貪吃蛇停止運動~
             return;    
        }else if (itclassName == 'boom') {
             endshow("==你踩炸彈啦==",endgrate);
             $("#btn").html("再玩一次");
             stoptime();
             clearInterval(snake.timmer);//別忘了清除計時器貪吃蛇停止運動~
             return;    
        }else if(itclassName=='food' || itclassName=='food1' ||
            itclassName=='food2'){
        	var nnn=0;
            $('#demo').children().eq(zb).removeClass();
            $('#demo').children().eq(zb).addClass("h-"+direction);
            arrSnake.unshift(zb);//我們將這個點加入到我們貪吃蛇的身體中
            $('#demo').children().eq(arrSnake[1]).removeClass();
            $('#demo').children().eq(arrSnake[1]).addClass("body");
            if(itclassName=="food"){
            	var t=parseInt($("#count2").html());
            	t++;
            	$("#count2").html(t);
            	if (snake.speed<205) {
            		nnn=80;
            	}else if(snake.speed<260){
            		nnn=50;
            	}else{
            		nnn=30;
            	}
            }else if(itclassName=="food1"){
            	var t=parseInt($("#count3").html());
            	t++;
            	$("#count3").html(t);
            	if (snake.speed<205) {
            		nnn=60;
            	}else if(snake.speed<260){
            		nnn=40;
            	}else{
            		nnn=20;
            	}
            }else if(itclassName=="food2"){
            	var t=parseInt($("#count1").html());
            	t++;
            	$("#count1").html(t);
            	if (snake.speed<205) {
            		nnn=40;
            	}else if(snake.speed<260){
            		nnn=10;
            	}else{
            		nnn=5;
            	}
            }
            var grade=parseInt($(".grade span").html())+nnn;
            $(".grade span").html(parseInt(grade)+"分");
            var indxofZb = arryRoad.indexOf(zb); //獲取目標位置在可用位置陣列中的索引
            arryRoad.splice(indxofZb, 1);
            food();
            return;
        }


        $('#demo').children().eq(zb).removeClass(); //同上**
        if(direction=="right"){
           $('#demo').children().eq(zb).addClass("h-right");
        }else if(direction=="down"){
            $('#demo').children().eq(zb).addClass("h-down");
        }else if(direction=="up"){
           $('#demo').children().eq(zb).addClass("h-up");
        }else if(direction=="left"){
            $('#demo').children().eq(zb).addClass("h-left");
        }

        var endtime= $("#divTime").text();
            if(endtime=='00:00'){
            	stop();
            	stoptime();
            	$("#btn").html("再玩一次");
            	var endgrate = parseInt($(".grade span").html());
             	endshow("==時間到==",endgrate);
        }

        
        arrSnake.unshift(zb); //同上**
        var indxofZb = arryRoad.indexOf(zb); //同上**
        arryRoad.splice(indxofZb, 1); //同上**
        $('#demo').children().eq(lastzb).removeClass(); //刪除蛇尾的所有樣式**
        $('#demo').children().eq(lastzb).addClass('in'); //將原本是貪吃蛇的尾巴重新變成了可用位置。
        var length=arrSnake.length-1;
        arrSnake.splice(length, 1);
        var len= Math.abs(arrSnake[0]-arrSnake[2]);
        for (var i = 1; i <= arrSnake.length-1; i++) {//我們迴圈遍歷貪吃蛇陣列。
            $('#demo').children().eq(arrSnake[i]).removeClass();
            if(i==arrSnake.length-1){
                $('#demo').children().eq(arrSnake[i]).addClass("f-right");
            }else{
                $('#demo').children().eq(arrSnake[i]).addClass("body");
            }
        }
        //然後我們將最後一個位置從我們的貪吃蛇陣列中刪除~因為他已經不再屬於我們的貪吃蛇了**
        arryRoad.push(lastzb); //把最arrSnake中的最後一位新增到arryRoad中,因為它已經變成了一個可用位置
    }

    function stop(){
    	clearInterval(snake.timmer);
    }

    function start(){
    	autoMove();
    }


    /*-----set------*/
    function set1show(){
    	$("#set1").show(200);
    }
    function set1hide(){
    	$("#set1").hide(200);
    }
    function set2show(){
    	$("#set2").show(200);
    }
    function set2hide(){
    	$("#set2").hide(200);
    }
    function set3show(){
    	$("#set3").show(200);
    }
    function set3hide(){
    	$("#set3").hide(200);
    }
    function set4show(){
    	$("#maxgrader").html("簡單:"+localStorage.count1+"分"+"<br>"+"中等:"+localStorage.count2+"分"
    		+"<br>"+"較難:"+localStorage.count3+"分");
    	$("#set4").show(200);
    }
    function set4hide(){
    	$("#set4").hide(200);
    }
    function endshow(text,a){
    	$("#end").show(200);
    	$("#endcount").html(text+"<br>"+a+"分");
    	 maxgrader(a,snake.level);
    	for (var i = 0; i <= 474; i++) {
    		var itName = $('#demo').children().eq(i).attr("class").toString();
    		if(itName!='out'){
    			$('#demo').children().eq(i).removeClass();
    		}
    	}
    }
    function endhide(){
    	$("#end").hide(200);
    }


    function setclose(){
    	$(".set").hide(200);
    }

    function setshow(){
    	$(".set").show(200);
    }
  
    function cmusic(obj){
    //控制音樂
    var state = $(obj).val();
 	var music = document.getElementById("music");
 	if(state=='off'){
 		music.pause();
 	}else{
 		music.play();
 	}
	}

	function gamelevel(obj){
	//遊戲級別
	snake.level = $(obj).val();
    	if (snake.level=='l1') {
    		snake.level='l1';
    		snake.speed=300;
    	}else if(snake.level=='l2'){
    		snake.level='l2';
    		snake.speed=200;
    	}else if (snake.level=='l3') {
    		snake.level='l3';
    		snake.speed=100;
    	}
	    }


    $(window).keydown(function(event) {//當滑鼠按下時,傳入事件物件~
    	var text=$("#btn").html();
        switch (event.keyCode) {//獲取鍵值碼
        	case 32:
		        if(text=='開始遊戲'){
		        	$(".set").hide();
		            $("#btn").html("暫停遊戲");
		            init();
		            counttime();
		        }else if(text=='暫停遊戲'){
		            $("#btn").html("繼續遊戲");
		            stop();
		            stoptime();
		        }else if(text=='繼續遊戲'){
           			 $("#btn").html("暫停遊戲");
            		start();
            		counttime();
        		} 
		        else if(text=='再玩一次'){
		          window.location.reload();
		        } 
        		break;
            case 37://如果鍵值碼為37,代表著我的鍵盤上的左鍵
                if (snake.direction != 'right') {//判斷是否當前的方向為右,因為,我們的貪吃蛇不能回頭~
                    snake.direction = 'left';//如果不是的話,我們將方向改為左
                }
                break;//跳出swich
            case 38:
                if (snake.direction != 'down') {
                    snake.direction = 'up';
                }
                break;
            case 39:
                if (snake.direction != 'left') {
                    snake.direction = 'right';
                }
                break;
            case 40:
                if (snake.direction != 'up') {
                    snake.direction = 'down';
                }
                break;
            case 65:
                add();
                break;
            case 68:
                sub();
                break;
        }

    })

    function add(){
    	var text=$("#btn").html();
    	if(text=="暫停遊戲"){
    		snake.speed=snake.speed-50;
    		stop();
    		start();
    	}
    }
    function sub(){
    	var text=$("#btn").html();
    	if(text=="暫停遊戲"){
    		snake.speed=snake.speed+100;
    		stop();
    		start();
    	}
    }
    function autoMove() {//讓蛇自動移動的函式~
        snake.timmer = setInterval(function() {//我們建立一個計時器~
            move(snake.direction);//目的就是每隔200毫秒呼叫move函式讓貪吃蛇運動起來,並且我們將方向也傳遞給了他
        }, snake.speed)
    }



    /*---加速---*/

    function randomXY(arryRoad) {//產生隨機數函式~
        var x = parseInt(Math.random() * arryRoad.length);
        return arryRoad[x];
    }
    function food() {
        var x = randomXY(arryRoad);
        var y = randomXY(arryRoad);
        $('#demo').children().eq(x).removeClass();
        if (x%2==0) {
            if(x%4==0){
            	$('#demo').children().eq(y).removeClass();
                $('#demo').children().eq(y).addClass('boom');//並且給他添加了‘食物’樣式
            	setTimeout(function() {//我們建立一個計時器~
            	$('#demo').children().eq(x).addClass('food2');
                },5000);
            }
                $('#demo').children().eq(x).addClass('food2');//並且給他添加了‘食物’樣式  
        }else if(x%3==0){
            $('#demo').children().eq(x).addClass('food2');//並且給他添加了‘食物’樣式 
        }else if(x%5==0){
        	$('#demo').children().eq(x).addClass('food');
        }else{
        	setTimeout(function() {//我們建立一個計時器~
                 $('#demo').children().eq(y).removeClass();
                 $('#demo').children().eq(y).addClass('food');//並且給他添加了‘食物’樣式
            },2000); 
        }
    }


    function init() {//初始化函式
        for (var i = 0; i < arrSnake.length; i++) {//我們迴圈遍歷貪吃蛇陣列。
            $('#demo').children().eq(arrSnake[i]).removeClass("in");//移出對應的內部方格樣式
            if(i==0){
                $('#demo').children().eq(arrSnake[i]).addClass("h-right");
            }else if(i==1){
                $('#demo').children().eq(arrSnake[i]).addClass("body");
            }else if(i==2){
                $('#demo').children().eq(arrSnake[i]).addClass("f-right");
            }
        }
        arryRoad.splice(0, arrSnake.length+1);//然後,我們刪除了可用陣列中的屬於蛇的部分
        food();//給我們的貪吃蛇生產出一個食物~
        autoMove();//呼叫貪吃蛇自動運動函式

    }

     
    $("#btn").click(function(){
        var timeIndex = 0;
        var text=$("#btn").html();
        if(text=='開始遊戲'){
        	$(".set").hide();
            $("#btn").html("暫停遊戲");
            init();
            counttime();
        }else if(text=='暫停遊戲'){
            $("#btn").html("繼續遊戲");
            stop();
            stoptime();
        }
        else if(text=='繼續遊戲'){
            $("#btn").html("暫停遊戲");
            start();
            counttime();
        } 
        else if(text=='再玩一次'){
          window.location.reload();
        } 
    });
	gamelevel(snake.level);
    </script>
</html>