通过这几天的学习利用Jquery实现了一个2048小游戏,在这个游戏中主页面实现基本框架, supportww2048.js实现基本的支撑部分, showanimation.js实现基本的动画逻辑, main.js实现基本的控制部分。
实现完成之后的效果如下
提供链接可以亲自体验一下 2048
下面来看代码:
index.html实现布局效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,minimun-scale=1.0, maximun-scale=1.0, user-scaleable=no"/>
<title>2048</title>
<link rel="stylesheet" type="text/css" href="2048.css">
<script src="jquery-1.9.1.js"></script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script type="text/javascript" src="supportww2048.js"></script>
<script type="text/javascript" src="showanimation.js"></script>
<script type="text/javascript" src="main2048.js"></script>
</head>
<body>
<header>
<h1>小小程序员</h1>
<a href="javascript:newgame();" id="newgamebutton">New Game</a>
<p>score:<span id="score">0</span></p>
</header>
<div id="grid-container">
<div class="grid-cell" id=grid-cell-0-0></div>
<div class="grid-cell" id=grid-cell-0-1></div>
<div class="grid-cell" id=grid-cell-0-2></div>
<div class="grid-cell" id=grid-cell-0-3></div>
<div class="grid-cell" id=grid-cell-1-0></div>
<div class="grid-cell" id=grid-cell-1-1></div>
<div class="grid-cell" id=grid-cell-1-2></div>
<div class="grid-cell" id=grid-cell-1-3></div>
<div class="grid-cell" id=grid-cell-2-0></div>
<div class="grid-cell" id=grid-cell-2-1></div>
<div class="grid-cell" id=grid-cell-2-2></div>
<div class="grid-cell" id=grid-cell-2-3></div>
<div class="grid-cell" id=grid-cell-3-0></div>
<div class="grid-cell" id=grid-cell-3-1></div>
<div class="grid-cell" id=grid-cell-3-2></div>
<div class="grid-cell" id=grid-cell-3-3></div>
</div>
</body>
</html>
接下来是页面的效果设置
2048.css
header{
display: block;
margin: 0 auto;
width: 100%;
text-align: center;
}
header h1{
font-family: Arial;
font-size: 40px;
font-weight: bold;
}
header #newgamebutton{
display: block;
margin: 20px auto;
width: 100px;
padding: 10px 10px;
background-color: #8f7a66;
font-family: Arial;
color: white;
border-radius: 10px;
}
header #newgamebutton:hover{
background-color: #9f8b77;
}
header p{
font-family: Arial;
font-size: 25px;
margin: 20px auto;
}
header a{
text-decoration: none;
}
#grid-container{
width: 460px;
height: 460px;
padding: 20px;
margin: 50px auto;
background-color: #bbada0;
border-radius: 10px;
position: relative;
}
.grid-cell{
width: 100px;
height: 100px;
border-radius: 6px;
background-color: #ccc0b3;
position: absolute;
}
.number-cell{
border-radius: 6px;
font-family: Arial;
font-weight: bold;
font-size: 20px;
line-height: 100px;
text-align: center;
position: absolute;
}
基本支撑部分supportww.js
documentWidth=window.screen.availWidth;
gridContainerWidth=0.92*documentWidth;
cellSideLength=0.18*documentWidth;
cellSpace=0.04*documentWidth;
function getPosTop(i, j){
return cellSpace+i*(cellSideLength+cellSpace);
}
function getPosLeft(i, j){
return cellSpace+j*(cellSideLength+cellSpace);
}
function getNumberBackgroundColor(number)
{
switch(number){
case 2: return "#eee4da"; break;
case 4: return "#ede0c8"; break;
case 8: return "#f2b179"; break;
case 16: return "#f59563"; break;
case 32: return "#f67c5f"; break;
case 64: return "#f65e3b"; break;
case 128: return "#edcf72"; break;
case 256: return "#edcc61"; break;
case 512: return "#9c0"; break;
case 1024:return "#33b5e5"; break;
case 2048:return "#09c"; break;
case 4096:return "#a6c"; break;
case 8192:return "#93c"; break;
}
return "black";
}
function getNumberColor(number){
if(number<=4)
{
return "#776e65";
}
else
return "white";
}
function nospace(board){
for(var i=0; i<4; i++)
for(var j=0; j<4; j++)
if(board[i][j]==0)
return false;
return true;
}
function canMoveLeft( board ){
for( var i = 0 ; i < 4 ; i ++ )
for( var j = 1; j < 4 ; j ++ )
if( board[i][j] != 0 )
if( board[i][j-1] == 0 || board[i][j-1] == board[i][j] )
return true;
return false;
}
function canMoveReight( board ){
for( var i = 0 ; i < 4 ; i ++ )
for( var j = 2; j >= 0 ; j -- )
if( board[i][j] != 0 )
if( board[i][j+1] == 0 || board[i][j+1] == board[i][j] )
return true;
return false;
}
function canMoveUp( board ){
for( var j = 0 ; j < 4 ; j ++ )
for( var i = 1 ; i < 4 ; i ++ )
if( board[i][j] != 0 )
if( board[i-1][j] == 0 || board[i-1][j] == board[i][j] )
return true;
return false;
}
function canMoveDown( board ){
for( var j = 0 ; j < 4 ; j ++ )
for( var i = 2 ; i >= 0 ; i -- )
if( board[i][j] != 0 )
if( board[i+1][j] == 0 || board[i+1][j] == board[i][j] )
return true;
return false;
}
function noBlockHorizontal( row , col1 , col2 , board ){
for( var i = col1 + 1 ; i < col2 ; i ++ )
if( board[row][i] != 0 )
return false;
return true;
}
function noBlockVertical( col , row1 , row2 , board ){
for( var i = row1 + 1 ; i < row2 ; i ++ )
if( board[i][col] != 0 )
return false;
return true;
}
function nomove( board ){
if( canMoveLeft( board ) ||
canMoveReight( board ) ||
canMoveUp( board ) ||
canMoveDown( board ) )
return false;
return true;
}
实现动画部分的js showanimation.js
function showNumberWithAnimation(i, j, randNumber ){
var numberCell=$("#number-cell-"+i+'-'+j);
numberCell.css('background-color',getNumberBackgroundColor(randNumber));
numberCell.css('color', getNumberColor(randNumber));
if (randNumber==2){
numberCell.text("小白");
}
else if(randNumber==4){
numberCell.text("实习生");
}
else if(randNumber==8){
numberCell.text("程序员");
}
else if(randNumber==16){
numberCell.text("项目经理");
}
else if(randNumber==32){
numberCell("架构师");
}
else if(randNumber==64){
numberCell.text("技术经理");
}
else if(randNumber==128){
numberCell.text("高级经理");
}
else if(randNumber==256){
numberCell.text("技术总监");
}
else if(randNumber==512){
numberCell.text("副总裁");
}
else if(randNumber==1024){
numberCell.text("CTO");
}
else if(randNumber==2048){
numberCell.text("总裁");
}
else if(randNumber==4096){
numberCell.text("Boss");
}
numberCell.animate({
width:cellSideLength,
height:cellSideLength,
top:getPosTop(i, j)+'px',
left:getPosLeft(i, j)+'px'
},300);
}
function showMoveAnimation(fromx, fromy, tox, toy){
var numberCell=$("#number-cell-"+fromx+'-'+fromy);
numberCell.animate({
top: getPosTop(tox, toy),
left:getPosLeft(tox, toy)
},200);
}
function updateScore(score){
$("#score").text(score);
}
主要逻辑运行部分 main2048.js
var board=new Array();
var score=0;
var hasConflicted=new Array();
var startx = 0;
var starty = 0;
var endx = 0;
var endy = 0;
$(document).ready(function(){
prepareForMobile();
newgame();
});
function prepareForMobile(){
if( documentWidth > 500 ){
gridContainerWidth = 500;
cellSpace = 20;
cellSideLength = 100;
}
$('#grid-container').css('width',gridContainerWidth - 2*cellSpace);
$('#grid-container').css('height',gridContainerWidth - 2*cellSpace);
$('#grid-container').css('padding', cellSpace);
$('#grid-container').css('border-radius',0.02*gridContainerWidth);
$('.grid-cell').css('width',cellSideLength);
$('.grid-cell').css('height',cellSideLength);
$('.grid-cell').css('border-radius',0.02*cellSideLength);
}
function newgame(){
//初始化16个方格
init();
//在两个格子里随机的生成数字
generateOneNumber();
generateOneNumber();
}
function init(){
for(var i=0; i<4; i++)
for(var j=0; j<4; j++){
var gridCell=$("#grid-cell-"+i+"-"+j);
gridCell.css('top',getPosTop(i, j));
gridCell.css('left',getPosLeft(i, j));
}
for(var i=0; i<4; i++)
{
board[i]= new Array();
hasConflicted[i]=new Array();
for(var j=0; j<4; j++){
board[i][j]=0;
hasConflicted[i][j]=false;
}
}
updateBoardView();
score=0;
}
function updateBoardView(){
$(".number-cell").remove();
for(var i=0; i<4; i++)
for(j=0; j<4; j++){
$('#grid-container').append('<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>');
var theNumberCell=$('#number-cell-'+i+'-'+j);
if(board[i][j]==0){
theNumberCell.css('width','0px');
theNumberCell.css('height','0px');
theNumberCell.css('top',getPosTop(i, j)+cellSideLength/2);
theNumberCell.css('left',getPosLeft(i,j)+cellSideLength/2);
}else{
theNumberCell.css('width',cellSideLength);
theNumberCell.css('height',cellSideLength);
theNumberCell.css('top',getPosTop(i, j));
theNumberCell.css('left',getPosLeft(i, j));
theNumberCell.css('background-color', getNumberBackgroundColor(board[i][j]));
theNumberCell.css('color',getNumberColor(board[i][j]));
///可以用数字theNumberCell.text(board[i][j]);
///
///
///
/改为数字时应该一下字体font-size: 60px;
//自定义优化
var randNumber=board[i][j];
if (randNumber==2){
theNumberCell.text("小白");
}
else if(randNumber==4){
theNumberCell.text("实习生");
}
else if(randNumber==8){
theNumberCell.text("程序员");
}
else if(randNumber==16){
theNumberCell.text("项目经理");
}
else if(randNumber==32){
theNumberCell.text("架构师");
}
else if(randNumber==64){
theNumberCell.text("技术经理");
}
else if(randNumber==128){
theNumberCell.text("高级经理");
}
else if(randNumber==256){
theNumberCell.text("技术总监");
}
else if(randNumber==512){
theNumberCell.text("副总裁");
}
else if(randNumber==1024){
theNumberCell.text("CTO");
}
else if(randNumber==2048){
theNumberCell.text("总裁");
}
else if(randNumber==4096){
theNumberCell.text("Boss");
}
}
hasConflicted[i][j]=false;
}
$('.number-cell').css('line-height',cellSideLength+'px');
$('.number-cell').css('font-size',0.2*cellSideLength+'px');
}
function generateOneNumber(){
//判断空间是否已满
if(nospace(board))//nospace()在support中
return false;
//随机生成一个位置
var randx=parseInt(Math.floor(Math.random()*4));
var randy=parseInt(Math.floor(Math.random()*4));
//添加一个变量来优化while
var times=0;
while(times<50){//可以写成1或true
if(board[randx][randy]==0)
break;
//如果位置不可用继续寻找可用位置
randx=parseInt(Math.floor(Math.random()*4));
randy=parseInt(Math.floor(Math.random()*4));
times++;
}
if(times==50){//人工寻找到一个没有数字的位置
for(var i=0; i<4; i++)
for(var j=0; j<4; j++){
if(board[i][j]==0)
randx=x;
randy=y;
}
}
//随机生成一个数字
//50%概率生成随机数2和4
var randNumber=Math.random()<0.5?2:4;
//在随机位置上显示随机的数字
board[randx][randy]=randNumber;
//显示在前端界面的函数在showanimation2048中实现
showNumberWithAnimation(randx, randy, randNumber);
return true;
}
$(document).keydown(function(event){
event.preventDefault();//阻止默认的事件行为
switch(event.keyCode){
case 37: //left
if(moveLeft()){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
break;
case 38: //up
if(moveUp()){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
break;
case 39: //reight
if(moveReight()){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
break;
case 40: //down
if(moveDown()){
setTimeout("generateOneNumber()", 210);
setTimeout("isgameover()",300);
}
break;
default: //default
break;
}
});
//移动端手指触发判断
document.addEventListener('touchstart',function(event){//手指开始位置
startx = event.touches[0].pageX;
starty = event.touches[0].pageY;
});
document.addEventListener('touchend',function(event){//手指结束位置
endx = event.changedTouches[0].pageX;
endy = event.changedTouches[0].pageY;
var deltax = endx - startx;
var deltay = endy - starty;
//防止误触发
if( Math.abs( deltax ) < 0.3*documentWidth && Math.abs( deltay ) < 0.3*documentWidth )
return;
//判断是向左右移动还是上下移动
if( Math.abs( deltax ) >= Math.abs( deltay ) ){
if( deltax > 0 ){
//move right
if( moveReight() ){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
}
else{
//move left
if( moveLeft() ){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
}
}
else{
if( deltay > 0 ){
//move down
if( moveDown() ){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
}
else{
//move up
if( moveUp() ){
setTimeout("generateOneNumber()",210);
setTimeout("isgameover()",300);
}
}
}
});
function isgameover(){
if( nospace( board ) && nomove( board ) ){
gameover();
}
}
function gameover(){
alert('gameover!');
$("#score").text(0);
}
function moveLeft(){
if( !canMoveLeft( board ) )
return false;
//moveLeft
for( var i = 0 ; i < 4 ; i ++ )
for( var j = 1 ; j < 4 ; j ++ ){
if( board[i][j] != 0 ){
for( var k = 0 ; k < j ; k ++ ){
if( board[i][k] == 0 && noBlockHorizontal( i , k , j , board ) ){
//move
showMoveAnimation( i , j , i , k );
board[i][k] = board[i][j];
board[i][j] = 0;
continue;
}
else if( board[i][k] == board[i][j] && noBlockHorizontal( i , k , j , board ) && !hasConflicted[i][k]){
//move
showMoveAnimation( i , j , i , k );
//add
board[i][k] += board[i][j];
board[i][j] = 0;
//加分步骤
score+=board[i][k];
updateScore(score);
hasConflicted[i][k]=true;
continue;
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
function moveReight(){
if(!canMoveReight( board ) )
return false;
//moveRight
for( var i = 0 ; i < 4 ; i ++ )
for( var j = 2 ; j >= 0 ; j -- ){
if( board[i][j] != 0 ){
for( var k = 3 ; k > j ; k -- ){
if( board[i][k] == 0 && noBlockHorizontal( i , j , k , board ) ){
showMoveAnimation( i , j , i , k );
board[i][k] = board[i][j];
board[i][j] = 0;
continue;
}
else if( board[i][k] == board[i][j] && noBlockHorizontal( i , j , k , board ) && !hasConflicted[i][k] ){
showMoveAnimation( i , j , i , k);
board[i][k] +=board[i][j];
board[i][j] = 0;
score+=board[i][k];
updateScore(score);
hasConflicted[i][k]=true;
continue;
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
function moveUp(){
if( !canMoveUp( board ) )
return false;
//moveUp
for( var j = 0 ; j < 4 ; j ++ )
for( var i = 1 ; i < 4 ; i ++ ){
if( board[i][j] != 0 ){
for( var k = 0 ; k < i ; k ++ ){
if( board[k][j] == 0 && noBlockVertical( j , k , i , board ) ){
showMoveAnimation( i , j , k , j );
board[k][j] = board[i][j];
board[i][j] = 0;
continue;
}
else if( board[k][j] == board[i][j] && noBlockVertical( j , k , i , board ) &&!hasConflicted[k][j] ){
showMoveAnimation( i , j , k , j );
board[k][j] += board[i][j];
board[i][j] = 0;
score+=board[k][j];
updateScore(score);
hasConflicted[k][j]=true;
continue;
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}
function moveDown(){
if( !canMoveDown( board ) )
return false;
//moveDown
for( var j = 0 ; j < 4 ; j ++ )
for( var i = 2 ; i >= 0 ; i -- ){
if( board[i][j] != 0 ){
for( var k = 3 ; k > i ; k -- ){
if( board[k][j] == 0 && noBlockVertical( j , i , k , board ) ){
showMoveAnimation( i , j , k , j );
board[k][j] = board[i][j];
board[i][j] = 0;
continue;
}
else if( board[k][j] == board[i][j] && noBlockVertical( j , i , k , board ) && !hasConflicted[k][j] ){
showMoveAnimation( i , j , k , j );
board[k][j] +=board[i][j];
board[i][j] = 0;
score+=board[k][j];
updateScore(score);
hasConflicted[k][j]=true;
continue;
}
}
}
}
setTimeout("updateBoardView()",200);
return true;
}