简体   繁体   English

需要帮助来理解绘制棋盘的代码

[英]Need assistance for understanding code for drawing a checkerboard

The book uses this code to draw a checkerboard. 本书使用此代码绘制棋盘格。 The only problem I'm having is understanding the sequence of how the individual squares on drawn on the checkerboard. 我唯一的问题是了解棋盘格上各个正方形的绘制顺序。 When I do my calculations it only fills the checkerboard with squares in a diagonal direction from top left to bottom right. 当我进行计算时,它只会在棋盘上从左上角到右下角的对角线方向填充正方形。 The book says the code does this loop 64 times for every square but I'm not sure how it does this 64 times. 这本书说代码对每个方块执行此循环64次,但是我不确定它如何执行64次。

For example lets say getHeight() = 72 例如,假设getHeight()= 72

sqSize = 9 sqSize = 9

moving in the inner most loop 在最内层循环
double x = 0 * 9 ===> 0 双x = 0 * 9 ===> 0
double y = 0 * 9 ===> 0 双重y = 0 * 9 ===> 0
GRect (0, 0, 9, 9,); GRect(0,0,9,9,);

double x = 1 * 9 ===> 9 双x = 1 * 9 ===> 9
double y = 1 * 9 ===> 9 双y = 1 * 9 ===> 9
GRect (9, 9, 9, 9,); GRect(9,9,9,9,);

double x = 2 * 9 ===> 18 双x = 2 * 9 ===> 18
double y = 2 * 9 ===>18 双y = 2 * 9 ===> 18
GRect (18, 18, 9, 9); GRect(18,18,9,9);

etc... 等等...

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

public class Checkerboard extends GraphicsProgram {

public void run(){

double sqSize = (double) 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 sq = new GRect(x, y, sqSize, sqSize);
           sq.setFilled(( i + J ) % 2 !=0); 

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

You have two loops - the second loop cycles through each value 0-7, and does so a total of 8 times, because that's how many times the first loop runs. 您有两个循环-第二个循环在每个值0-7之间循环,总共执行8次,因为这是第一个循环运行的次数。 It appears in your explaination that you are incrementing both values at the same time, as if there was only one loop that increments both values each time through. 在您的解释中,您似乎同时增加了两个值,好像每次循环中只有一个循环使两个值都增加一样。

It may be helpful to print the values of i and j inside your loop. 在循环内打印ij的值可能会有所帮助。

(i,j)

(0, 1) (0, 2) (0, 3) ...
(1, 1) (1, 2) (1, 3) ...
...

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

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