簡單實現2048小遊戲

想實現2048遊戲書寫代碼時能夠分爲三個步驟

1、HTML部分

先書寫HTML把遊戲結構搭建出來javascript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
<!--最外部的大框-->
<div class="outermost"> //包裹遊戲全局的大盒子
    <!--title-->
    <span class="top"><b>SCORE:<span id="score01"></span></b></span>//頂部實時顯示的遊戲分數
    <!--遊戲大框框-->
    <div class="big">//2048遊戲爲四行四列所以須要16個div盒子
        <div class="cell" id="c00"></div>
        <div class="cell" id="c01"></div>
        <div class="cell" id="c02"></div>
        <div class="cell" id="c03"></div>

        <div class="cell" id="c10"></div>
        <div class="cell" id="c11"></div>
        <div class="cell" id="c12"></div>
        <div class="cell" id="c13"></div>

        <div class="cell" id="c20"></div>
        <div class="cell" id="c21"></div>
        <div class="cell" id="c22"></div>
        <div class="cell" id="c23"></div>

        <div class="cell" id="c30"></div>
        <div class="cell" id="c31"></div>
        <div class="cell" id="c32"></div>
        <div class="cell" id="c33"></div>
    //遊戲結束時會彈出的提示框
    </div>
    <!--提示框-->
    <div class="tips" id="gameover">
       <p>GAME OVER!!! <br>
           SCORE: <span id="score02">0</span><br>
           <button class="startbtn">從新開始</button>
       </p>
    </div>
    <!--重玩一遍-->
    <div class="foot">
        <button class="replay"><a>重玩一遍</a></button>
    </div>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
複製代碼

2、css部分

通過了第一步的搭建遊戲框架,第二部就是給遊戲添加樣式,使它能顯示出來css

*{
    padding: 0px;
    margin: 0px auto;
    font-family: Arial;

}
/*最外部的大框*/
.outermost{
    width: 480px;
    height: 600px;
    font-size: 40px;
    margin-top: 120px;
}
/*title*/
<!--頂部顯示分數的樣式-->
.top{
    margin: auto;
}
.top span{
    color: red;
}
/*遊戲大框框*/
.big{
    width: 480px;
    height: 480px;
    background:pink;
    border-radius: 8px;
}
<!--給每個盒子包裹的小框子添加樣式-->
.cell{
    list-style: none;
    float: left;
    display: inline-block;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    background-color: #fbf8cd;
    margin-left: 16px;
    margin-top: 16px;
    border-radius: 6px;
}
<!--提早把出現的數二、四、八、16等的數所在的格子給添加好樣式增長遊戲體驗感-->
.n2{background-color:#f65e3b;color:#776e65}
.n4{background-color:#33b5e5;color:#776e65}
.n8{background-color:#f2b179;color:#776e65}
.n16{background-color:#f59563;color:#776e65}
.n32{background-color:#f67c5f;color:#776e65}
.n64{background-color:#f65e3b;color:#776e65}
.n128{background-color:#edcf72;color:#776e65}
.n256{background-color:#edcc61;color:#776e65}
.n512{background-color:#9c0;color:#776e65}
.n1024{background-color:#33b5e5;color:#776e65;font-size:40px}
.n2048{background-color:#09c;color:#776e65;font-size:40px}
/*提示框樣式*/
.tips{
    border: 1px solid #cccccc;
    background: #FFFFFF;
    width: 400px;
    height: 200px;
    border-radius: 10px;
    color: #ff4456;
    text-align: center;
    line-height: 60px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -200px;
    margin-top: -100px;
    display: none;
}
.tips .startbtn{
    height: 50px;
    width: 200px;
    color: #FFFFFF;
    font-size: 20px;
    line-height: 50px;
    border-radius: 10px;
    background: cornflowerblue;
    border: none;
}
/*重玩一遍*/
.foot{
    width: 200px;
    height: 50px;
}
.foot>.replay{
    width: 200px;
    height: 50px;
    background: aquamarine;
    margin-top: 60px;
    color: lightpink;
    border:0;
    font-size: 24px;
    font-weight: bold;
    border-radius: 6px;
}
複製代碼

書寫好了HTML+CSS部分遊戲的模樣也就出來了,以下圖所示: html

3、JS部分

下面就到了最後也是最關鍵的一步----添加行爲,也就是JS部分的書寫,給其添加效果java

//建立一個對象,裏面存儲全部的遊戲數據及遊戲方法
var game = {
	data : [],   //定義一個數組,用來存全部的遊戲的數據
	score : 0,   //定義一個分數的屬性
	gamerunning : 1,   //定義一個遊戲運行的狀態,將其設置爲1與其餘狀態區分開
	gameover : 0,     //定義一個遊戲結束的狀態
	status : 0,      //這個是目前遊戲的狀態,時刻的跟上面兩個狀態作比較,肯定遊戲處於運行或者結束
	start : function(){   //遊戲開始時候的方法
//		遊戲開始的時候確定是要把遊戲的狀態設置成遊戲運行的狀態
//		this == game
		this.status = this.gamerunning;
//		遊戲開始的時候分數清空
		this.score = 0;
//		數組中的全部元素所有設置成0
		this.data = [
			[0,0,0,0],
			[0,0,0,0],
			[0,0,0,0],
			[0,0,0,0]
		];
		this.randomNum();//調用下面自定義的隨機函數,能夠在移動和開始的時候隨機出來一個數
		this.randomNum();//調用兩次是由於這是遊戲開始時的方法,開局隨機出現兩個數和位置,所以須要調用兩次
		this.dataView();//調用下面所寫的更新視圖的方法
	},
	
	
複製代碼
//	隨機數的函數,開始的時候隨機生成,移動的時候隨機生成
	randomNum: function(){
		while(true){
			//		隨機生成行和列 0 - 3隨機整數
			var r = Math.floor( Math.random() * 4 );   //隨機生成一個行
			var c = Math.floor( Math.random() * 4 );   //隨機生成一個列
			
			if(this.data[r][c] == 0){
				var num = Math.random() > 0.5 ? 2 : 4;//隨機出現2或4
				this.data[r][c] = num;
				break;
			}
		}
	},
	
複製代碼
//	更新試圖的方法
	dataView: function(){
//		大的循環,而後把全部的元素所有遍歷一遍
		for(var r = 0; r < 4; r++){
			for(var c = 0; c < 4; c++){
//				找到對應的div
				var div = document.getElementById("c" + r + c);  //字符串拼接
				if(this.data[r][c] != 0){
//					數組中對應的內容放到格子上面去
					div.innerHTML = this.data[r][c];
//					樣式也寫成對應的
					div.className = "cell n" + this.data[r][c];
				}else{
					div.innerHTML = "";
					div.className = "cell"
				}
			}
		}
		
複製代碼
//		更新分數
		document.getElementById("score01").innerHTML = this.score;
		//遊戲沒有結束的時候 彈出層時刻都是隱藏的
		if(this.status == this.gamerunning){
			document.getElementById("gameover").style.display = "none";
		}else{
			document.getElementById("gameover").style.display = "block";
			document.getElementById("score02").innerHTML = this.score;
		}
	},
	
複製代碼
//	判斷遊戲是否結束的方法
	isgameover: function(){
		for(var r = 0; r < 4; r++){
			for(var c = 0; c < 4; c++){
				if(this.data[r][c] == 0){  //裏面有空格子的時候,遊戲仍是能夠運行
					return false;   //表示遊戲尚未結束
				}
				if(c < 3){//判斷左右是否有相同的
					if(this.data[r][c] == this.data[r][c+1]){
						return false;
					}
				}
				if(r < 3){
					if(this.data[r][c] == this.data[r+1][c]){
						return false;
					}
				}
			}
		}
		return true;
	},
	
複製代碼

//移動的方法,左 右 上 下四個部分

//	左 右 上 下
//	左移的方法
	moveLeft: function(){
		var before = String(this.data);   //以前作一次轉換
//		具體的移動須要處理的邏輯,直接處理好每一行便可
		for(var r = 0;r < 4;r ++){
			this.moveLeftInRow(r);
		}
		var after = String(this.data);  //移動以後再作一次轉換
//		若是說移動以前不等於移動以後,確定是發生了移動
		if(before != after){
			this.randomNum();   //生成隨機數
//			生成的隨機數可能會形成遊戲的gameover
			if(this.isgameover()){
//				改變遊戲的狀態
				this.status = this.gameover
			}
//			更新視圖
			this.dataView();
		}
	},
	moveLeftInRow: function(r){   //只去作處理每一行的邏輯
		for(var c = 0; c < 3; c++){
			var nextc = this.getNextinRow(r,c);
			if(nextc != -1){
				if(this.data[r][c] == 0){
//					若是等於0,直接替換
					this.data[r][c] = this.data[r][nextc];
					this.data[r][nextc] = 0;  //位置恢復成0
					c --;   //要讓位置恢復到原地
				}else if(this.data[r][c] == this.data[r][nextc]){
					this.data[r][c] *= 2;   //位置直接翻一倍
					this.data[r][nextc] = 0;
					this.score += this.data[r][c];  //更新分數
				}
			}else{   //沒有找到
				break;   //直接退出循環
			}
		}
	},
	getNextinRow: function(r,c){
		for(var i = c + 1; i < 4; i++){
			if(this.data[r][i] != 0){
				return i;    //表示已經找到位置,而且把位置返回出來
			}
		}
		return -1;   //返回一個標識符
	},
//	右移的方法
	moveRight: function(){
		var before = String(this.data);
		for(var r = 0; r < 4; r++){
			this.moveRightInRow(r);
		}
		var after = String(this.data);
		if(before != after){
			this.randomNum();
			if(this.isgameover()){
				this.status = this.gameover;
			}
			this.dataView();
		}
	},
	moveRightInRow: function(r){
		for(var c = 4; c > 0; c--){
			var prevc = this.getPrevInRow(r,c);
			if(prevc != -1){
				if(this.data[r][c] == 0){
					this.data[r][c] = this.data[r][prevc];
					this.data[r][prevc] = 0;
					c ++
				}else if(this.data[r][c] == this.data[r][prevc]){
					this.data[r][c] *= 2;
					this.data[r][prevc] = 0;
					this.score += this.data[r][c];
				}
			}else{
				break;
			}
		}
	},
	getPrevInRow: function(r,c){
		for(var i = c - 1; i >= 0; i--){
			if(this.data[r][i] != 0){
				return i;
			}
		}
		return -1;
	},
//	上移
	moveUp: function(){
		var before = String(this.data);
		for(var c = 0; c < 4; c++){
			this.moveUpInCol(c);
		}
		var after = String(this.data);
		if(before != after){
			this.randomNum();
			if(this.isgameover()){
				this.status = this.gameover;
			}
			this.dataView();
		}
	},
	moveUpInCol: function(c){
		for(var r = 0;r < 4; r++){
			var nextr = this.getNextInCol(r,c);
			if(nextr != -1){
				if(this.data[r][c] == 0){
					this.data[r][c] = this.data[nextr][c];
					this.data[nextr][c] = 0;
					r -- ;
				}else if(this.data[r][c] == this.data[nextr][c]){
					this.data[r][c] *= 2;
					this.data[nextr][c] = 0;
					this.score += this.data[r][c];
				}
			}else{
				break;
			}
		}
	},
	getNextInCol: function(r,c){
		for(var i = r + 1; i < 4; i++){
			if(this.data[i][c] != 0){
				return i;
			}
		}
		return -1;
	},
//	下移的方法
	moveDown: function(){
		var before = String(this.data);
		for(var c = 0;c < 4; c++){
			this.moveDownInCol(c);
		}
		var after = String(this.data);
		if(before != after){
			this.randomNum();
			if(this.isgameover()){
				this.status = this.gameover;
			}
			this.dataView();
		}
	},
	moveDownInCol: function(c){
		for(var r = 3; r > 0; r--){
			var prev = this.getPrevIncol(r,c);
			if(prev != -1){
				if(this.data[r][c] == 0){
					this.data[r][c] = this.data[prev][c];
					this.data[prev][c] = 0;
					r -- ;
				}else if(this.data[r][c] == this.data[prev][c]){
					this.data[r][c] *= 2;
					this.data[prev][c] = 0;
					this.score += this.data[r][c];
				}
			}else{
				break;
			}
		}
	},
	getPrevIncol: function(r,c){
		for(var i = r - 1; i >= 0; i--){
			if(this.data[i][c] != 0){
				return i;
			}
		}
		return -1;
	},
	
	
	
}
game.start();
console.log(game.data)
console.log(game.status);
console.log(game.score);
//鍵盤事件
document.onkeydown = function(){
	if(event.keyCode == 37){
		//console.log("左")
		game.moveLeft();
	}else if(event.keyCode == 38){
		//console.log("上")
		game.moveUp()
	}else if(event.keyCode == 39){
		//console.log("右")
		game.moveRight()
	}else if(event.keyCode == 40){
		//console.log("下")
		game.moveDown()
	}
}
//touch事件
//手指按下
var startX;//設定開始起始位置的x座標
var startY;//設定開始起始位置的y座標
var endX;//設定結束滑動位置的x座標
var endY;//設定結束滑動位置的y座標
document.addEventListener('touchstart',function(){
//	console.log("手指按下了屏幕")
	console.log(event);
	startX = event.touches[0].pageX;
	startY = event.touches[0].pageY;
})
//手指移動
//document.addEventListener('touchmove',function(){
//	console.log("手指的移動")
//})
//手指鬆開
document.addEventListener("touchend",function(){
//	console.log("手指鬆開")
	console.log(event);
	endX = event.changedTouches[0].pageX;//如何獲取結束時的位置x
	endY = event.changedTouches[0].pageY;
	var X = endX - startX;
	var Y = endY - startY
	var absX = Math.abs(X) > Math.abs(Y);
	var absY = Math.abs(Y) > Math.abs(X);
	if(X > 0 && absX){
		console.log("右滑動")
		game.moveRight()
	}else if(X < 0 && absX){
		console.log("左滑動")
		game.moveLeft()
	}if(Y > 0 && absY){
		console.log("下滑動")
		game.moveDown()
	}if(Y < 0 && absY){
		console.log("上滑動")
		game.moveUp()
	}
})

複製代碼

以下爲遊戲效果圖 c++

就這樣一個簡單的2048遊戲就完成啦數組

關注我,下期講解如何將這個2048 打包到手機上,變成手機小遊戲!!!!bash

相關文章
相關標籤/搜索