vendredi 31 juillet 2015

How to check arrays for equality between multiple values?

So I'm trying to build a tic-tac-toe game that involves the user playing against a the computer. I would like these arrays to check for a winning sequence of blocks that will indicate someone has won the game. I'm wondering if this method of checking different parts of an array and comparing them for equality is valid?

function winner() {
    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'X' || blocks[0, 3, 6].value == 'X' || blocks[2, 5, 8].value == 'X' || blocks[6, 7, 8].value == 'X' || blocks[2, 4, 6].value == 'X' || blocks[0, 4, 8].value == 'X') {
            alert('Player X Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }
    };

    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'O' || blocks[0, 3, 6].value == 'O' || blocks[2, 5, 8].value == 'O' || blocks[6, 7, 8].value == 'O' || blocks[2, 4, 6].value == 'O' || blocks[0, 4, 8].value == 'O') {
            alert('Player O Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }

    }
}

Also, is this a viable way to dictate whose turn it is? I had a little success with this class switching mechanism to determine which blocks have been chosen in the beginning but can't seem to make it work now.

This is the code for changing turns and class switching so far but I'm sure there's a better way:

var player === 1

var blocks = document.getElementsByClassName('block');

function turn() {
    if (player === 1) {
        player -= 1;
        winner();
        var buttons = document.getElementsByTagName("button");
        console.log(buttons.length);
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener("click", function(e) {
                var number = (this.getAttribute('name'));
                var chosenblock = document.getElementsByName(number)[0];
                chosenblock.classList.toggle('chosen');
                chosenblock.value = 'X';
                // console.log('click!');
            });
        }
    } else {
        player += 1;
        winner();
        var computer;
        computer = function() {
                var computerchoice = Math.floor(Math.random() * (9) + 1);

                function compselected(number) {
                    //How to make number equal to the id of the selected block?
                    var chosenblock = document.getElementsByName(number)[0];
                    chosenblock.classlist.toggle('picked');
                }

Any advice is appreciated thanks guys! Here's the fiddle if that helps.

Aucun commentaire:

Enregistrer un commentaire