xxxxxxxxxx
167
//GLOBAL VARIABLES
var myGrid;
var numLines;
var w;
var snake;
var apple;
var gameState;
function setup(){
createCanvas(400, 400);
gameState = 0;
numLines = 30;
myGrid = new Grid();
w = width/numLines;
snake = new Snake();
apple = new Apple();
frameRate(10);
textSize(20);
noStroke();
}
function draw(){
if(gameState == 0){
background(100, 60,200);
//myGrid.show();
snake.show();
snake.move();
if(snake.checkTail()){
gameState = 1;
}
apple.show();
eatApples();
} else {
fill(0);
text("You lost" , 200, 300);
fill(255);
text("You lost" , 202, 302);
}
text("Score: " + snake.x.length, width-100, 30)
}
function eatApples(){
if(snake.x[0] == apple.x && snake.y[0] == apple.y){
apple = new Apple();
snake.x.push(apple.x);
snake.y.push(apple.y);
snake.bulge = 0;
}
}
function keyPressed(){
if(keyCode == UP_ARROW && snake.dir != "DOWN"){
snake.dir = "UP";
} else if(keyCode == DOWN_ARROW && snake.dir != "UP"){
snake.dir = "DOWN";
} else if(keyCode == LEFT_ARROW && snake.dir != "RIGHT"){
snake.dir = "LEFT";
} else if(keyCode == RIGHT_ARROW && snake.dir != "LEFT"){
snake.dir = "RIGHT";
}
}
class Snake{
constructor(){
this.x = [];
this.y = [];
this.d = w;
this.r = 30;
this.g = 0;
this.b = 0;
this.bulge = 1;
this.x.push(5);
this.y.push(1);
this.dir = ""; //EMPTY STRING
}
show(){
this.bulge+=2;
stroke(205,0,0);
for(var i = 0; i < this.x.length; i++){
this.d = map(i, 0, this.x.length , w, 2*w/3);
this.r = map(i, 0, this.x.length ,0, 255);
fill(this.r, this.g, this.b);
if(i == this.bulge){
ellipse(this.x[i]*w+w/2, this.y[i]*w+w/2, 2*this.d, 2*this.d);
} else {
rect(this.x[i]*w+(w/2-this.d/2), this.y[i]*w+(w/2-this.d/2), this.d, this.d, w/6);
}
}
}
checkTail(){
for(var i = 1; i < this.x.length; i++){
if(this.x[i] == this.x[0] && this.y[i] == this.y[0]){
return true;
}
}
return false;
}
move(){
//START AT THE TAIL, MAKE THE X & Y FOLLOW THE PIECE BEFORE IT
//AKA -- this.x[this.x.length - 1] = this.x[this.x.length-2]; etc....
for(var i = this.x.length - 1; i > 0; i--){
this.x[i] = this.x[i-1];
this.y[i] = this.y[i-1];
}
//MOVE HEAD
switch(this.dir){
case "UP":
if(this.y[0]>0){
this.y[0]--;
}
break;
case "DOWN":
if(this.y[0]<numLines - 1){
this.y[0]++;
}
break;
case "LEFT":
if(this.x[0] > 0){
this.x[0]--;
}
break;
case "RIGHT":
if(this.x[0]<numLines - 1){
this.x[0]++;
}
break;
}
}
}
class Apple{
//this is for the 'apple = new Apple();' line
constructor(){
this.x = int(random(numLines));
this.y = int(random(numLines));
}
show(){
noStroke();
fill(0,255,0); //GREEN APPLE
rect(this.x*w, this.y*w, w, w, w);
stroke(150,70,0);
line(this.x*w+(w/2), this.y*w+w/10, this.x*w+(3*w/5), this.y*w-w/4);
}
}
class Grid{
constructor(){
this.w = width/numLines;
}
show(){
stroke(0);
for(var i = 0; i < numLines; i++){
line(i*this.w, 0, i*this.w, height); //VERTICAL LINES
line(0, i*this.w, width, i*this.w); //HORIZTONAL LINES
}
}
}