重写2048游戏

在慕客网上看到一个叫2048的游戏,作者讲的不错。听听很激动,看着很多网友留言,遇到各种问题,于是打算自己写一遍。试玩了一遍别人写好的2048.感觉逻辑还算容易理解。一种写下来,还是遇到了不少问题,但是冷静的想想,很快就找出问题,并解决了。最后,终于完成了自己的2048私人定制版。

下面是最终成果:

写完之后,其实代码一点都不难,会用jquery就可以了。

下面我自己的代码贴一下:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />

    <title>2048 私人定制</title>
    <link rel="stylesheet" type="text/css" href="2048.css" />

    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>
    <script type="text/javascript" src="support2048.js"></script>
    <script type="text/javascript" src="showanimation2048.js"></script>
    <script type="text/javascript" src="main2048.js"></script>
</head>
<body>
    <header>
        <h1>2048 升官版</h1>
        <a href="javascript:newgame();" id="newgamebutton">New Game</a>
        <p>贡献值 : <span id="score">0</span></p>
    </header>

    <div id="grid-container"></div>

    <div style="width:500px;margin:10px auto;text-align:center;">请使用键盘上的上、下、左、右的按键进行游戏。</div>
</body>
</html>

support2048.js

/**
 * Created by *** on 14-4-11.
 * modify by ouyangli on 14-8-15.
 * @author <[email protected]>
 * my site: http://www.imooc.com/
 */

function getPosTop( i ,j, size){
    var top = size.paddingTop;
    var height = size.cellHeight + top;
    return top + i*height;
}

function getPosLeft( i , j,size ){
    var left = size.paddingLeft;
    var width = size.cellWidth + left;
    return left + j*width;
}

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";

    return "white";
}

//生成单元格
function setGridCell(i,j){
    return $(‘<div class="grid-cell" id="grid-cell-‘+i+‘-‘+j+‘"></div>‘);
}
//获取单元格
function getGridCell(i,j){
    return $(‘#grid-cell-‘+i+"-"+j);
}
//生成数字块
function setNumberCell(i,j){
    return $(‘<div class="number-cell" id="number-cell-‘+i+‘-‘+j+‘"></div>‘ );
}
//获取数字块
function getNumberCell(i,j){
    return $(‘#number-cell-‘ + i + "-" + j );
}

function getNumberText( number ){
    switch( number ){
        case 2:return "学生";break;
        case 4:return "工人";break;
        case 8:return "企业家";break;
        case 16:return "人大代表";break;
        case 32:return "市长";break;
        case 64:return "省长";break;
        case 128:return "部长";break;
        case 256:return "副总理";break;
        case 512:return "总理";break;
        case 1024:return "副主席";break;
        case 2048:return "国家主席";break;
        case 4096:return "#a6c";break;
        case 8192:return "#93c";break;
    }

    return "black";
}

//修正字号
function getNumberTextSize(number){
    var str = getNumberText(number);
    switch(str.length){
        case 2 : return ‘1.5em‘;
        case 3 : return ‘1em‘;
        case 4 : return ‘0.25em‘;
        default: return ‘0.2em‘;
    }
}

//生成一个0到4之间的随机数
function getRandomNum () {
    return Math.floor( Math.random()  * 4 )
}

//手动找出空闲位置
function setPosition (board) {
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 0 ; j < 4 ; j ++ ){
            if( board[i][j] == 0 ){
                return [i,j];
            }
        }
}

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 canMoveRight( 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 ) ||
        canMoveRight( board ) ||
        canMoveUp( board ) ||
        canMoveDown( board ) )
        return false;

    return true;
}

showanimation.js

/**
 * Created by *** on 14-4-11.
 * modify by ouyangli on 14-8-15.
 * @author <[email protected]>
 * my site: http://www.imooc.com/
 */
function showNumberWithAnimation( i , j , randNumber ,size){

    getNumberCell(i,j).css({
        backgroundColor : getNumberBackgroundColor( randNumber ),
        color : getNumberColor( randNumber ),
        fontSize : getNumberTextSize(randNumber)
    }).text( getNumberText( randNumber ) ).animate({
        width : size.cellWidth,
        height : size.cellWidth
    },200);
}

function showMoveAnimation( fromx , fromy , tox, toy ,size){
    getNumberCell(fromx,fromy).animate({
        top:getPosTop( tox,toy ,size),
        left:getPosLeft( tox ,toy, size )
    },200);

}

function updateScore( score ){
    $(‘#score‘).text( score );
}

main.js
/**
 * Created by *** on 14-4-11.
 * modify by ouyangli on 14-8-15.
 * @author <[email protected]>
 * my site: http://www.imooc.com/
 */

var board = new Array();
var score = 0;
var hasConflicted = new Array();
var size = {};

$(document).ready(function(){
    newgame();
});

function newgame(){
    //初始化棋盘格
    init();
    //在随机两个格子生成数字
    generateOneNumber();
    generateOneNumber();
}

function init(){
    //获取棋盘尺寸
    setWrapSize();
    setFontSize();
    //创建格子
    createBoardView();
    //初始化数据
    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;
    $(‘#score‘).text( score );
}

//设置棋盘的宽高信息
function setWrapSize(){
    // 这里有一个等宽分布格子的公式
    // 棋盘宽度 = 格子宽 * 4 + 间距 * 5
    // 在没有提供棋盘尺寸时,取屏幕最小长度的60%,
    var boardWidth = size.boardWidth || function(Width){
            return Math.round(Width * 0.6);
        }(Math.min(window.innerWidth,window.innerHeight)),
        boardHeight = size.boardHeight || boardWidth,
        maxCellWidth = Math.floor(boardWidth / 4),
        maxCellHeight = Math.floor(boardHeight / 4),
        paddingLeft = Math.ceil(maxCellWidth * 0.2),
        paddingTop = Math.ceil(maxCellHeight * 0.2),
        cellWidth = Math.floor((boardWidth - 5 * paddingLeft) / 4),
        cellHeight = Math.floor((boardHeight - 5 * paddingTop) / 4);
    size = {
        boardWidth : boardWidth,
        boardHeight : boardHeight,
        paddingLeft : paddingLeft,
        paddingTop : paddingTop,
        cellWidth : cellWidth,
        cellHeight: cellWidth
    };
}

//设置字体大体
function setFontSize(){
    var width = size.boardWidth;
    if(width < 320){
        size.fontSize = ‘12px‘;
    }else if(width > 320 && width < 800){
        size.fontSize = ‘16px‘;
    }else{
        size.fontSize = ‘22px‘;
    }

}

//创建棋盘
function createBoardView(){
    var cell = ‘‘;
    var frame = $(‘<div></div>‘);
    for( var i = 0 ; i < 4 ; i ++ ){
        for( var j = 0 ; j < 4 ; j ++ ){
            cell  = setGridCell(i,j);
            cell.css({
                width : size.cellWidth,
                height : size.cellHeight,
                left : getPosLeft(i,j,size),
                top : getPosTop(i,j,size)
            })
            frame.append(cell);
        }
    }
    $(‘#grid-container‘).html(frame.html()).css({
        width : size.boardWidth,
        height: size.boardHeight,
        fontSize : size.fontSize,
        margin : ‘0 auto‘
    });
}

function updateBoardView(){
    $(".number-cell").remove();
    for( var i = 0 ; i < 4 ; i ++ )
        for( var j = 0 ; j < 4 ; j ++ ){

            var theNumberCell = setNumberCell(i,j);
            var tag = getNumberText( board[i][j] );

            if( board[i][j] == 0 ){
                theNumberCell.css({
                    width : 0,
                    height : 0,
                    top : getPosTop(i,j,size),
                    left : getPosLeft(i,j,size),
                    lineHeight : size.cellHeight+‘px‘
                })
            }else{
                theNumberCell.css({
                    width : size.cellWidth,
                    height: size.cellHeight,
                    lineHeight : size.cellHeight+‘px‘,
                    top : getPosTop(i,j,size),
                    left : getPosLeft(i,j,size),
                    color : getNumberColor( board[i][j] ),
                    backgroundColor : getNumberBackgroundColor(board[i][j]),
                    fontSize : getNumberTextSize(board[i][j])
                }).text( tag );
            }

            $("#grid-container").append(theNumberCell);
            hasConflicted[i][j] = false;
        }
}

function generateOneNumber(){
    var randx,randy,times=0,pos,randNumber;

    if( nospace( board ) )
        return false;

    //随机一个位置
    randx = getRandomNum();
    randy = getRandomNum();

    while( times < 50 ){
        if( board[randx][randy] == 0 )
            break;

        randx = getRandomNum();
        randy = getRandomNum();

        times ++;
    }

    if( times == 50 ){
        pos = setPosition(board);
        randx = pos[0];
        randy = pos[1];
    }

    //随机一个数字
    randNumber = Math.random() < 0.5 ? 2 : 4;

    //在随机位置显示随机数字
    board[randx][randy] = randNumber;
    showNumberWithAnimation( randx , randy , randNumber ,size);

}

$(document).keydown( function( event ){
    switch( event.keyCode ){
        case 37: //left
            moveLeft();
            break;
        case 38: //up
            moveUp();
            break;
        case 39: //right
            moveRight();
            break;
        case 40: //down
            moveDown();
            break;
        default: //default
            break;
    }
});

function isgameover(){
    if( nospace( board ) && nomove( board ) ){
        gameover();
    }
}

function gameover(){
    alert(‘gameover!‘);
}

function next () {

    setTimeout(function() {
        generateOneNumber();
    },210);

    setTimeout(function(){
        isgameover();
    },300);
}

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 ,size);
                        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 ,size);
                        //add
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        updateScore( score );

                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }

        setTimeout(function(){
            updateBoardView();
        },200);
    }
    next();
}

function moveRight(){
    if( !canMoveRight( 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 ) ){
                        //move
                        showMoveAnimation( i , j , i , k ,size);
                        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] ){
                        //move
                        showMoveAnimation( i , j , i , k,size);
                        //add
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        updateScore( score );

                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }

        setTimeout(function(){
            updateBoardView();
        },200);
    }
    next();
}

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 ) ){
                        //move
                        showMoveAnimation( i , j , k , j ,size);
                        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] ){
                        //move
                        showMoveAnimation( i , j , k , j ,size);
                        //add
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        updateScore( score );

                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }

        setTimeout(function(){
            updateBoardView();
        },200);
    }
    next();
}

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 ) ){
                        //move
                        showMoveAnimation( i , j , k , j,size );
                        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] ){
                        //move
                        showMoveAnimation( i , j , k , j ,size);
                        //add
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        updateScore( score );

                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }

        setTimeout(function(){
            updateBoardView();
        },200);
    }
    next();
}

2048.css

/**
 * Created by *** on 14-4-11.
 * modify by ouyangli on 14-8-15.
 * @author <[email protected]>
 * my site: http://www.imooc.com/
 */
body {
    font-family:Arial;
}

header{
    display:block;
    margin:0 auto;
    width:500px;
    text-align:center;
}

header h1{
    font-size:1.25em;
    font-weight:bold;
}

#newgamebutton{
    display:block;
    margin:10px auto;

    width:100px;
    padding:10px;
    background-color:#8f7a66;

    color:white;

    border-radius:10px;
    text-decoration:none;
}
#newgamebutton:hover{
    background-color:#9f8b77;
}

header p{
    font-size:1em;
    margin:20px auto;
}

#grid-container{
    background-color:#007aff;

    border-radius: 10px;
    position: relative;
}

.grid-cell {
    background-color: #ccc0b3;
}
.grid-cell,.number-cell{
    border-radius: 6px;
    position: absolute;
}

.number-cell{
    overflow: hidden;
    font-weight:bold;
    text-align:center;
}
 

重写2048游戏,布布扣,bubuko.com

时间: 2024-12-31 06:04:53

重写2048游戏的相关文章

Android 2048游戏开发

根据教程写的简单的2048游戏. 极客学院教程地址:http://www.jikexueyuan.com/course/43.html 我的源代码地址:https://github.com/myCodingTrip/2048Game 项目有3个类. Card extends FrameLayout{ private int num; private TextView label; public Card(Context context) public int getNum() public vo

是男人就下100层【第五层】——2048游戏

前言: 在"阳光小强"的实战系列博文<是男人就下100层>的上一层我们一起从零开始完成了我们自己的贪吃蛇游戏--CrazySnake,可能很多朋友还不过瘾,那么我们今天就来玩一玩最近一直比较火的2048游戏,让大家再过一把瘾.由于"阳光小强"目前并没有从事Android的游戏开发工作,所以这些游戏的实现并不需要很专业的游戏开发知识,如果你有Android的基础就可以一起来参与进来共同完成这个游戏.有些朋友可能就会说"这些小游戏,会不会有点简单,

2048游戏完整源代码揭秘和下载 (一)

2048 最近有一款2048的游戏非常火,本文将来介绍一下使用OGEngine游戏引擎开发游戏2048. OGEngine引擎是开源的,我们很容易找到,搭建起来也很方便,我们只需在Android工程下添加OGEngine的jar包或者直接引用源码就可以了. OGEngine引擎官网 2048游戏源码下载1.创建游戏的主Activity 类 创建的游戏主Activity入口类继承于GameActivity类,需要重写相关方法. (1) 重写onCreatePixelPerfectEngineOpt

2048游戏完整源代码揭秘和下载 (二)

5.游戏滑动上下左右相加的逻辑 下面我们将来分析一下游戏2048滑动上下左右相加逻辑的实现.要实现这一功能,首先我们得监听触碰事件.本游戏中,我们是在 GameGroup 实现滑动事件的处理. (1) public GameGroup(GameScene pGameScene) { super(0, 0, 435, 435, pGameScene); // 设置可以监听触碰事件 this.setIgnoreTouch(false); this.mGameScene = pGameScene; i

Java 实现2048游戏之详细教程

一.整体项目结构 使用Maven来管理项目结构 二.基本功能实现 (一)创建游戏窗口(静态) package com.baidu.czy; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.net.URI; import java.net.URL; import

C# GUI应用 实现 2048游戏

C# GUI应用 实现 2048游戏 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Gui { p

用javascript制作2048游戏的思路(原创若 转载请附上本链接)

一.项目已上传至github,地址:https://github.com/forjuan/2048game 二.学习了javascript基础后,想要捣鼓点东西做,做了一个自己以前很爱玩的2048游戏.经过初期的思路设计手工画了设计思路图.手工图有空在用图画出来. 实现2048的功能:1.核心:上下左右移动. 2.游戏开始,游戏结束. 3.外观实现. 4.积分(暂时没实现) 把问题分解:1.首要难点移动,将移动进行分解,分为上下左右移动: 2.用什么记录位置,怎样记录每个方块的值,边界,相同值相

2048游戏C语言代码

听说2048游戏实现起来很easy! 所以今天就试了试!确实不太难,要想编的很成功,也不是太容易!有很多细节需要考虑! 下面是我自己设计的代码,估计里面会漏洞百出!希望路过大神能指点一二! #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<time.h> #define WIN 256 // 可以修改决定游戏输赢的值 // 矩阵数组 int num[4][4]={0,0,0,0,0

用javascript实现一个2048游戏

早就想自己写一个2048游戏了,昨晚闲着没事,终于写了一个如下图,按方向键开始玩吧.如果觉得操作不方便,请直接打开链接玩吧:http://gujianbo.1kapp.com/2048/2048.html 附上源代码链接:https://github.com/gujianbo/js2048 个人博客地址:http://gujianbo.1kapp.com/ 新浪微博:http://weibo.com/gujianbobo 欢迎读者交流讨论并提出宝贵意见. 用javascript实现一个2048游