cocos creator实例--使用creator简单实现连连看游戏 | 附代码

游戏效果:

游戏玩法:

点击相同的两个动物图案,会消失一个选中框,然后就会消失掉。

游戏逻辑实现:

1.动物图案棋子的预制体

  • 这里我们每一个棋子,做成一个预制体;含有动物图案,边框,和点击事件。

  • 然后创建一个8*10的二维数组,保存每一个预制体棋子的实例;
            for(let i = 0; i < this.linesCount; i++){
                for(let j = 0; j < this.columnsCount; j++){
                    let tile = cc.instantiate(this.prefabTile).getComponent(GameTile);
                    tile.node.parent = this.node;
                    tile.node.x = (j + 0.5 - this.columnsCount * 0.5) * this.spaceX;
                    tile.node.y = (i + 0.5 - this.linesCount * 0.5 ) * this.spaceY;
                    this.tiles[i][j] = tile;
                }
            }

2.添加棋子类GameTile

  • 8个棋子,保存7中不同图案的棋子和一个空白棋子;
    @property([cc.SpriteFrame])
    sfTileType: cc.SpriteFrame[] = [];
  • 设置棋子的类型
setType(type: number){
        this.spTile.spriteFrame = this.sfTileType[type];
        this.type = type;
    }
  • 点击事件:
 onClick(){
        console.log("点击啦~~~~");
        //this.setType(0);
        this.main.onTileClick(this);
    }
  • 判断这个棋子是否被选中:
setIsSelected(isSelected: boolean){
        this.spFrame.node.active = isSelected;
    }

3.主控脚本GameMain:

  • 填充格子
    initBoard(){
        let type = 1;
        let count = 0;

        //循环:method 1
        for(let i = 0; i < this.linesCount; i++){
            for(let j = 0; j < this.columnsCount; j++){
                this.tileDatas[i][j] = type;
                count++;

                if(count == 2){
                    count = 0;
                    type++;

                    if(type == 7){
                        type = 1;
                    }
                }
                this.tiles[i][j].setType(type);
            }
        }
}
  • 随机打散棋牌
    randomBoard(){
        this.foreach((i: number, j: number) => {
            let swapi = Math.floor(Math.random() * this.linesCount);
            let swapj = Math.floor(Math.random() * this.columnsCount);

            //交换
            let temp = this.tileDatas[i][j];
            this.tileDatas[i][j] = this.tileDatas[swapi][swapj];
            this.tileDatas[swapi][swapj] = temp;
        });
    }
  • 刷新
refreshBoard(){
        this.foreach((i: number, j: number) => {
            this.tiles[i][j].setType(this.tileDatas[i][j]); 
        });
    }

点击棋子的响应处理:

onTileClick(tile: GameTile){
        if(!this.lastClickTile){
            tile.setIsSelected(true);
            this.lastClickTile = tile;
            return;
        }

        if(this.checkCanClenr(tile, this.lastClickTile)){

        }

        this.lastClickTile.setIsSelected(false);
        this.lastClickTile = null;
    }

游戏待优化完善的地方:

  • 没有加入一些特效,可以添加闪电等很绚丽的效果。
  • 代码结构可以进行优化。
  • 可以添加多个关卡,增加游戏趣味性。
  • 可以在游戏中尝试玩的时候改变图案位置。
  • 可以加入一些特殊功能的图案。
扫描二维码关注公众号,回复: 9781724 查看本文章

源码地址:

发布了265 篇原创文章 · 获赞 20 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ccnu027cs/article/details/104020476