size(500, 500);
int rows = 10;
int cols = 10;
int cellHeight = height/rows;
int cellWidth = width/cols;
textAlign(CENTER, CENTER);
textSize(28);
background(32);
for(int y = 0; y < rows; y++){
for(int x = 0; x < cols; x++){
//get a random ascii letter
char c = '!';
c += random(93);
//calculate cell position
int pixelX = cellWidth * x;
int pixelY = cellHeight * y;
//add half to center letters
pixelX += cellWidth/2;
pixelY += cellHeight/2;
fill(random(256));
text(c, pixelX, pixelY);
}
}
This code uses nested for
loops to draw a grid of random letters.
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
The code uses the char
type, which stores an individual letter as an ASCII code. In other words, it stores a letter as a number. This lets us get a random letter by doing this:
char c = '!';
c += random(93);
To understand these lines, take a look at the printable characters chart, and notice that !
is the first printable ascii value, starting with ascii code 33
. There are 93 other printable characters. So adding a random number from 0-93 to the !
character gives you a random ascii letter!
You could also use the ascii code directly instead of the letter it represents:
char c = 33;
c += random(93);
Anyway, this results in a grid of random letters.
This example uses nested for loops to show a grid of letters.
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!
Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!