I want to print a chess/checkers board and with the help of a tutorial came to this code. I understand everything that's happening apart from this line: rect(i * squareSize,j * squareSize,squareSize, squareSize);
The thing I do not get is why you multiply i by the variable squareSize.
My first intuition was to the rects inside the if/else statements below the fill functions and not below the else.
Can anyone explain to me what I am missing and why my method does not work and multiplying by squareSize is necessary?
I have added my working code as a snippet below.
const WIDTH = 400;
const HEIGHT = 400;
const ROWS = 10;
const COLS = 10;
var squareSize = WIDTH/10;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
drawBoard();
}
function drawBoard(){
for(var i = 0; i < ROWS; i++)
{
for(var j = 0; j < COLS; j++)
{
if((i+j) % 2 == 0)
{
fill(0);
}
else
{
fill(255);
}
rect(i * squareSize,j * squareSize,squareSize, squareSize);
}
}
noLoop();
}
html, body {
margin: 0;
padding: 0;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.1/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
why my method does not work
I'm a bit confused: your code seems to work fine. What's not working about it?
The thing I do not get is why you multiply i by the variable squareSize.
One of the best things you can do when you have a question like this is to get out some graph paper and draw out a few examples.
Let's say you have a paper that's 1000x1000, and you want to draw a 10x20 (10 columns x 20 rows) grid on it.
Notice that for the x and y values of each column and row, we're multiplying the column or row index (your i
and j
variables) by the size of the columns and rows (your squareSize
variable).
If this still isn't clear, try drawing out a few examples.