Quick actions

cmd+k|ctrl+k

Navigation

Languages

Four in a row

Snippet info

Language

JavaScript

Visibility

public

Author

linus.aspelin

Created

2018-10-17T12:48:54Z

Updated

2018-10-17T12:48:54Z

var state = Object.freeze({
    NotInitialized: 0,
    Playing: 1,
    Tie: 4,
    Player1Won: 5,
    Player2Won: 6,
});
var game = {
    width: 7,
    height: 6,
    state: state.NotInitialized,
    
    init: function() {
        this.state = state.Playing;
        this.player = 1;
        this.board = [];
        this.latest = undefined;
        this.winner = 0;

        for (let x = 0; x < this.width; x++) {
            this.board[x] = [];
        }
    },
    getAvailableCols: function() {
        var cols = [];
        if(this.winner == 0)
            for(let x in this.board)
                if(this.board[x].length < this.height)
                cols.push(x);

        return cols;
    },
    
    getWinner: function() {
        if(this.winner > 0)
            return this.winner;


        var deltas = [1,2,3];
        for(var x = 0; x < this.width; x++) {
            for(var y = 0; y < this.height; y++) {
                var player = this.board[x][y];
                var upperBound = y < this.height - 3;
                var lowerBound = y > 2;
                var rightBound = x < this.width - 3;
                if(player != undefined) {
                    if((upperBound && deltas.every(d => player == this.board[x][y+d])) //vertical  
                    || (rightBound 
                        && ((deltas.every(d => player == this.board[x+d][y])) //horizontal
                        || (upperBound && deltas.every(d => player == this.board[x+d][y+d])) //diagonal right up
                        || (lowerBound && deltas.every(d => player == this.board[x+d][y-d]))))) { //diagonal right down
                        return (this.winner = player);
                    }
                }
            }
        }
        return 0;
    },
    dropDisc: function(col) {
        if(this.board[col].length == this.height) {
            console.log("this column is full. Try another one!");
            console.log(`the available columns are ${this.getAvailableCols()}`);
            return false;
        }
        this.board[col].push(this.player);
        this.latest = { x: col, y: (this.board[col].length - 1) };
        if(this.getWinner() > 0)
        {
            this.state = state.Tie | this.winner;
        }
        else if(this.board.every(x => x.length == this.height))
        {
            this.state = state.Tie;
        }
        
        this.player ^= 3;
        return true;
    }
}

// game.init();
// console.log(game.board.length);
// console.log(game.getAvailableCols());
INFO