You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.3 KiB
99 lines
2.3 KiB
const START_SEGMENTS = 10;
|
|
const SEG_LEN = 10;
|
|
const SPEED = 4;
|
|
const WIDTH = 300;
|
|
const HEIGHT = 300;
|
|
const APPLE_SIZE = 20;
|
|
const APPLE_R = APPLE_SIZE/2;
|
|
const SPACE_BAR = 32;
|
|
let head;
|
|
let tail;
|
|
let apple;
|
|
let turn = 0;
|
|
let speedup = 0;
|
|
|
|
const isOutside = (aVec) => (
|
|
aVec.x > WIDTH ||
|
|
aVec.x < 0 ||
|
|
aVec.y > HEIGHT ||
|
|
aVec.y < 0);
|
|
|
|
|
|
function setup() {
|
|
// put setup code here
|
|
apple = new Vector(random(APPLE_R,WIDTH-APPLE_R),
|
|
random(APPLE_R,HEIGHT-APPLE_R));
|
|
tail = new Segment(WIDTH/2, 0, 10, HALF_PI);
|
|
head = tail
|
|
for(let i = 0; i < START_SEGMENTS; i++){
|
|
let pos = head.end();
|
|
head.child = new Segment(pos.x, pos.y, 10, HALF_PI);
|
|
head.child.parent = head;
|
|
head = head.child;
|
|
}
|
|
createCanvas(300,300);
|
|
frameRate(15);
|
|
}
|
|
|
|
function draw() {
|
|
// put drawing code here
|
|
background(0);
|
|
for(let current = tail; current !== null; current= current.child){
|
|
current.draw();
|
|
}
|
|
fill(0, 255, 0);
|
|
noStroke();
|
|
circle(apple.x, apple.y, APPLE_SIZE);
|
|
// update
|
|
head.heading += turn * PI/18;
|
|
head.start.add(p5.Vector.fromAngle(head.heading, SPEED*(1+speedup)));
|
|
head.update();
|
|
head_end = head.end();
|
|
if(Vector.sub(head_end, apple).mag() < APPLE_SIZE){
|
|
apple = new Vector(random(APPLE_R,WIDTH-APPLE_R),
|
|
random(APPLE_R,HEIGHT-APPLE_R));
|
|
for(let i=1; i<=3; i++){
|
|
let end = tail.end();
|
|
let heading = tail.heading;
|
|
tail = tail.expand_parent(end.x, end.y, SEG_LEN, heading+ PI);
|
|
}
|
|
}
|
|
// Game over
|
|
if(isOutside(head_end) || head.eats_parents())
|
|
{
|
|
background(128);
|
|
textSize(HEIGHT/10);
|
|
textAlign(CENTER);
|
|
text("Game Over! Refresh page to restart.",
|
|
0.1*WIDTH, 0.1*HEIGHT,
|
|
0.8*WIDTH, 0.8*HEIGHT)
|
|
noLoop();
|
|
};
|
|
}
|
|
|
|
function keyPressed(){
|
|
switch(keyCode){
|
|
case LEFT_ARROW:
|
|
turn = -1;
|
|
break;
|
|
case RIGHT_ARROW:
|
|
turn = +1;
|
|
break;
|
|
case SPACE_BAR:
|
|
speedup = 1;
|
|
break;
|
|
}
|
|
}
|
|
|
|
function keyReleased(){
|
|
switch(keyCode){
|
|
case LEFT_ARROW:
|
|
case RIGHT_ARROW:
|
|
turn = 0;
|
|
break;
|
|
case SPACE_BAR:
|
|
speedup = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
|