简介
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