JS: How do I create a 10x10 grid of filled rectangles? - javascript

I'm trying to create 100 filled rectangles in a 10x10 grid. Each of these rectangles is 20px*20px big, and 20px apart from each other. I completely understand the logic behind it, and roughly how to put it into code, but there is one part I can't seem to get my head around; how I make the rectangles appear on the next line after the first 10 have been drawn.
I've got a fiddle here with my current progress: http://jsfiddle.net/z3wsxa8j/
As you can see, they go diagonally. I understand why, because X and Y keep getting +40px added to their coordinates. If I remove the yvalue += 40; part, they all go on the same row, obviously. I don't know how I can elegantly make them go on another row after reaching 10 rectangles. I tried using if/else statements, so when there's 11 rectangles, make it my_context.fillRect(xvalue,40,20,20); ...
if it's 21 rectangles
my_context.fillRect(xvalue,80,20,20); and so on.
But that would A) result in a lot of if statements and B) It didn't even work (they printed on the same line, still).
Any hints are appreciated, thanks!

Every 10th square, you'll need to do 2 things:
Increase the "y" value to move down to the next line, and
Set the "x" value back to 0
Also, you need to make sure you only do 100 boxes and not 101:
for (var x = 0; x < 100; x++) {
my_context.fillRect(xvalue, yvalue, 20, 20);
xvalue += 40;
if ((x+1) % 10 === 0) {
yvalue += 40;
xvalue = 0;
}
}
The value of (x+1) % 10 will be 0 when "x" is 9, 19, 29, etc.

Basically start drawing with one axis 10 rects using an inner loop, and repeating that with 40px shiftign for the other axis, repeating it 10 times JS Fiddle
NOTE: that in your code you have (var x = 0; x <= 10; x++) this will draw 11 rectangles not 10, because you started from 0 and ended at 10, so it should be (var x = 0; x < 10; x++) instead of <=
var canvas = document.getElementById("canvas");
var my_context = canvas.getContext('2d');
my_context.strokeStyle = "white"; // Draws the canvas border
my_context.rect(0, 0, 1000, 1000);
my_context.stroke();
my_context.fillStyle = "white";
var xvalue = 0;
var yvalue = 0;
for (var y = 0; y < 10; y++) {
for (var x = 0; x < 10; x++) {
my_context.fillRect(xvalue, yvalue, 20, 20);
xvalue += 40;
}
xvalue = 0;
yvalue += 40;
}
body {
background-color: gray;
margin: 0px;
overflow: hidden;
}
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
</body>

Just use an x and a y loop instead of one big loop:
for (var x = 0; x <= 10; x++) {
for (var y = 0; y <= 10; y++) {
my_context.fillRect(x*40, y*40, 20, 20);
}
}

Try using nested for loops:
var canvas = document.getElementById("canvas");
var my_context = canvas.getContext('2d');
my_context.strokeStyle = "white"; // Draws the canvas border
my_context.rect(0, 0, 1000, 1000);
my_context.stroke();
my_context.fillStyle = "white";
var step = 40;
for (var x = 0; x <= 10; x++) {
for(var y = 0; y <= 10; y++) {
my_context.fillRect(x*step, y*step, 20, 20);
}
}
This code draws the rectangles column by column. Here's a fiddle.

You can accomplish this using single if statement and a variable to keep track of number of boxes drawn in a row. When 10 boxes are drawn reset the count and increment the y value.
Updated Fiddle: Demo
var canvas = document.getElementById("canvas");
var my_context = canvas.getContext('2d');
my_context.strokeStyle = "white"; // Draws the canvas border
my_context.rect(0, 0, 1000, 1000);
my_context.stroke();
my_context.fillStyle = "white";
var xvalue = 0;
var yvalue = 0;
var boxes = 1;
for (var x = 0; x <= 100; x++) {
if(boxes>10){
boxes = 1;
xvalue = 0;
yvalue += 40;
}
boxes++;
my_context.fillRect(xvalue, yvalue, 20, 20);
xvalue += 40;
}

As others have stated you can have a for loop within a for loop, such that you increment each row first, then increment each column.
http://jsfiddle.net/z3wsxa8j/10/
var canvasSize = 1000;
var blockSize = 20;
var numBlocks = canvasSize/blockSize;
// Outer loop for each columns
for (var i = 0; i < numBlocks; i++) {
xvalue = 0;
yvalue = blockSize*i;
// Inner loop for the rows
for (var j = 0; j < numBlocks; j++) {
my_context.fillRect(xvalue, yvalue, blockSize, blockSize);
xvalue += blockSize;
}
}

Related

Cursor trail algorithm for p5.js

I found this little coding exercise on Processing's website (https://processing.org/examples/storinginput.html) and decided to make a p5.js version of it.
The part that I do not understand about this algorithm is how the ellipses drawn (in the trail) shrinks when variable i, which is used as the scale of the ellipse, is increasing. I suspect that it has something to do with the value of variable index but I am unable piece it together.
Does anyone know how this algorithm works? Any help would be appreciated.
Here is the Javascript version of code:
var num = 60;
var mx = [];
var my = [];
function setup() {
createCanvas(windowHeight, windowHeight);
noStroke();
fill('rgba(0,0,0, 0.5)');
noCursor();
}
function draw() {
background(255);
var array_pos = (frameCount) % num;
mx[array_pos] = mouseX;
my[array_pos] = mouseY;
for (var i = 0; i < num; i++) {
var index = (array_pos + 1 + i) % num;
ellipse(mx[index], my[index], i, i);
}
}
The current mouse position is stored in an array in every frame. When the array is full, it will be filled again from the beginning. This is achieved using the modulo (%) operator (% computes the remainder of a division).
var array_pos = frameCount % num;
mx[array_pos] = mouseX;
my[array_pos] = mouseY;
The diameter of the circle depends on the control variable of the loop (i). The smallest circle is the circle with index array_pos + 1. Therefore with i == 0 the circle with the index array_pos + 1 is drawn. The following circles become larger as i increases. Again, the modulo operator (%) is used to prevent the array from being accessed out of bounds.
var index = (array_pos + 1 + i) % num;
var num = 60;
var mx = [];
var my = [];
function setup() {
createCanvas(windowWidth, windowHeight);
noCursor();
}
function draw() {
var array_pos = frameCount % num;
mx[array_pos] = mouseX;
my[array_pos] = mouseY;
background(255);
noStroke();
fill(255, 0, 0, 127);
for (var i = 0; i < num; i++) {
var index = (array_pos + 1 + i) % num;
ellipse(mx[index], my[index], i, i);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

Using for loop to print grid in JavaScript

I am trying to create a small grid for connect four game using a four loop. I have printed circles for X and Y axis but I have only been able to print 1 row successfully, I am trying to print this seven times across the canvas but the for loop I have created does not seem to work.
var x = 30;
var y = 30;
function setup(){
createCanvas(300,300);
background(0);
for(i=0; i<=6; i++){
for(i=0; i<=6; i++){
x+=30;
circle(x, y, 20);
for(i=0; i<=6; i++){
y+=30;
circle(x, y, 20);
}
}
}
}
setup();
I am trying to achieve this:
Change your loop structure - iterate 7 times and increase y at the end of each iteration, and iterate within this loop where you render the circle, and increase x:
for (let i = 0; i < 6; i++) {
x = 30;
for (let j = 0; j < 7; j++) {
circle(x, y, 20);
x += 30;
}
y += 30;
}
You do have three loops that use i, and actually all loops will work on the same number, therefore the inner loop will loop 6times, than all three loops end. As your aim is to loop over x and y, just use them:
for(let x = 1; x < 6; x++) { // always declare variables with let!
for(let y = 1; y < 6; y++) {
circle(x * 30, y * 30, 20); // just keep as many varoables as necessary, the position can easily be derived from the index
}
}
Maybe this is what you need:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = (canvas.width = 300),
cx = cw / 2;
let ch = (canvas.height = 300),
cy = ch / 2;
//the circles radius
let ar = 30;
//the red and yellow clees index
let red = [10, 23, 30, 31, 37, 40];
let gold = [16, 17, 24, 32, 38, 39];
let n = 0;// a counter
let cellw = cw / 7;// the width of a cell
//the loop:
for (let y = cellw / 2; y < ch; y += cellw) {
for (let x = cellw / 2; x < cw; x += cellw) {
ctx.beginPath();
ctx.arc(x, y, ar / 2, 0, 2 * Math.PI);
//set the color of the circles
for (let i = 0; i < red.length; i++) {
if (n == red[i]) {
ctx.fillStyle = "red";
break;
} else if (n == gold[i]) {
ctx.fillStyle = "gold";
break;
} else {
ctx.fillStyle = "white";
}
}
ctx.fill();
n++;
}
}
body {
background-color: #222;
overflow: hidden;
}
canvas {
background-color: #000;
display: block;
position:absolute;
margin: auto;
top:0;bottom:0;left:0;right:0
}
<canvas id="canvas"></canvas>
Yep, there's a problem in the for loop.
You just need to 2 loops for that.
for (let row = 0; row <= 6; row++) {
for (let column = 0; column <= 6; column++) {
circle(row * 30, column * 30, 20)
}
}

Smoothing algorithm for map tiling in JavaScript

I'm using JsIso (found it on github) to (hopefully) make a fun little browser game. I modified the hardcoded values for a height map, into a variable and function to generate terrain randomly. What I would like to do, but can't picture in my head at all, is to have a given tile no more or less than 2 levels different than the tile next to it, getting rid of towers and pits.
This is my current code:
var tileHeightMap = generateGround(10, 10); //Simple usage
function generateGround(height, width)
{
var ground = [];
for (var y = 0 ; y < height; y++)
{
ground[y] = [];
for (var x = 0; x < width; x++)
{
ground[y][x] = tile();
}
}
return ground;
function tile()
{
return (Math.random() * 5 | 0);
}
}
It looks like it would be best to modify the tile function, perhaps passing it the value of the previous tile, and not the generate ground function. If more info is needed, let me know!
You can use a two-dimensional Value Noise.
It basically works like this:
Octave #1: Create a number of random points (8, for example) that are evenly spaced in x direction and interpolate between them (if you choose linear interpolation, it could look like this):
Octave #2: Do the same thing as in #1, but double the amount of points. The amplitude should be the half of the amplitude in #1. Now interpolate again and add the values from both octaves together.
Octave #3: Do the same thing as in #2, but with the double amount of points and an amplitude that is the half of the amplitude in #2.
Continue these steps as long as you want.
This creates a one-dimensional Value Noise. The following code generates a 2d Value Noise and draws the generated map to the canvas:
function generateHeightMap (width, height, min, max) {
const heightMap = [], // 2d array containing the heights of the tiles
octaves = 4, // 4 octaves
startFrequencyX = 2,
startFrequencyY = 2;
// linear interpolation function, could also be cubic, trigonometric, ...
const interpolate = (a, b, t) => (b - a) * t + a;
let currentFrequencyX = startFrequencyX, // specifies how many points should be generated in this octave
currentFrequencyY = startFrequencyY,
currentAlpha = 1, // the amplitude
octave = 0,
x = 0,
y = 0;
// fill the height map with zeros
for (x = 0 ; x < width; x += 1) {
heightMap[x] = [];
for (y = 0; y < height; y += 1) {
heightMap[x][y] = 0;
}
}
// main loop
for (octave = 0; octave < octaves; octave += 1) {
if (octave > 0) {
currentFrequencyX *= 2; // double the amount of point
currentFrequencyY *= 2;
currentAlpha /= 2; // take the half of the amplitude
}
// create random points
const discretePoints = [];
for (x = 0; x < currentFrequencyX + 1; x += 1) {
discretePoints[x] = [];
for (y = 0; y < currentFrequencyY + 1; y += 1) {
// create a new random value between 0 and amplitude
discretePoints[x][y] = Math.random() * currentAlpha;
}
}
// now interpolate and add to the height map
for (x = 0; x < width; x += 1) {
for (y = 0; y < height; y += 1) {
const currentX = x / width * currentFrequencyX,
currentY = y / height * currentFrequencyY,
indexX = Math.floor(currentX),
indexY = Math.floor(currentY),
// interpolate between the 4 neighboring discrete points (2d interpolation)
w0 = interpolate(discretePoints[indexX][indexY], discretePoints[indexX + 1][indexY], currentX - indexX),
w1 = interpolate(discretePoints[indexX][indexY + 1], discretePoints[indexX + 1][indexY + 1], currentX - indexX);
// add the value to the height map
heightMap[x][y] += interpolate(w0, w1, currentY - indexY);
}
}
}
// normalize the height map
let currentMin = 2; // the highest possible value at the moment
for (x = 0; x < width; x += 1) {
for (y = 0; y < height; y += 1) {
if (heightMap[x][y] < currentMin) {
currentMin = heightMap[x][y];
}
}
}
// currentMin now contains the smallest value in the height map
for (x = 0; x < width; x += 1) {
for (y = 0; y < height; y += 1) {
heightMap[x][y] -= currentMin;
}
}
// now, the minimum value is guaranteed to be 0
let currentMax = 0;
for (x = 0; x < width; x += 1) {
for (y = 0; y < height; y += 1) {
if (heightMap[x][y] > currentMax) {
currentMax = heightMap[x][y];
}
}
}
// currentMax now contains the highest value in the height map
for (x = 0; x < width; x += 1) {
for (y = 0; y < height; y += 1) {
heightMap[x][y] /= currentMax;
}
}
// the values are now in a range from 0 to 1, modify them so that they are between min and max
for (x = 0; x < width; x += 1) {
for (y = 0; y < height; y += 1) {
heightMap[x][y] = heightMap[x][y] * (max - min) + min;
}
}
return heightMap;
}
const map = generateHeightMap(40, 40, 0, 2); // map size 40x40, min=0, max=2
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
for (let x = 0; x < 40; x += 1) {
for (let y = 0; y < 40; y += 1) {
const height = map[x][y];
ctx.fillStyle = 'rgb(' + height * 127 + ', 127, 127)';
// draw the tile (tile size 5x5)
ctx.fillRect(x * 5, y * 5, 5, 5);
}
}
<canvas width="200" height="200"></canvas>
Note that the values in this height map can reach from -2 to 2. To change that, change the method that is used to create the random values.
Edit:
I made a mistake there, the version before the edit reached from -1 to 1. I modified it so that you can easily specify the minimum and maximum value.
First, I normalize the height map so that the values really reach from 0 to 1. Then, I modify all values so that they are between the specified min and max value.
Also, I changed how the heights are displayed. Instead of land and water, it now displays a smooth noise. The more red a point contains, the higher it is.
By the way, this algorithm is widely used in Procedural Content Generation for games.
If you want further explanation, just ask!

Javascript error while dropping balls

I wrote a javascript code to drop in ball multiple times when clicked on canvas. It is an experiment.
Here is the code:
HTML
<br style="clear: both" />
<canvas id="myCanvas1" width="134px" height="331px" onclick="draw(0)"></canvas>
<canvas id="myCanvas2" width="134px" height="331px" onclick="draw(1)"></canvas>
<canvas id="myCanvas3" width="134px" height="331px" onclick="draw(2)"></canvas>
JAVASCRIPT
var balls = [[], [], []],
canvases = document.getElementsByTagName('canvas'),
context = [],
interval,
boxWidth = 150,
ballRadius = 10,
canvasHeight = 235;
for (var i = 0; i < canvases.length; i++) {
context.push(canvases[i].getContext('2d'));
}
function draw() {
var movement = false;
for (var i = 0; i < 3; i++) {
context[i].clearRect(0, 0, boxWidth, canvasHeight);
for (var j = 0; j < balls[i].length; j++) {
if (balls[i][j].y < balls[i][j].yStop) {
balls[i][j].y += 4;
movement = true;
}
context[i].beginPath();
context[i].fillStyle = "red";
context[i].arc(balls[i][j].x, balls[i][j].y, ballRadius, 0, Math.PI * 2, true);
context[i].closePath();
context[i].fill();
}
}
if (!movement) {
clearInterval(interval);
interval = null;
}
}
function newBall(n) {
console.log('new ball', n);
var last = balls[n][balls[n].length - 1],
ball = {x: ballRadius, y: ballRadius, yStop: canvasHeight - ballRadius};
if (last) {
if (last.x < boxWidth - ballRadius * 3) {
ball.x = last.x + ballRadius * 2;
ball.yStop = last.yStop;
} else {
ball.yStop = last.yStop - ballRadius * 2;
}
}
balls[n].push(ball);
if (!interval) {
interval = setInterval(draw, 10);
}
}
But balls aren't dropping in. Please tell me that where am I wrong so that I can fix it...
balls is [] when the loop starts. So balls[0] is undefined, and thus has no property length.
Your code is always looping from 0 to 3. However, at first, there is no ball around. When you try to reach balls[0], balls[1] and balls[2], you get undefined error.
What you have to do is to change the loop to:
for (var i = 0; i < balls.length; i++)
or if you do not want to change the loop, you can initialize 3 balls at the start:
balls = [ball1, ball2, ball3];
where ball1, ball2 and ball3 are defined as how your ball data type is.
EDIT:
As I understand, you have some number of contexts, and for each context, you want to have a list of balls so that you can draw them.
Then:
balls = []
for (var i = 0; i < canvases.length; i++) {
context.push(canvases[i].getContext('2d'));
balls.push([]);
}
and use the remaining code same.

Making functions with Crafty.js

I am working on a top down video game with the crafty.js game library and I keep having to repeat a piece of code to make borders and the background sprite, So i want to put it into its own seperate function and call it, the problem is whenever I do this with traditional javascript syntax it causes an error, and i cant work out how else to do it: heres my scenes code:
Crafty.scene('World', function() {
//Draw Floor
for (var i = 0; i < 32; i++)
{
for (var y = 0; y < 24; y++)
{
Crafty.e('GrateFloor').at(i, y);
}
}
//Draw borders, gotta find a more code efficient way
for (var i = 0; i < 32; i++)
{
Crafty.e('Border').at(i, 0);
}
for (var y = 0; y < 24; y++)
{
Crafty.e('Border').at(0, y);
}
for (var y = 0; y < 24; y++)
{
Crafty.e('Border').at(31, y);
}
for (var y = 0; y < 32; y++)
{
Crafty.e('Border').at(y, 23);
}
//draw in game entities such as the player and obstacles
//drawing walls here
//horizontal walls
for (var y = 10; y <29; y++)
{
Crafty.e('WallHor').at(y, 20);
}
for (var y = 10; y <29; y++)
{
Crafty.e('WallHor').at(y, 5);
}
//vertical walls
for (var i = 6; i <20; i++)
{
Crafty.e('WallVert').at(29, i);
}
for (var i = 6; i <12; i++)
{
Crafty.e('WallVert').at(9, i);
}
for (var i = 14; i <20; i++)
{
Crafty.e('WallVert').at(9, i);
}
//single wall points
Crafty.e('WallTpRht').at(29,5);
Crafty.e('WallBtmRht').at(29,20);
Crafty.e('WallTpLft').at(9,5);
Crafty.e('WallBtmLft').at(9,20);
//everything else
Crafty.e('Enemy').at(20, 10);
Crafty.e('Teleporter1').at(1, 11);
Crafty.e('Player').at(15,15);
});
Crafty.scene('Loading', function() {
//Load in Visual Assets
Crafty.e('2D, DOM, Text')
.attr({ x: 15, y: 15 })
.text('Loading...');
Crafty.load(['assets/White_Male_Student_Animation_Bitmap.gif', 'assets/Walls_Bitmap.gif'], function(){
//Define terrain
Crafty.sprite(24, 24, 'assets/Walls_Bitmap.gif' , {
spr_WallWireHor: [0,0],
spr_Border: [0,1],
spr_WallWireVert: [1,1],
spr_WallWireTopRight: [1,0],
spr_WallWireBottomRight: [1,2],
spr_RobotSkull: [0,2],
spr_WallWireTopLeft: [2,0],
spr_WallWireBottomLeft: [2,1],
spr_Teleporter: [3,0],
spr_GrateFloor: [3,1],
})
//Define player
Crafty.sprite(25, 36.75, 'assets/White_Male_Student_Animation_Bitmap.gif' , {
spr_player: [0,0],
spr_BattlePlayer: [0,1],
},0, 0)
Crafty.scene('World')
})
});
//Screen for all combat to happen upon
Crafty.scene('BattleScreen', function() {
Crafty.e('2D, DOM, Text')
.attr({ x: 24, y: 22 })
.text('Monster destroyed!');
//Draw borders, gotta find a more code efficient way
for (var i = 0; i < 32; i++)
{
Crafty.e('Border').at(i, 0);
}
for (var y = 0; y < 24; y++)
{
Crafty.e('Border').at(0, y);
}
for (var y = 0; y < 24; y++)
{
Crafty.e('Border').at(31, y);
}
for (var y = 0; y < 32; y++)
{
Crafty.e('Border').at(y, 23);
}
//draws Player sprite for the combat screen
Crafty.e('BattlePlayer').at(16,20);
});
Crafty.scene('HubWorld', function() {
//Draw Floor
for (var i = 0; i < 32; i++)
{
for (var y = 0; y < 24; y++)
{
Crafty.e('GrateFloor').at(i, y);
}
}
//Draw borders, gotta find a more code efficient way
for (var i = 0; i < 32; i++)
{
Crafty.e('Border').at(i, 0);
}
for (var y = 0; y < 24; y++)
{
Crafty.e('Border').at(0, y);
}
for (var y = 0; y < 24; y++)
{
Crafty.e('Border').at(31, y);
}
for (var y = 0; y < 32; y++)
{
Crafty.e('Border').at(y, 23);
}
//draw other stuff
Crafty.e('Player').at(28,11);
Crafty.e('Teleporter2').at(30,11);
});
I want to move the Draw floor and Draw boders bits into there own subroutine, and I also need to know how to pass variables to and from functions with crafty.js
Crafty is a framework that uses the component design pattern. (http://gameprogrammingpatterns.com/component.html)
A component is exactly what you are asking for, a reusable piece of code.
So you should create a component which draws the floor and another for the border.
But first you should think again about the way you are drawing. Entities should not be used like that, except if you explicitely need that many entities. An entity is basically an ID with a list of components. The components should do the hard work, not the entities.
Take a look at the TextShadow component below, maybe it helps you to understand the idea:
var TextShadow = {
init: function init () {
this.requires('DOM');
this._textShadowColor = '#FFFFFF';
this._apply();
},
_apply: function _apply () {
this.css('text-shadow', '1px 1px 2px ' + this._textShadowColor);
},
textShadowColor: function textShadowColor (color) {
this._textShadowColor = color;
this._apply();
return this;
}
};
Crafty.c('TextShadow', TextShadow);

Categories