CocosCreator项目实战(08):计分与失败检测


一、计分

  1. 游戏的计分规则为:每当两个相同数字块合并时,就加上这两个数字块的分值,比如2和2合并为4时,分数会加上4分。
    所以修改moveDirection(direction)中的Merge相关操作更改score即可,然后在afterMove(hasMoved)方法中调用updateScore()方法。
    moveDirection(direction) {
		···
        let move = (x, y, callback) => {
			···
            if (condition || this.data[x][y] == 0) {
				···
            } else if (this.data[destX][destY] == 0) {
                // Move
				···
            } else if (this.data[destX][destY] == this.data[x][y]) {
                // Merge
				···
                // Add score
                this.score += this.data[destX][destY];
            } else {
				···
            }
        };
        ···
    },
    
    afterMove(hasMoved) {
        if (hasMoved) {
            this.updateScore(this.score);
            this.addBlock();
        }
    },
  1. 预览可得,Score发生变化。

在这里插入图片描述


二、失败检测

  1. 失败条件为:a. 没有剩余空间快;b. 每一个数字块与其相邻的所有数字块均不相同。
  2. 修改afterMove(hasMoved)方法,在每次移动完做checkFail()检查
    afterMove(hasMoved) {
		...
        if (this.checkFail()) {
            this.fail();
        }
    },
  1. 编写checkFail()方法。按照a. 是否有剩余空块;b. 没有空块的情况下是否有相邻格数字相同的顺序做判断。
    checkFail() {
        for (let i = 0; i < ROWS; ++i) {
            for (let j = 0; j < ROWS; ++j) {
                let n = this.data[i][j];
                if (n == 0) return false;
                if (j > 0 && this.data[i][j - 1] == n) return false;
                if (j < ROWS - 1 && this.data[i][j + 1] == n) return false;
                if (i > 0 && this.data[i - 1][j] == n) return false;
                if (i < ROWS - 1 && this.data[i + 1][j] == n) return false;
            }
        }
        return true;
    },
  1. 先简单定义fail()方法为在控制台简单打印Game Over!
    gameOver() {
        console.log('Game Over!');
    },
  1. 为了能快速预览失败检测,将game.js设置的常量ROWS改为2。可看到当失败时控制台打印Game Over!
const ROWS = 2;

在这里插入图片描述


发布了97 篇原创文章 · 获赞 10 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Fan0628/article/details/104711676