Из того, как вы описали ожидаемый результат, кажется, что линии сетки и узлы, соединенные линиями, не связаны. Таким образом, вам нужно выполнить две задачи:
- Рисование сетки с
N_PARTITIONS
строками и линиями столбцов и - Рисование и соединение окружностей диаметром 10 с помощью щелчка мыши.
Первое относительно легко. Учитывая
final int N_PARTITIONS = 10;
, нам нужно 10 строк по экрану и 10 строк по экрану.
В пределах void setup()
используйте size(600, 360);
, чтобы установить размер холста равным 600x360 пикселей.
Давайте сначала обработаем рисование линий на экране. Для этого мы будем использовать цикл for
.
void draw() {
int distVertLine = width / N_PARTITIONS; // This variable defines the distance between each subsequent vertical line.
for(int i = distVertLine / 2; i < width; i += distVertLine) {
line(i, 0, i, height); // Draw a line at x=i starting at the top of the canvas (y=0) and going to the bottom (y=height)
}
}
Выше мы инициализируем переменную distVertLine
для определения горизонтального расстояния между каждой вертикальной линией. Его значение равно width / N_PARTITIONS
, потому что мы разделяем ширину холста на заданное количество разделов.
В цикле for
i
инициализируется как distVertLine / 2
, так что линии сеткинаходятся в центре.
Аналогично, мы можем сделать это с горизонтальными линиями:
int distHorizLine = height / N_PARTITIONS; // This variable defines the distance between each subsequent vertical line.
for(int i = distHorizLine / 2; i < width; i += distHorizLine) {
line(0, i, width, i); // Draw a line at y=i starting at the left of the canvas (x=0) and going to the right (x=width)
}
Сейчасдля узлов и линий. Круг при обработке задается как circle(x, y, extent)
(см. Документы здесь ).
При нажатии мыши вызывается метод void mousePressed()
. При каждом нажатии мы хотим записать значения x
и y
в массиве:
ArrayList nodeX = new ArrayList(); // ArrayLists are nice to use because they're expandable, unlike a Processing array.
ArrayList nodeY = new ArrayList(); // ArrayLists are nice to use because they're expandable, unlike a Processing array.
void mouseClicked() {
nodeX.add(mouseX); // Adds the x-position of the mouse pointer to the nodeX list.
nodeY.add(mouseY); // Adds the y-position of the mouse pointer to the nodeY list.
}
В void draw()
установить цикл for
, который рисует окружности по координатам в обоихсписки:
stroke(0); // Set the circle's outline as black.
for(int i = 0; i < nodeX.size(); i++) {
float xPos = (int)nodeX.get(i); // Grab the ith x-position from the list.
float yPos = (int)nodeY.get(i); // Grab the ith y-position from the list.
circle(xPos, yPos, 10); // Draw a circle of diameter 10 at (xPos, yPos).
}
(Обратите внимание, в первой строке void draw()
я добавил
background(255); // Set the background color to white
stroke(125); // Set the stroke color as gray.
, чтобы сделатькруги легче видеть).
Наконец, нам нужно соединить каждый круг линией.
stroke(0, 0, 255); // Make the connecting lines blue.
for(int i = 0; i < nodeX.size() - 1; i++) {
float xPosA = (int)nodeX.get(i); // Grab the ith x-position from the list.
float yPosA = (int)nodeY.get(i); // Grab the ith y-position from the list.
float xPosB = (int)nodeX.get(i+1); // Grab the next x-position from the list.
float yPosB = (int)nodeY.get(i+1); // Grab the next y-position from the list.
line(xPosA, yPosA, xPosB, yPosB);
}
// And draw the connecting line.
if(nodeX.size() > 0) { // The code in this block will crash unless this condition is added to handle an empty list.
int size = nodeX.size() - 1; // Get the index of the last item in nodeX/nodeY.
float xPosA = (int)nodeX.get(0); // Grab the first x-position from the list.
float yPosA = (int)nodeY.get(0); // Grab the first y-position from the list.
float xPosB = (int)nodeX.get(size); // Grab the last x-position from the list.
float yPosB = (int)nodeY.get(size); // Grab the last y-position from the list.
line(xPosA, yPosA, xPosB, yPosB);
}