Создание игры в жанре памяти с помощью Phaser Framework .... Различные проблемы - PullRequest
0 голосов
/ 19 сентября 2018

Начнем с того, что моя текущая проблема связана с тем, что я хочу, чтобы в phaser были расположены 2 карты в формате 6x4.Из них на каждой клетке будет 2 карты, одна из которых представляет собой простую карту с буквой, а другая является задним концом карты (и все карты будут иметь это покрытие).Когда я щелкаю, карточки показывают, что под ними, и когда они щелкают по другой карточке, и это соответствует, вы получаете балл.

Массив, в котором я хранил буквы, заставляет буквы показываться хорошо, а непокажите 2 каждой буквы, иногда она показывает 4 одинаковых буквы, а иногда только одну или не указывается вообще, учитывая, что я поместил только правильное количество элементов в массиве, которые нужно перемешать и отобразить на карточках.

Помимо базовых тегов HTML и сценариев, ведущих к моим main.js и phaser.min.js (или phaser.js в зависимости от того, как я сохранил файл), ниже приведен код:

    var game = new Phaser.Game(1000,750,Phaser.CANVAS,'gameDiv');

    var background_pic;

    var card_1;
    var CardStacks;

    var text;

    var card_back;
    var card_BackStacks;

    // var firstClick, secondClick;

    var score;

    // var myCountdownSeconds;

    // var array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];

var array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'];


var mainState = {

    preload: function() {

        // game.load.image('backgrounds', "assets/bg.jpg");
        game.load.image('Card_1', "assets/cards/plain.png");
        game.load.image('Back', "assets/cards/back.png");
    },

    create: function() {
        game.add.text(380, 10, 'Sun-Tiles', 
            {fill : 'blue',
            fontSize : '50px'
        });

        score = game.add.text(800, 30, 'Score: 0', 
            {fill : 'white',
            fontSize : '20px'
        });

        card_1 = game.add.sprite(0,0, 'Card_1');
        card_1.anchor.setTo(0);
        card_1.visible = false; //sets original tile invisible by default.

        card_1 = game.add.group();
        card_1.enableBody = true;
        card_1.physicsBodyType = Phaser.Physics.ARCADE;

        createTiles();

        text = game.add.group();
        // text.enableBody = true;
        // text.physicsBodyType = Phaser.Physics.ARCADE;

        // var score = game.add.group();
        // score.add(game.make.text(10,10, "Score: " + 100,  { font: "32px Arial", fill: generateHexColor() }))

        card_back = game.add.sprite(0,0, 'Back');
        card_back.anchor.setTo(0);
        card_back.visible = false;  //sets original tile invisible by default.

        card_back = game.add.group();
        card_back.enableBody = true;
        card_back.physicsBodyType = Phaser.Physics.ARCADE;

        // createBackTiles();

        // scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#' });
    },

    update: function() {
    }
}

// function countScore () {
// counting number of matches

//     //  Add and update the score
//     // score += 15;
//     scoreText.text = 'Score: ' + score;

// }

function createTiles() {
    for(var y = 0; y < 4; y++) {
        for(var x = 0; x < 6; x++) {
            CardStacks = game.add.sprite(x*160 + 20,y*160 + 90,'Card_1');

            card_1.inputEnabled = true;

            var style = { font: "100px Chiller", fill: "blue", wordWrap: true, wordWrapWidth: 150, align: "center"}; //The style to be applied to the text on cards.

            Phaser.ArrayUtils.shuffle(array);

            text = game.add.text(0,0, Phaser.ArrayUtils.getRandomItem(array), style);
            text.x = 40; text.y = 20; //setting all the text to the right spot along the X and Y axis on the blank card.
            CardStacks.addChild(text); // making the text variable a child of the tile(blank card) variable. 

            // card_BackStacks = game.add.sprite(x*160 + 20,y*160 + 90,'Back'); //to reveal the unflipped cards
        }
    }

    tween.onLoop.add(descend,this);
}

game.state.add('mainState', mainState);

game.state.start('mainState');

1 Ответ

0 голосов
/ 19 сентября 2018

Для каждой карты вы перетасовываете свой массив букв и выбираете случайный.Это не удаляет элемент из массива, а это означает, что для следующей карты вы можете легко выбрать один и тот же элемент случайно:

for (var y = 0; y < 4; y++) {
  for (var x = 0; x < 6; x++) {
    // ...

    Phaser.ArrayUtils.shuffle(array);
    text = game.add.text(0, 0, Phaser.ArrayUtils.getRandomItem(array), style);
  }
}

Вместо этого перемешайте массив один раз ,перед вашей петлей.Затем в цикле удалите по одному элементу для каждой карты, чтобы избежать дублирования:

var shuffledCards =Phaser.ArrayUtils.shuffle(Array.from(array));

for (var y = 0; y < 4; y++) {
  for (var x = 0; x < 6; x++) {
    // ...

    text = game.add.text(0, 0, shuffledCards.pop(), style);
  }
}
...