简体   繁体   English

使用嵌套的for循环绘制棋盘格

[英]Drawing a Checkerboard using nested for loops

I have a couple of questions regarding the use of nested for loops. 关于嵌套循环的使用,我有几个问题。 In this example in the book it uses nested for loops to draw a typical checkerboard. 在本书的这个示例中,它使用嵌套的for循环绘制典型的棋盘格。

1) Is my understanding correct when I assume the code below says the sequence of drawing the checkerboard squares will be vertically down from left to right until the entire checkerboard is drawn? 1)当我假设以下代码说棋盘方格的绘制顺序从左到右垂直向下直到绘制整个棋盘时,我的理解是正确的吗?

2) I'm have some questions about the purpose of double x, and double y inside the inner most for loop. 2)我对最里面的for循环中double x和double y的用途有疑问。 Are they being calculated for the purpose of spacing one square to the next? 是否计算它们是为了将一个正方形与另一个正方形隔开? Can you expand on the purpose of double x and double y and what occurs each cycle of one loop? 您是否可以针对double x和double y进行扩展,以及一个循环的每个循环会发生什么?

import acm.program.*;
import acm.graphics.*;




public class checkerBoard extends GraphicsProgram{
    public void run(){


        double sqSize = getHeight() / N_ROWS;
        for ( int i = 0; i < N_ROWS; i++){
            for (int j = 0; j < N_COLUMNS; j++){
                double x = j * sqSize;
                double y = i * sqSize;

                GRect rect = new GRect(x, y, sqSize, sqSize);
                rect.setFilled((i+ j) % 2 !=0);
                add(rect);

            }

        }

    }


    private static final int N_ROWS = 8;
    private static final int N_COLUMNS = 8;


}

1) Is my understanding correct when I assume the code below says the sequence of drawing the checkerboard squares will be vertically down from left to right until the entire checkerboard is drawn? 1)当我假设以下代码说棋盘方格的绘制顺序从左到右垂直向下直到绘制整个棋盘时,我的理解是正确的吗?

This is correct. 这是对的。 Row by row, left to right, top to bottom. 一行一行,从左到右,从上到下。

2) I'm have some questions about the purpose of double x, and double y inside the inner most for loop. 2)我对最里面的for循环中double x和double y的用途有疑问。 Are they being calculated for the purpose of spacing one square to the next? 是否计算它们是为了将一个正方形与另一个正方形隔开? Can you expand on the purpose of double x and double y and what occurs each cycle of one loop? 您是否可以针对double x和double y进行扩展,以及一个循环的每个循环会发生什么?

They are the coordinates of the location where to draw the next square. 它们是绘制下一个正方形的位置的坐标。 Specifically, they are the coordinate for the upper left part of the square. 具体来说,它们是正方形左上部分的坐标。 You can figure out the start points for all squares by simply multiplying by the width of the squares, as they have done. 您可以通过简单地乘以正方形的宽度来算出所有正方形的起点,就像这样做一样。

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

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