CocosCreator項目實戰(05):生成數字塊


一、找空閒位置

  1. 編寫一個找ROWS * ROWS塊中空閒位置的函數getEmptyLocations(),返回值爲一個表示空閒位置的數組。
    getEmptyLocations() {
        let locations = [];
        for (let i = 0; i < ROWS; ++i) {
            for (let j = 0; j < ROWS; ++j) {
                if (this.blocks[i][j] == null) {
                    locations.push({ x: i, y: j });
                }
            }
        }
        return locations;
    },

二、隨機生成2或4的塊

  1. 首先在game.js添加常量隨機數字NUMBERS數組
const NUMBERS = [2, 4];
  1. 因爲在遊戲開始時需要有一些隨機數字塊,因此在init()方法中添加addBlock()方法,並循環調用ROWS-1次。
    init() {
		...
        for (let i = 0; i < ROWS - 1; ++i) {
            this.addBlock();
        }
    },
  1. 編寫addBlock()方法,先調用getEmptyLocations()找到當前所有空閒位置,如果此時沒有空閒位置,直接返回false,如果有空閒位置則從其中隨機選擇一個位置,在該位置生成NUMBERS數組中隨機數的block,並將block保存到blocks數組,將該隨機數保存到number數組,返回true
    addBlock() {
        let locations = this.getEmptyLocations();
        if (locations.length == 0) {
            return false;
        } else {
            let location = locations[Math.floor(Math.random() * locations.length)];
            let x = location.x;
            let y = location.y;
            let position = this.positions[x][y];
            let block = cc.instantiate(this.blockPrefab);
            block.width = this.blockSize;
            block.height = this.blockSize;
            this.bg.addChild(block);
            block.setPosition(position);
            let number = NUMBERS[Math.floor(Math.random() * NUMBERS.length);
            block.getComponent('block').setNumber(number);
            this.blocks[x][y] = block;
            this.data[x][y] = number;
            return true;
        }
    },
  1. 預覽多次可看到每次生成不同的初始數字塊。

在這裏插入圖片描述
在這裏插入圖片描述


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章