日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JS实现2048小游戏

發布時間:2023/12/14 javascript 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JS实现2048小游戏 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

JS實現2048小游戲

  • 簡介
  • 效果展示
  • 代碼實現

簡介

2048是一款休閑益智類的數字疊加小游戲。

游戲存在4種模式,分別是 3 X 3宮格、4 X 4宮格(默認)、5 X 5宮格、6 X 6宮格,每種模式的目標數字分別是 1024、2048、4096、8192,達到目標數字即可贏得勝利。

您可以通過鍵盤的上、下、左、右四個方向鍵進行操作,數字會按方向移動,相鄰的兩個數字相同就會合并,組成更大的數字,每次移動或合并后會自動增加一個數字。

效果展示

代碼實現

游戲UI部分index.html

<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>2048小游戲</title><style>* {margin: 0;padding: 0;}.left {float: left;}.right {float: right;}.clear-fixed:after {content: "";display: table;clear: both;}.container {width: 480px;height: 530px;position: absolute;top: 20px;left: 50%;margin-left: -240px;}.container .header {width: 100%;height: 50px;font-size: 25px;}.container .header .score-panel {height: 50px;text-align: center;line-height: 50px;}#canvas {width: 480px;height: 480px;background-color: #bbada0;border-radius: 10px;}#game-over {display: none;position: absolute;left: 50%;top: 50px;width: 480px;height: 480px;border-radius: 10px;background-color: rgba(0, 0, 0, .6);margin-left: -240px;text-align: center;z-index: 5;}#game-over .panel {position: absolute;left: 50%;right: 50%;top: 140px;width: 220px;height: 200px;border-radius: 10px;background-color: white;margin-left: -110px;text-align: center;z-index: 6;}#again {display: inline-block;width: 170px;height: 50px;border-radius: 10px;text-decoration: none;background-color: #9F8D77;color: white;font-size: 36px;}</style> </head><body><div class="container"><div class="header clear-fixed"><div class="score-panel left"><span>SCORE: </span><span id="score">0</span></div><div class="selection right"><label for="mode">模式選擇</label><select id="mode"><option value="3">3 X 3</option><option value="4" selected>4 X 4</option><option value="5">5 X 5</option><option value="6">6 X 6</option></select></div></div><canvas id="canvas" width="480" height="480"></canvas><div id="game-over"><div class="panel"><h1 id="state" style="margin-top: 5px;"></h1><a href="javascript:;" id="again">Try again</a></div></div><div>TIP: 通過鍵盤↑ ↓ ← → 鍵操作</div></div> </body> <script src="game.js"></script> </html>

游戲邏輯部分game.js

;(function (win, doc) {win.$ = function (el) {return /^#\S+/.test(el) ? doc.querySelector(el) : doc.querySelectorAll(el);}win.Game = function (id) {this.canvas = $(id);this.ctx = this.canvas.getContext('2d');this.mapWidth = this.canvas.width;this.mapHeight = this.canvas.height;}Game.prototype = {score: 0, // 得分isWin: false,isOver: false,cols: 4, // 列數rows: 4, // 行數spacing: 15, // 方格之間的間距grids: [], // 方格對象數組bgColors: { // 方格背景色0: '#ccc0b3', 2: '#eee3da', 4: '#ede0c8', 8: '#f2b179',16: '#f59563', 32: '#f67c5f', 64: '#f65e3b', 128: '#edcf72',256: '#edcc61', 512: '#9c0', 1024: '#33b5e5', 2048: '#09c',4096: '#a6c', 8192: '#93c'},// 初始化init: function () {this.score = 0;this.isWin = false;this.isOver = false;// 計算小方塊寬度this.width = (this.mapWidth - (this.cols + 1) * this.spacing) / this.cols;// 計算小方塊高度this.height = (this.mapHeight - (this.rows + 1) * this.spacing) / this.rows;// 初始化方塊數組for (var row = 0; row < this.rows; row++) {this.grids[row] = [];for (var col = 0; col < this.cols; col++) {var x = col * this.width + this.spacing * (col + 1);var y = row * this.height + this.spacing * (row + 1);this.grids[row][col] = {num: 0,x: x,y: y};}}this.random();this.random();this.draw();this.updateScore();},// 開始游戲start: function () {var self = this;self.init();doc.onkeydown = function (e) { // 綁定按鍵點擊事件if (this.isWin || this.isOver) {return false;}switch (e.keyCode) { // 判斷按鍵case 37: // leftself.dir = 3;self.moveLeft();break;case 38: // upself.dir = 1;self.moveUp();break;case 39: // rightself.dir = 4;self.moveRight();break;case 40: // downself.dir = 2;self.moveDown();break;}self.updateScore();};},// 隨機生成數字random: function () {while (1) {var row = Math.floor(Math.random() * this.rows);var col = Math.floor(Math.random() * this.cols);// 當前方塊的值必須是0,才能生成新的值if (this.grids[row][col].num === 0) {// 生成2和4的概率比例是 3:2this.grids[row][col].num = (Math.random() >= 0.6) ? 4 : 2;break;}}},// 更新分數顯示updateScore() {$('#score').innerText = this.score;},// 判斷游戲結束isGameOver: function () {for (var row = 0; row < this.rows; row++) {for (var col = 0; col < this.cols; col++) {if (this.grids[row][col].num === 0) {return false;} else if (col != this.cols - 1 && this.grids[row][col].num === this.grids[row][col + 1].num) {return false;} else if (row != this.rows - 1 && this.grids[row][col].num === this.grids[row + 1][col].num) {return false;}}}return true;},// 查找下一個不為0的數值的位置find: function (row, col, start, condition) {if (this.dir === 1) { // upfor (var f = start; f < condition; f += 1) {if (this.grids[f][col].num != 0) {return f;}}} else if (this.dir === 2) { // downfor (var f = start; f >= condition; f += -1) {if (this.grids[f][col].num != 0) {return f;}}} else if (this.dir === 3) { // leftfor (var f = start; f < condition; f += 1) {if (this.grids[row][f].num != 0) {return f;}}} else if (this.dir === 4) { // rightfor (var f = start; f >= condition; f += -1) {if (this.grids[row][f].num != 0) {return f;}}}return null;},// 方塊的移動move: function (itertor) {var before, // 沒處理前after; // 處理后before = this.gridsToString(this.grids);itertor(); //執行for函數after = this.gridsToString(this.grids);if (before != after) { // 前后對比,如果不同就updatethis.random();this.draw();}},// 處理左按鍵事件moveLeft: function () {var self = this;this.move(function () {for (var row = 0; row < self.rows; row++) {var next;for (var col = 0; col < self.cols; col++) {next = self.find(row, col, col + 1, self.cols); // 找出第一個不為0的位置if (next == null) {break; // 沒有找到就返回}// 如果當前位置為0if (self.grids[row][col].num === 0) {self.grids[row][col].num = self.grids[row][next].num; // 把找到的不為0的數值替換為當前位置的值self.grids[row][next].num = 0; //找到的位置清0col--; // 再次循環多一次,查看后面否有值與替換后的值相同,} else if (self.grids[row][col].num === self.grids[row][next].num) { // 如果當前位置與找到的位置數值相等,則相加self.grids[row][col].num *= 2;self.grids[row][next].num = 0;self.score += self.grids[row][col].num;}}}});},// 處理右按鍵事件moveRight: function () {var self = this;this.move(function () {for (var row = 0; row < self.rows; row++) {var next;for (var col = self.cols - 1; col >= 0; col--) {next = self.find(row, col, col - 1, 0); //找出第一個不為0的位置if (next == null) {break; //沒有找到就返回}//如果當前位置為0if (self.grids[row][col].num === 0) {self.grids[row][col].num = self.grids[row][next].num; //把找到的不為0的數值替換為當前位置的值self.grids[row][next].num = 0; //找到的位置清0col++; //再次循環多一次,查看后面否有值與替換后的值相同,} else if (self.grids[row][col].num === self.grids[row][next].num) { //如果當前位置與找到的位置數值相等,則相加self.grids[row][col].num *= 2;self.grids[row][next].num = 0;self.score += self.grids[row][col].num;}}}});},// 處理上按鍵事件moveUp: function () {var self = this;this.move(function () {for (var col = 0; col < self.cols; col++) {var next;for (var row = 0; row < self.rows; row++) {next = self.find(row, col, row + 1, self.rows); // 找出第一個不為0的位置if (next == null) {break;}// 如果當前位置為0if (self.grids[row][col].num === 0) {self.grids[row][col].num = self.grids[next][col].num; // 把找到的不為0的數值替換為當前位置的值self.grids[next][col].num = 0; // 找到的位置清0row--; // 再次循環多一次,查看后面否有值與替換后的值相同} else if (self.grids[row][col].num == self.grids[next][col].num) { // 如果當前位置與找到的位置數值相等,則相加self.grids[row][col].num *= 2;self.grids[next][col].num = 0;self.score += self.grids[row][col].num;}}}});},// 處理下按鍵事件moveDown: function () {var self = this;this.move(function () {for (var col = 0; col < self.cols; col++) {var next;for (var row = self.rows - 1; row >= 0; row--) {next = self.find(row, col, row - 1, 0); // 找出第一個不為0的位置if (next == null) {break;}// 如果當前位置為0if (self.grids[row][col].num === 0) {self.grids[row][col].num = self.grids[next][col].num; // 把找到的不為0的數值替換為當前位置的值self.grids[next][col].num = 0; // 找到的位置清0row++; // 再次循環多一次,查看后面否有值與替換后的值相同} else if (self.grids[row][col].num === self.grids[next][col].num) { // 如果當前位置與找到的位置數值相等,則相加self.grids[row][col].num *= 2;self.grids[next][col].num = 0;self.score += self.grids[row][col].num;}}}});},// 繪制游戲內容draw: function () {// 清空原有內容this.ctx.clearRect(0, 0, this.mapWidth, this.mapHeight);for (var row = 0; row < this.rows; row++) {for (var col = 0; col < this.cols; col++) {var x = this.grids[row][col].x; // 得到方塊x坐標var y = this.grids[row][col].y; // 得到方塊y坐標var num = this.grids[row][col].num; // 得到方塊數字var bgColor = this.bgColors[num]; // 得到方塊背景色// 繪制方塊this.fillRoundRect(this.ctx, x, y, this.width, this.height, 10, bgColor);if (num > 0) { // 只有方塊數字大于0才繪制數字// 繪制方塊的數字this.fillText(this.ctx, num, x + this.width / 2, y + this.height / 2, this.width - 20, num <= 4 ? '#776e65' : '#fff');}// 判斷是否勝利if (this.rows === 3 && num === 1024) {this.isWin = true;}if (this.rows === 4 && num === 2048) {this.isWin = true;}if (this.rows === 5 && num === 4096) {this.isWin = true;}if (this.rows === 6 && num === 8192) {this.isWin = true;}}}if (this.isWin) { // 勝利$('#state').innerHTML = 'YOU WIN<br>SCORE:<br>' + this.score;$('#state').style.color = 'green';$('#game-over').style.display = 'block';}if (this.isGameOver()) { // 失敗this.isOver = true;$('#state').innerHTML = 'GAME OVER<br>SCORE:<br>' + this.score;$('#state').style.color = 'red';$('#game-over').style.display = 'block';}},// 繪制文字fillText(ctx, text, x, y, maxWidth, fillColor) {ctx.fillStyle = fillColor || "#000"; // 設置畫筆顏色ctx.font = "bold 40px '微軟雅黑'"; // 設置字體ctx.textAlign = 'center'; // 水平居中ctx.textBaseline = "middle"; // 垂直居中ctx.fillText(text, x, y, maxWidth);},// 繪制并填充圓角矩形fillRoundRect: function (ctx, x, y, width, height, radius, fillColor) {// 圓的直徑必然要小于矩形的寬高if (2 * radius > width || 2 * radius > height) {return false;}ctx.save();ctx.translate(x, y);// 繪制圓角矩形的各個邊this.drawRoundRectPath(ctx, width, height, radius);ctx.fillStyle = fillColor || "#000"; // 設置畫筆顏色ctx.fill();ctx.restore();},// 繪制圓角矩形框drawRoundRectPath: function (ctx, width, height, radius) {ctx.beginPath(0);// 從右下角順時針繪制,弧度從0到1/2PIctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);// 矩形下邊線ctx.lineTo(radius, height);// 左下角圓弧,弧度從1/2PI到PIctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);// 矩形左邊線ctx.lineTo(0, radius);// 左上角圓弧,弧度從PI到3/2PIctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);// 上邊線ctx.lineTo(width - radius, 0);// 右上角圓弧ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);// 右邊線ctx.lineTo(width, height - radius);ctx.closePath();},// grids數組轉成stringgridsToString: function (grids) {var s = '[';for (var i in grids) {if (Object.prototype.toString.call(grids[i]) === '[object Array]') {s += this.gridsToString(grids[i]);} else if (Object.prototype.toString.call(grids[i]) === '[object Object]') {s += JSON.stringify(grids[i]);} else {s += grids[i];}}s += ']';return s;}}; })(window, document);var game = new Game('#canvas'); game.start();$('#mode').onchange = function () {game.rows = game.cols = $('#mode').value / 1;game.init();$('#mode').blur(); }$('#again').onclick = function () {$('#game-over').style.display = 'none';game.init(); }

在線體驗地址:https://www.feonix.cn/2048

總結

以上是生活随笔為你收集整理的JS实现2048小游戏的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。