简体   繁体   English

p5.j​​s 中的 2D 对象网格

[英]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.我正在尝试创建一个 Battleships 游戏,目前我正在绘制棋盘,以便每个点都是一个对象。 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.我试图通过将每个点作为一个对象存储在一个名为 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:我已经篡改了 for 循环(x、y 和 i)的排列,但似乎没有任何效果,如果我尝试其他任何方法,而不是获得如下所示的网格 - 每个 O 都是一个对象:

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当然,您必须稍微调整一下这些值,但这是基本思想

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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