Java Mini Project
Java Mini Project
The Snake Game is a classic arcade game that has been popular since the late
1970s. It is recognized for its simple rules and engaging gameplay. In this
snake around a grid, where the goal is to consume food items, grow in length,
The Snake Game project aims to replicate the traditional gameplay where
players control a snake that moves on a grid, consuming food items to grow.
The game presents challenges, as players must navigate the snake without
colliding with the walls or the snake's own body. The project encompasses
Managing User Input: Handling keyboard input to control the snake allows
students to practice event-driven programming concepts.
This project is highly relevant to the course objectives, as it reinforces several key
learning outcomes:
Tile(int x, int y) {
this.x = x;
this.y = y;
}
}
int boardWidth;
int boardHeight;
int tileSize = 25;
//snake
Tile snakeHead;
ArrayList<Tile> snakeBody;
//food
Tile food;
Random random;
//game logic
int velocityX;
int velocityY;
Timer gameLoop;
boolean gameOver = false;
velocityX = 1;
velocityY = 0;
//game timer
gameLoop = new Timer(100, this); //how long it takes to start timer, milliseconds
gone between frames
gameLoop.start();
}
//Snake Head
g.setColor(Color.green);
// g.fillRect(snakeHead.x, snakeHead.y, tileSize, tileSize);
// g.fillRect(snakeHead.x*tileSize, snakeHead.y*tileSize, tileSize, tileSize);
g.fill3DRect(snakeHead.x*tileSize, snakeHead.y*tileSize, tileSize, tileSize, true);
//Snake Body
for (int i = 0; i < snakeBody.size(); i++) {
Tile snakePart = snakeBody.get(i);
// g.fillRect(snakePart.x*tileSize, snakePart.y*tileSize, tileSize, tileSize);
g.fill3DRect(snakePart.x*tileSize, snakePart.y*tileSize, tileSize, tileSize, true);
}
//Score
g.setFont(new Font("Arial", Font.PLAIN, 16));
if (gameOver) {
g.setColor(Color.red);
g.drawString("Game Over: " + String.valueOf(snakeBody.size()), tileSize - 16, tileSize);
}
else {
g.drawString("Score: " + String.valueOf(snakeBody.size()), tileSize - 16, tileSize);
}
}
@Override
public void actionPerformed(ActionEvent e) { //called every x milliseconds by gameLoop
timer
move();
repaint();
if (gameOver) {
gameLoop.stop();
}
}
@Override
public void keyPressed(KeyEvent e) {
// System.out.println("KeyEvent: " + e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_UP && velocityY != 1) {
velocityX = 0;
velocityY = -1;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN && velocityY != -1) {
velocityX = 0;
velocityY = 1;
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT && velocityX != 1) {
velocityX = -1;
velocityY = 0;
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT && velocityX != -1) {
velocityX = 1;
velocityY = 0;
}
}
//not needed
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
}
App.Java
import javax.swing.*;