问题
When I click anywhere on the display window, circle of diameter 10 (henceforth called a node) should be displayed at that point. Nodes from previous clicks should stay on the screen and there should be lines that join each node with the next one (and the last is joined to the first node). There should be no other lines besides these lines (and the grid lines of course).
When I click at any location, the node should be generated at the closest grid intersection point.
//code for grid
int n_part=10;
void setup () {
size (600, 360);
}
void draw () {
background (255);
int gridW= width/n_part;
int gridH=height/n_part;
stroke(210);
for (int row = 0; row < n_part; row++){
int gridY = 0 + row*gridH;
for (int col = 0; col < n_part; col++) {
int gridX = 0+ col* gridW;
rect (gridX, gridY, gridW, gridH);
}
}
}
I expect when i click the mouse on grid a node should appear on closest grid. and after clicking mouse once again another node should appear and an edge between these two nodes.
回答1:
Create a class which can store point and its size (radius). The class has a constructor and a method to draw the point respectively circle.
class Point {
int x, y, r;
Point(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
void Draw() {
circle(this.x, this.y, this.r*2);
}
}
Use ArrayList of Point objects to store the points
ArrayList<Point> points = new ArrayList<Point>();
Use mousePressed() event callback to add anew point to the list
void mousePressed() {
int gridW = width/n_part;
int gridH = height/n_part;
int x = round(mouseX / (float)gridW) * gridW;
int y = round(mouseY / (float)gridH) * gridH;
points.add(new Point(x, y, 5));
}
Draw the points in a loop. The lines can be created by drawing a line()
between to consecutive points from the list. e.g.:
void draw () {
background (255);
int gridW = width/n_part;
int gridH = height/n_part;
strokeWeight(1);
stroke(210);
noFill();
for (int row = 0; row < n_part; row++){
int gridY = 0 + row*gridH;
for (int col = 0; col < n_part; col++) {
int gridX = 0+ col* gridW;
rect (gridX, gridY, gridW, gridH);
}
}
strokeWeight(3);
stroke(0, 0, 255);
for (int i = 0; i < points.size(); ++ i) {
Point p1 = points.get(i);
Point p2 = points.get((i+1) % points.size());
line(p1.x, p1.y, p2.x, p2.y);
}
strokeWeight(1);
stroke(0, 0, 0);
fill (255, 0, 0);
for (int i = 0; i < points.size(); ++ i) {
Point p = points.get(i);
p.Draw();
}
}
来源:https://stackoverflow.com/questions/58533932/what-types-of-arraycode-will-work-for-this-question