Commit ac354c5b authored by jack.webb's avatar jack.webb

Add new file

parents
Pipeline #580 canceled with stages
//Arrays for when the snake eats another block is added
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
//Size of the grid and snake
int w=30, h=30, blockSize=20;
//Starting direction of the snake (Right)
int direction = 2;
//Starting position of the apple, before randomise.
int applex=1, appley=10;
//Direction X and Y of the snake
int[]dirx={0, 0, 1, -1};
int[]diry={1, -1, 0, 0};
//sets the game state, which allows the game to restart
boolean gameover=false;
void setup() {
//Size of Window
size(600, 600);
//Starting Position
x.add(5);
y.add(5);
}
void draw() {
//Background Colour
background(192, 192, 192);
//Draws the grids
for (int i=0; i<w; i++) line(i*blockSize, 0, i*blockSize, height);
for(int i=0; i<h; i++) line(0, i*blockSize, width, i*blockSize);
//Draws the snake
fill(34, 139, 34);
for (int i = 0 ; i < x.size(); i++)
rect(x.get(i)*blockSize, y.get(i)*blockSize, blockSize, blockSize);
//Draws the apple
if (!gameover) {
fill(255, 0, 0);
rect(applex*blockSize, appley*blockSize, blockSize, blockSize);
//FrameRate
if (frameCount%7==0) {
x.add(0, x.get(0) + dirx[direction]);
y.add(0, y.get(0) + diry[direction]);
//Boundries, so game ends if touch sides
if(x.get(0) < 0 || y.get(0) < 0 || x.get(0) >= w || y.get(0) >= h) gameover = true;
//If snake eats apple, add length and randomise apple position
if (x.get(0)==applex && y.get(0)==appley) {
applex = (int)random(0, w);
appley = (int)random(0, h); }
else { x.remove(x.size()-1); y.remove(y.size()-1); }
}
}
//Game end screen, that allows for restarts
else {
fill(0);
textSize(30);
textAlign(CENTER);
text("GAME OVER. Press space to Restart",width/2,height/2);
if(keyPressed&&key==' ') {
x.clear();
y.clear();
x.add(5);
y.add(5);
gameover = false; }
}
}
//Direction
void keyPressed() {
int newdir = key=='s'? 0:(key=='w'?1:(key=='d'?2:(key=='a'?3:-1)));
if (newdir != -1) direction = newdir;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment