I created the game “Snake” using three classes: the board class, the snake class, and the food class. The movement of the snake is controlled by the w, s, a, and d keys.
The win/game over functions were integrated directly into the draw function.
The following is a quick video demonstration of the game in action:
This is my code:
ArrayList<Integer> positionsX = new ArrayList<Integer>();
ArrayList<Integer> positionsY = new ArrayList<Integer>();
int dimSquare = 40;
int dim = 800;
int positionX = 5;
int positionY = 5;
int foodX = 15;
int foodY = 15;
int [] dirX = {1,-1,0,0};
int [] dirY = {0,0,1,-1};
int direction = 0;
int speedOfGame = 10;
boolean gameover = false;
class gameBoard{
gameBoard(){}
void drawLines(){
noFill();
stroke(0);
strokeWeight(1);
for(int i = 0; i < dim; i++){
line(dimSquare*i, 0, dimSquare*i, dim);
line(0, dimSquare*i, dim, dimSquare*i);
}
}
}
class snake{
snake(){
positionX = positionX*dimSquare;
positionY = positionY*dimSquare;
}
void drawSnake(){
fill(0,255,0);
noStroke();
for(int i = 0; i < positionsX.size() ; i++){
rect(positionsX.get(i)*dimSquare, positionsY.get(i)*dimSquare, dimSquare, dimSquare);
}
if(frameCount % speedOfGame == 0){
positionsX.add(0, positionsX.get(0) + dirX[direction]);
positionsY.add(0, positionsY.get(0) + dirY[direction]);
//positionsX.add(0, dirX[direction]);
//positionsY.add(0, dirY[direction]);
positionsX.remove(positionsX.size() – 1);
positionsY.remove(positionsY.size() – 1);
}
}
void growSnake(){
positionsX.add(1, positionsX.get(0) + dirX[direction]);
positionsY.add(1, positionsY.get(0) + dirY[direction]);
}
}
class food{
food(){
}
void drawFood(){
fill(255, 0, 0);
rect(foodX*dimSquare, foodY*dimSquare, dimSquare, dimSquare);
}
}
gameBoard a;
snake b;
food c;
void setup(){
size(802, 802);
a = new gameBoard();
b = new snake();
c = new food();
positionsX.add(5);
positionsY.add(5);
}
void draw(){
if(gameover == false){
background(255);
//a.drawLines();
b.drawSnake();
c.drawFood();
if(positionsX.get(0) == foodX && positionsY.get(0) == foodY){
foodX = (int)random(0,20);
foodY = (int)random(0,20);
b.growSnake();
}
if(positionsX.get(0) < 0 || positionsY.get(0) < 0 || positionsX.get(0) >= 20 || positionsY.get(0) >= 20){
gameover = true;
fill(0);
textSize(30);
textAlign(CENTER);
text(“GAME OVER.”,width/2,height/2);
}
if(positionsX.size() == 20){
gameover = true;
fill(0);
textSize(30);
textAlign(CENTER);
text(“YOU WINNNNN.”,width/2,height/2);
}
}
}
void keyPressed(){
int keyInput = 0;
if(key == ‘d’){
keyInput = 0;
}
if(key == ‘a’){
keyInput = 1;
}
if(key == ‘s’){
keyInput = 2;
}
if(key == ‘w’){
keyInput = 3;
}
if(keyInput != -1){
direction = keyInput;
}
}