0

Below is my full code. For some reason it fails when setting board[2][0] and I can't see why. I'm sure it's something simple though...

function randColor() {
    min = Math.ceil(0);
    max = colors.length;
    return colors[Math.floor(Math.random() * (max - min)) + min]; 
}

const colCount = 10;
const rowCount = 10;

var board = [[],[]];

const colors = ["#f00","#0f0","00f"];

class piece {
    constructor(value, color) {
        this.value = value;
        this.color = color;
    }
}

for (var x = 0; x < colCount; x++) {
    for (var y = 0; y < rowCount; y++) {
        var p = new piece('b',randColor());
        console.log("Setting board[" + x + "][" + y + "]");
        board[x][y] = p;
    }
}

1 Answer 1

1

It's failing because you are creating your board incorrectly. It fails at 2 because you have [[ ],[ ]]. It would fail at 1 if you had [[ ]]..and so on for 3 etc.

Also your row is your outer loop and columns are your inner loop. The following will do what you need.

function randColor() {
    min = Math.ceil(0);
    max = colors.length;
    return colors[Math.floor(Math.random() * (max - min)) + min]; 
}

const colCount = 10;
const rowCount = 10;

var board = [];

const colors = ["#f00","#0f0","00f"];

function piece(value, color) {
    this.value = value;
    this.color = color;
}

for (var x = 0; x < rowCount; x++) {
    board[x] = [];
    for (var y = 0; y < colCount; y++) {
        var p = piece('b', randColor());
        console.log("Setting board[" + x + "][" + y + "]");
        board[x][y] = p;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.