简体   繁体   中英

2D Grid of objects in p5.js

What I am trying to do

I am trying to create a Battleships game and at the moment I am working on drawing the board so that each spot is an object. So that when the user clicks on them, they can select where to place their battleships. I am trying to do this through storing each spot as an object in an array called circles.

Grid

The problem

My problem is that when trying to create the objects, I can only seem to make the entire grid as one object. Here is the code I have so far (sorry for the quality, I am a noob!):

var circles = [];
var x = 100;
var y = 100;
for(i = 0; i < 2; i++) {
    circles[i] = {
        drawGrid: function() {
            for (var x = 100; x <= 1000; x += 100) {
                for (var y = 100; y <=1000; y += 100) {
                    fill(0);
                    ellipse(x,y,20,20);
                }
            }
        }
    }
}

function setup() {
    createCanvas(1100,1100);
}

function draw() {
    for(i = 0; i < 2; i++) {
        circles[i].drawGrid();
    }
}

I have tampered with the arrangement of the for loops (x, y and i) but nothing seems to work and if I try anything else, instead of getting a grid like the one below - with each O being an object:

O O O O 
O O O O
O O O O
O O O O

I will get something like one of these:

1) O O O O   | 2) O
   O         |      O
   O         |        O
   O         |          O

Any help is much appreciated, thank you!

i would make a constructor function for the circle, like this:

var circles = [];

function setup() {
  createCanvas(500, 500);
  //there's a "b" for every "a"
  for (var a = 10; a < width; a += 30) {
    for (var b = 10; b < height; b += 30) {
      //add the circles to the array at x = a and y = b
      circles.push(new Circle(a, b));
    }
  }
  console.log(circles.length);

}

function draw() {
  background(50);
  for (var b = 0; b < circles.length; b++) {
    circles[b].show();
    //console.log("shown");
  }
}

function Circle(x, y) {
  this.x = x;
  this.y = y;

  this.show = function() {
    fill(255);
    noStroke();
    ellipse(this.x, this.y, 10, 10);
    //console.log("showing");
  }
}

of course you'll have to play with the values a bit but this is the basic idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM