游戏截图:



对应的html代码:

<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
<h1>通过四个方向键移动
</h1>
<div class="container text-center" id="2048">
</div>
<script>$(document).ready(function () {$("#2048").init2048();});
</script>

对应的css代码:

.holder2048 {width: 280px;height: 380px;position: relative;margin: 0 auto;
}.holder2048>.container {width: 280px;height: 280px;position: relative;margin: 0 auto;border-style: none;border: 3px solid #BBADA0;background-color: #CCC0B3;
}.holder2048>.container>.mask {width: 70px;height: 70px;position: absolute;box-sizing: border-box;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;border: 3px solid #BBADA0;
}.holder2048>.container>.box {width: 66px;height: 66px;background-color: Black;position: absolute;color: #776E65;font-size: x-large;font-weight: bolder;font-family: Arial;text-align: center;line-height: 70px;
}.holder2048>.container>.box[value='2'] {background-color: #FFF8D7
}.holder2048>.container>.box[value='4'] {background-color: #FFED97
}.holder2048>.container>.box[value='8'] {background-color: #FFBB77
}.holder2048>.container>.box[value='16'] {background-color: #FF9224
}.holder2048>.container>.box[value='32'] {background-color: #FF5809
}.holder2048>.container>.box[value='64'] {background-color: #EA0000
}.holder2048>.container>.box[value='128'] {background-color: #FFFF37
}.holder2048>.container>.box[value='256'] {background-color: #F9F900
}.holder2048>.container>.box[value='512'] {background-color: #E1E100
}.holder2048>.container>.box[value='1024'] {background-color: #C4C400
}.holder2048>.container>.box[value='2048'] {background-color: #9AFF02
}.holder2048>.container>.box[value='4096'] {background-color: #00FFFF
}.holder2048>.container>.box[value='8192'] {background-color: #FF00FF
}

对应的js代码:

(function ($) {/*** User options*/var defaults = {delay: 200 //Game speed};$.fn.init2048 = function (_options) {var _this = this,options = $.extend(defaults, _options),dir = {up: 'up',right: 'right',down: 'down',left: 'left'},holder = {}, //Game outer holdercontent = {}, //Game inner containermatrix = [], //For the logic behindboxes = [], //Boxes storageisCheating = 0,isGameOver = false;resetGame();bind();/*** Restart the game by recreate all DOM elements.*/function resetGame() {//Reset the propsboxes = [];matrix = [];isCheating = 0;isGameOver = false;//Recreate DOM elementsholder = $('<div>').addClass('holder2048');content = $('<div>').addClass('container').appendTo(holder);for (var i = 0; i < 4; i++) {for (var j = 0; j < 4; j++) {//Reset matrixmatrix[i * 4 + j] = {top: i * 70,left: j * 70,taken: false,combined: false,value: 0};//This is for the borders of each cell.$('<div>').addClass('mask').css({left: j * 70 + "px",top: i * 70 + "px"}).appendTo(content);}}//Create the first box on boardcreateBox();//Insert game holder and anything to whoever calls this function_this.html(holder);}/*** Just for fun.* Reset the game and place a 4096 box on the board.*/function cheat() {resetGame();createBox(4096);}/*** Create a box and add to game* Takes 1 or 0 param.** @param value*/function createBox(value) {//Check if there are spaces for a new box or notvar emptyMatrix = 0;for (var i = 0; i < matrix.length; i++) {if (!matrix[i].taken) {emptyMatrix++;}}if (emptyMatrix === 0) {return;}//Chose an actual index (means not taken) randomly for the new boxvar random = Math.floor(Math.random() * emptyMatrix + 1);var chosenIndex = 0;for (var j = 0; chosenIndex < matrix.length; chosenIndex++) {while (matrix[chosenIndex].taken) {chosenIndex++;}if (++j === random) {matrix[chosenIndex].taken = true;break;}}//Do the create jobvalue = value ? value : (Math.floor(Math.random() * 4 + 1) === 4 ? 4 : 2); //Use the value parse in or (1/4 -> 4 or  3/4 -> 2)var newBox = $('<div>').addClass('box').attr({position: chosenIndex,value: value}).css({marginTop: matrix[chosenIndex].top + 2,marginLeft: matrix[chosenIndex].left + 2,opacity: 0}).text(value).appendTo(content).animate({opacity: 1}, options.delay * 2);//Finally push it to the boxes arrayboxes.push(newBox);}/*** Combine 2 boxes into 1* @param source* @param target* @param value*/function combineBox(source, target, value) {var _value = parseInt(value) * 2;boxes[target].attr('value', _value).html(_value).css({zIndex: 99}).animate({width: '+=20',height: '+=20',marginTop: '-=10',marginLeft: '-=10'}, options.delay / 2, function () {$(this).animate({width: '-=20',height: '-=20',marginTop: '+=10',marginLeft: '+=10'}, options.delay / 2, function () {$(this).css({zIndex: 1})})});boxes[source].remove();boxes.splice(source, 1);}/*** Check if game over* @returns {boolean}*/function gameOver() {if (boxes.length != 16) {return false;}var i, a, b;for (i = 0; i < 16; i++) {for (a = 0; a < 16; a++) {if (boxes[a].attr('position') == i)break;}if (i % 4 != 3) {for (b = 0; b < 16; b++) {if (boxes[b].attr('position') == i + 1)break;}if (boxes[a].attr('value') == boxes[b].attr('value'))return false;}if (i < 12) {for (b = 0; b < 16; b++) {if (boxes[b].attr('position') == i + 4)break;}if (boxes[a].attr('value') == boxes[b].attr('value'))return false;}}return true;}/*** Game run* @param dir*/function gameRun(dir) {if (isGameOver) {return;}if (run(dir)) {createBox();}if (gameOver()) {isGameOver = true;alert("Game Over");}}/*** Bind keyboard and screen touch events to game*/function bind() {$(window).keydown(function (event) {if (!isGameOver) {if (event.which == 37) {event.preventDefault();gameRun(dir.left);} else if (event.which == 38) {event.preventDefault();gameRun(dir.up);} else if (event.which == 39) {event.preventDefault();gameRun(dir.right);} else if (event.which == 40) {event.preventDefault();gameRun(dir.down);}}});var touchStartClientX, touchStartClientY;document.addEventListener("touchstart", function (event) {if (event.touches.length > 1)return;touchStartClientX = event.touches[0].clientX;touchStartClientY = event.touches[0].clientY;});document.addEventListener("touchmove", function (event) {event.preventDefault();});document.addEventListener("touchend", function (event) {if (event.touches.length > 0)return;var dx = event.changedTouches[0].clientX - touchStartClientX;var absDx = Math.abs(dx);var dy = event.changedTouches[0].clientY - touchStartClientY;var absDy = Math.abs(dy);if (Math.max(absDx, absDy) > 10) {if (absDx > absDy) {if (dx > 0) {gameRun(dir.right);} else {gameRun(dir.left);}} else {if (dy > 0) {gameRun(dir.down);} else {gameRun(dir.up);}}}});}/*** [WARNING] This method is ugly enough for now. Waiting for refactor.** Make a single game move.* Takes 1 param.** @param dir* @returns {boolean}*/function run(dir) {var isMoved = false; //This is to indicate that if the game actually moved after calling this functionvar i, j, k, empty, _empty, position, value1, value2, temp; //Junks//Reset the matrix attr 'combined' before movingfor (i = 0; i < 16; i++) {matrix[i].combined = false;}if (dir == "left") {isCheating = -1;for (i = 0; i < 4; i++) {empty = i * 4;_empty = empty;for (j = 0; j < 4; j++) {position = i * 4 + j;if (!matrix[position].taken) {continue;}if (matrix[position].taken && position === empty) {empty++;if (empty - 2 >= _empty) {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty - 2) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty - 2].combined) {combineBox(k, temp, value1);matrix[empty - 1].taken = false;matrix[empty - 2].combined = true;empty--;isMoved = true;}}} else {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}boxes[k].animate({marginLeft: matrix[empty].left + 2,marginTop: matrix[empty].top + 2}, options.delay);boxes[k].attr('position', empty);matrix[empty].taken = true;matrix[position].taken = false;empty++;isMoved = true;if (empty - 2 >= _empty) {value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty - 2) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty - 2].combined) {combineBox(k, temp, value1);matrix[empty - 1].taken = false;matrix[empty - 2].combined = true;empty--;}}}}}} else if (dir == "right") {isCheating = -1;for (i = 3; i > -1; i--) {empty = i * 4 + 3;_empty = empty;for (j = 3; j > -1; j--) {position = i * 4 + j;if (!matrix[position].taken) {continue;}if (matrix[position].taken && position === empty) {empty--;if (empty + 2 <= _empty) {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty + 2) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty + 2].combined) {combineBox(k, temp, value1);matrix[empty + 1].taken = false;matrix[empty + 2].combined = true;empty++;isMoved = true;}}} else {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}boxes[k].animate({marginLeft: matrix[empty].left + 2,marginTop: matrix[empty].top + 2}, options.delay);boxes[k].attr('position', empty);matrix[empty].taken = true;matrix[position].taken = false;empty--;isMoved = true;if (empty + 2 <= _empty) {value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty + 2) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty + 2].combined) {combineBox(k, temp, value1);matrix[empty + 1].taken = false;matrix[empty + 2].combined = true;empty++;}}}}}} else if (dir == "up") {isCheating = -1;for (i = 0; i < 4; i++) {empty = i;_empty = empty;for (j = 0; j < 4; j++) {position = j * 4 + i;if (!matrix[position].taken) {continue;}if (matrix[position].taken && position === empty) {empty += 4;if (empty - 8 >= _empty) {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty - 8) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty - 8].combined) {combineBox(k, temp, value1);matrix[empty - 4].taken = false;matrix[empty - 8].combined = true;empty -= 4;isMoved = true;}}} else {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}boxes[k].animate({marginLeft: matrix[empty].left + 2,marginTop: matrix[empty].top + 2}, options.delay);boxes[k].attr('position', empty);matrix[empty].taken = true;matrix[position].taken = false;empty += 4;isMoved = true;if (empty - 8 >= _empty) {value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty - 8) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty - 8].combined) {combineBox(k, temp, value1);matrix[empty - 4].taken = false;matrix[empty - 8].combined = true;empty -= 4;}}}}}} else if (dir == "down") {if (isCheating != -1) {isCheating++;if (isCheating == 10) {cheat();return true;}}for (i = 0; i < 4; i++) {empty = i + 12;_empty = empty;for (j = 3; j > -1; j--) {position = j * 4 + i;if (!matrix[position].taken) {continue;}if (matrix[position].taken && position === empty) {empty -= 4;if (empty + 8 <= _empty) {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty + 8) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty + 8].combined) {combineBox(k, temp, value1);matrix[empty + 4].taken = false;matrix[empty + 8].combined = true;empty += 4;isMoved = true;}}} else {for (k = 0; k < boxes.length; k++) {if (boxes[k].attr("position") == position) {break;}}boxes[k].animate({marginLeft: matrix[empty].left + 2,marginTop: matrix[empty].top + 2}, options.delay);boxes[k].attr('position', empty);matrix[empty].taken = true;matrix[position].taken = false;empty -= 4;isMoved = true;if (empty + 8 <= _empty) {value1 = boxes[k].attr('value');for (temp = 0; temp < boxes.length; temp++) {if (boxes[temp].attr("position") == empty + 8) {break;}}value2 = boxes[temp].attr('value');if (value1 == value2 && !matrix[empty + 8].combined) {combineBox(k, temp, value1);matrix[empty + 4].taken = false;matrix[empty + 8].combined = true;empty += 4;}}}}}}return isMoved;}}
})(jQuery);

只用html+js+css实现2048小游戏(带源码)相关推荐

  1. java实现2048小游戏(源码+注释)

    实现文件 APP.java import javax.swing.*;public class APP {public static void main(String[] args) {new MyF ...

  2. JS与HTML、CSS实现2048小游戏(一)

    JS与HTML.CSS实现2048小游戏(一) 引言 知识储备 编译器推荐 游戏框架 构建游戏的基础页面 后续文章 引言 这是大一刚结束的时候做的东西,之前也写了文章做记录,最近想发一下博客,就重新整 ...

  3. html实现扫雷小游戏(附源码)

    文章目录 实现功能 1.扫雷设计 1.1 主界面 1.2 扫雷难度 1.3 附带功能 2.效果和源码 2.1 动态效果 2.2 源代码 源码下载 作者:xcLeigh 文章地址:https://blo ...

  4. python跑酷游戏源码_Phaser.js实现简单的跑酷游戏附源码下载

    采用的物理引擎是Phaser.js 在这里对此引擎不做过多介绍(因为我也是小白,嘿嘿) 效果展示: 源码(详细源码图片资源可点击文章下方或屏幕右上方的github链接进行clone) 1.创建游戏舞台 ...

  5. flash高科技php网站源码下载,Flash小游戏PHP源码

    项目包里有两种版本, 第一种是:UTF-8 PHP版本 第二种是:UTF-8 伪静态版本(如果空间支持,强烈建议使用此版本,对搜索引擎友好) 开源项目:flash游戏源码,小游戏PHP源码,休闲fla ...

  6. 星益小游戏平台源码 内置80多个在线小游戏

    简介: 星益小游戏平台源码是一款星益在线小游戏可的网站源码,本程序由小星合集整理制作,共计80个小游戏. 内置了80个在线小游戏,直接就能玩耍,上传到空间用! 本程序大部分都是自适应,但是使用电脑端体 ...

  7. python小游戏-16行代码实现3D撞球小游戏!-源码下载

    python小游戏-16行代码实现3D撞球小游戏!-源码下载 所属网站分类: 资源下载 > python小游戏 作者:搞笑 链接: http://www.pythonheidong.com/bl ...

  8. 微信网页小游戏网站源码带后台+可后台添加游戏+推荐到微信

    微信网页小游戏网站源码带后台,淘宝上卖的很火的源码,免费公开!

  9. 遥控汽车网页小游戏html源码

    这是一个网页小游戏源代码 你可以开着小汽车在整个地图中旅行 可撞墙.可鸣笛.自己发现吧 无聊时可以用它打消下无聊的时间 首页注释挺详细的,可自行修改 运行不成功注意文件引用的路径 路径 路径 快来下载 ...

最新文章

  1. 浅谈深度学习图像分割
  2. Debian/Ubuntu--blade安装与使用
  3. 机器人动力学方程的性质
  4. 基于傅里叶算子的手势识别
  5. jQuery 事件 - bind() 方法
  6. vue请求封装,Store-状态管理部分(文档笔记)
  7. 10个必需的iOS开发工具和资源
  8. 搜索框中“请输入搜索keyword”
  9. [LibTorch Linux] 各版本 LibTorch 下载
  10. 这位勇士,你别去读博了:搞机器学习要PhD何用?
  11. Html label 标签详解
  12. 知识图谱在推荐系统中的应用全面调研
  13. 控制 计算机某个程序自动开关,电脑自动开关机软件(示例代码)
  14. 《财富》2022全球500强榜单,沃尔玛九连冠,沙特阿美最赚钱,中国公司上榜最多 | 美通社头条...
  15. 第13章 Python建模库介绍--Python for Data Analysis 2nd
  16. VMware Workstation(vm虚拟机)
  17. 校验注解:@Valid 和 @Validated区别与用法(附详细案例)
  18. 往事如烟 - 老钟11
  19. java获取拼音_java获取中文拼音
  20. 千万级巨型汉语词库分享

热门文章

  1. 上海在职研究生计算机专业考什么,中国人民大学计算机专业在职研究生考试考什么?...
  2. 【转】【公司调查】车来了APP
  3. 5 打印选课学生名单 (25 分)
  4. 熊猫分发_熊猫实用指南
  5. android swstnw cn,Android应用开发之ubuntu14.04编译ijkplayer备忘
  6. python多核运行程序_python单进程能否利用多核cpu的测试结论
  7. 边缘计算与深度学习综述
  8. 解决谷歌浏览器打开控制台有延迟
  9. 30 张图,概览 CPU 制作全过程
  10. 微信小程序项目实例——手势解锁