# Random walker on certain part of the canvas

Hi!

I’m playing around with a Random Walker code. How can I make the Walker to be displayed only at the bottom half of the screen with the following code? And also not disapearing from the canvas ?

``````let grid;
let cols, rows;
let x;
let y;
let spacing = 10;

function make2DArray (cols, rows) {
let arr = new Array(cols);
for (let i =0; i<arr.length; i++){
arr[i] = new Array (rows);

}
return arr;
}

function setup() {
createCanvas(400, 400);
cols = floor(width/spacing);
rows = floor (height/spacing);
x = cols/2;
y = rows/2;
background (0);
grid = make2DArray(cols,rows);
}

function draw() {
stroke (255,100);
strokeWeight (spacing * 0.5);
point(x * spacing, y*spacing);
const r = floor (random(4));
switch (r){
case 0: x = x+1;
break;
case 1 : x = x -1;
break;
case 2 : y = y+1;
break;
case 3 : y = y-1;
break;

}

}
``````

What about an if-clause ? Before you change x or y, check if the new position would be allowed (stays inside the lower half of the screen).

1 Like

You’re right. But I don’t get why I can’t “translate” it only to the bottom of the canvas. Is it because it’s a 2D array?

put ` /4` here

Thank you for your reply but unfortunately that does not work. I think I had tried that before. I also tried `rows = floor ((height/2)/spacing);`. That doesn’t work either.

I meant ` y = (rows/4.0)*3.0;`

Full Sketch

``````let grid;
let cols, rows;
let x;
let y;
let spacing = 10;

function make2DArray (cols, rows) {
let arr = new Array(cols);
for (let i =0; i<arr.length; i++){
arr[i] = new Array (rows);

}
return arr;
}

function setup() {
createCanvas(400, 400);
cols = floor(width/spacing);
rows = floor (height/spacing);
x = cols/2;
y = (rows/4.0)*3.0;
background (0);
grid = make2DArray(cols,rows);
}

function draw() {
stroke (255,100);
strokeWeight (spacing * 0.5);
point(x * spacing, y*spacing);
const r = floor (random(4));
switch (r){
case 0: x = x+1;
break;
case 1 : x = x -1;
break;
case 2 : if((y+1)*spacing<width) y = y+1;
break;
case 3 : if((y-1)*spacing>width/2.0) y = y-1;
break;

}

}

``````
1 Like

Thanks for your help and your time, but I still get the same result. The “walker” goes around the full canvas This y is only the starting point for y.

You need to implement the if-clauses we mentioned.

Did you run my code?

I made 2 (of 4) if-clauses.

Oh no I didn’t, I’m sorry! You’re right it works! Thank you very much!

1 Like 