6th Inter Lab Documentation

The in-recitation exercise:

A rough frame for Snake games:

float bodyX[] = new float[900];
float bodyY[] = new float[900];
int n = 90;
int tX = int(random(30));
int tY = int(random(30));
boolean ch = true;

void setup(){

size(600,600);
/* for(int x = 20; x < 600 ; x+=20){
line(x,0,x,600);
line(0,x,600,x);
} */
for(int i = 0; i < n ; i++){
bodyX[i] = i;
bodyY[i] = 0;
}
ch = true;
while (ch) {
ch = false;
for(int i = 0; i < n ; i++){
if (bodyX[i] == tX && bodyY[i] == tY){
ch = true;
break;
}
}
tX = int(random(30));
tY = int(random(30));
}
}


void draw(){

background(255);
noStroke();
fill(255,0,0);
rect(tX*20,tY*20,20,20,9);

if (key == CODED){
if (keyCode == UP){
bodyX[n] = bodyX[n-1];
bodyY[n] = bodyY[n-1]-1;
}
else if (keyCode == DOWN){
bodyX[n] = bodyX[n-1];
bodyY[n] = bodyY[n-1]+1;
}
else if (keyCode == LEFT){
bodyX[n] = bodyX[n-1]-1;
bodyY[n] = bodyY[n-1];
}
else if (keyCode == RIGHT){
bodyX[n] = bodyX[n-1]+1;
bodyY[n] = bodyY[n-1];
}
}

fill(0);
for(int i = 0; i < n ; i++){
rect(bodyX[i]*20,bodyY[i]*20,20,20,9);
bodyX[i] = bodyX[i+1];
bodyY[i] = bodyY[i+1];
}

}

And it works like this:

https://drive.google.com/open?id=1m3duuuMUULfbwqRqAzpWoxTD67Bs1rKk

The homework

float speed = 8;
float r = 50;
float x = 300;
float y = 300;
float js = 5;
float i = 0;
float j = 40;

void setup(){
size(600,600);
colorMode(HSB, 100);
}

void draw(){
background(0,0,100);
strokeWeight(20);
ellipse(x,y,r,r);
if ( r < 40 || r >= 400) {
speed = -speed;
}
r += speed;
stroke(i, j, 80);
j += js;
if ((j == 100)||(j< 40)) {
js = -js;
j += js;
i += 5;
}
if (keyPressed){
if (keyCode == UP){
y -= 5;
}
else if (keyCode == DOWN){
y += 5;
}
else if (keyCode == LEFT){
x -= 5;
}
else if (keyCode == RIGHT){
x += 5;
}
}
}

And it works like this:

https://drive.google.com/open?id=1uisZ76edhzquj-BM_xKI6QMYSqII03oA

During the coding, I found how to draw a dynamic multi-element image and make it move. Like I do in the in-class exercise, I made a snake and using the keyboard to make it move.  One trivial detail that particularly surprises me is that we need to use (key == CODED) to determine whether something WAS PRESSED and (keyPressed) to determine whether something IS PRESSED. There is a huge difference between that. Something like a snake, which keeps moving should use the former one to get the moving signal; while something like a circle, which only moves when instructions are given, needs the application of the latter one. That’s something very interesting about these functions that I found.

Leave a Reply