Lukas Knudsen
Lukas Knudsen

Reputation: 339

Cannot read property of undefined - p5js

I am making a simple mine sweeper game. I am using p5js and i keep getting this error. ## Uncaught TypeError: Cannot read property 'isMine' of undefined(…) sketch.js:34 ##.

sketch.js -

var cells = [];

function createCells() {
    var x = 0;
    var y = 0;

    for(var i = 0; i < 100; i++) {
        cells[i] = new Cell(x, y, 255);
        x += 50;

        if(x >= 500) {
            y += 50;
            x = 0;
        }
    }
}

function setup() {
    createCanvas(501, 501);
    frameRate(60);

    createCells();

    for(var i = 0; i < 5; i++) {
        var rd = random(cells);
        if(!cells[rd].isMine()) {
            cells[rd].setMine();
        } else {
            i--;
        }
    }
}

function draw() {
    background(50);

    for(var i = 0; i < cells.length; i++) {
        cells[i].show();
    }
}

function mousePressed() {
    for(var i = 0; i < cells.length; i++) {
        if(mouseX < cells[i].x + cells[i].w && mouseX > cells[i].x) {
            if(mouseY < cells[i].y + cells[i].h && mouseY > cells[i].y) {
                if(!cells[i].mine) {
                    cells[i].cOlor = 'rgb(0, 153, 0)';
                }
            }
        }
    }
}

cell.js -

function Cell(x, y, cOlor) {
    this.w = 50;
    this.h = 50;
    this.x = x;
    this.y = y;
    this.cOlor = cOlor;
    this.mine = false;

    this.setMine = function() {
        this.mine = true;
    }

    this.isMine = function() {
        return this.mine;
    }

    this.show = function() {
        fill(this.cOlor);
        stroke(0);
        rect(this.x, this.y, this.w, this.h);
    }
}

Thanks on advance for any help. :)

Upvotes: 1

Views: 5467

Answers (2)

Gerdaho
Gerdaho

Reputation: 11

To get a random index you can use the length of the array and floor it to get an integer, like this:

var rd = floor(random(cells.length));

Hope that helps

Upvotes: 0

Thierry
Thierry

Reputation: 5233

random(cells) returns an element of the array (a Cell object), not an index. So try this:

for(var i = 0; i < 5; i++) {
    var cellRandom = random(cells);
    if(!cellRandom.isMine()) {
        cellRandom.setMine();
    } else {
        i--;
    }
}

See https://p5js.org/reference/#/p5/random

Upvotes: 1

Related Questions