0% found this document useful (0 votes)
11 views

Java Mini Project

MpReport

Uploaded by

jeelearning2005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Mini Project

MpReport

Uploaded by

jeelearning2005
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Introduction

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

project, we create a Snake Game using Java, providing a practical application of

programming concepts learned in the course. The game involves maneuvering a

snake around a grid, where the goal is to consume food items, grow in length,

and avoid collisions.

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

various aspects of programming, including user input handling, game state

management, and graphical representation.


Objective
The primary objective of this project is to enhance students' programming skills in
Java by:

Implementing Game Mechanics: we learn to design and implement game logic,


such as movement, scoring, and collision detection.

Managing User Input: Handling keyboard input to control the snake allows
students to practice event-driven programming concepts.

Developing a Graphical User Interface: By creating a visual representation of the


game, we gain experience in using Java's Swing library for GUI development.

Relevance to the Course:

This project is highly relevant to the course objectives, as it reinforces several key
learning outcomes:

Object-Oriented Programming: The project utilizes classes and objects to


represent game elements, demonstrating principles of encapsulation and modular
design.

Event-Driven Programming: Handling user input through key events illustrates


the event-driven paradigm, which is fundamental in GUI applications.

Algorithm Development: Designing algorithms for game mechanics, such as


movement and collision detection, enhances problem-solving skills and
logical reasoning.
Implementation
Coding
SnakeGame.java
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;

public class SnakeGame extends JPanel implements ActionListener, KeyListener {


private class Tile {
int x;
int y;

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;

SnakeGame(int boardWidth, int boardHeight) {


this.boardWidth = boardWidth;
this.boardHeight = boardHeight;
setPreferredSize(new Dimension(this.boardWidth, this.boardHeight));
setBackground(Color.black);
addKeyListener(this);
setFocusable(true);

snakeHead = new Tile(5, 5);


snakeBody = new ArrayList<Tile>();

food = new Tile(10, 10);


random = new Random();
placeFood();

velocityX = 1;
velocityY = 0;

//game timer
gameLoop = new Timer(100, this); //how long it takes to start timer, milliseconds
gone between frames
gameLoop.start();
}

public void paintComponent(Graphics g) {


super.paintComponent(g);
draw(g);
}

public void draw(Graphics g) {


//Grid Lines
for(int i = 0; i < boardWidth/tileSize; i++) {
//(x1, y1, x2, y2)
g.drawLine(i*tileSize, 0, i*tileSize, boardHeight);
g.drawLine(0, i*tileSize, boardWidth, i*tileSize);
}
//Food
g.setColor(Color.red);
// g.fillRect(food.x*tileSize, food.y*tileSize, tileSize, tileSize);
g.fill3DRect(food.x*tileSize, food.y*tileSize, tileSize, tileSize, true);

//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);
}
}

public void placeFood(){


food.x = random.nextInt(boardWidth/tileSize);
food.y = random.nextInt(boardHeight/tileSize);
}

public void move() {


//eat food
if (collision(snakeHead, food)) {
snakeBody.add(new Tile(food.x, food.y));
placeFood();
}

//move snake body


for (int i = snakeBody.size()-1; i >= 0; i--) {
Tile snakePart = snakeBody.get(i);
if (i == 0) { //right before the head
snakePart.x = snakeHead.x;
snakePart.y = snakeHead.y;
}
else {
Tile prevSnakePart = snakeBody.get(i-1);
snakePart.x = prevSnakePart.x;
snakePart.y = prevSnakePart.y;
}
}
//move snake head
snakeHead.x += velocityX;
snakeHead.y += velocityY;

//game over conditions


for (int i = 0; i < snakeBody.size(); i++) {
Tile snakePart = snakeBody.get(i);

//collide with snake head


if (collision(snakeHead, snakePart)) {
gameOver = true;
}
}

if (snakeHead.x*tileSize < 0 || snakeHead.x*tileSize > boardWidth || //passed left border or


right border
snakeHead.y*tileSize < 0 || snakeHead.y*tileSize > boardHeight ) { //passed top border
or bottom border
gameOver = true;
}
}

public boolean collision(Tile tile1, Tile tile2) {


return tile1.x == tile2.x && tile1.y == tile2.y;
}

@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.*;

public class App {


public static void main(String[] args) throws Exception {
int boardWidth = 600;
int boardHeight = boardWidth;

JFrame frame = new JFrame("Snake");


frame.setVisible(true);
frame.setSize(boardWidth, boardHeight);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

SnakeGame snakeGame = new SnakeGame(boardWidth, boardHeight);


frame.add(snakeGame);
frame.pack();
snakeGame.requestFocus();
}
}
Screenshots
Game Interface
Conclusion
Summary: The Snake Game project successfully demonstrates
fundamental programming concepts and offers an engaging way to apply
Java development skills. Key takeaways include:
Understanding Game Development: Students gain practical experience
in designing and implementing game mechanics, which can be applied to
future projects.
Importance of Testing: The iterative process of testing and debugging is
crucial in software development, highlighting the importance of
maintaining code quality and functionality.
Challenges Faced: During the development of the Snake Game, several
challenges arose, including:
Collision Detection: Accurately detecting collisions between the snake
and food, as well as between the snake and walls or its own body, required
careful planning and implementation. Debugging this logic involved
tracing the flow of data and ensuring all conditions were checked.
Game Over Conditions: Implementing multiple game-over conditions,
such as colliding with walls or the snake's own body, necessitated
thorough testing. This challenge was addressed by systematically
verifying each condition and using print statements for debugging.
These challenges were overcome through:
Iterative Testing: Regular testing of individual components helped identify and fix
issues early in the development process.
Consulting Documentation: Reference materials, such as textbooks and online
resources, provided insights and solutions to specific programming problems
encountered during development.
Peer Collaboration: Discussing challenges with classmates and seeking feedback
fostered a collaborative learning environment.
References
"Java: A Beginner's Guide" by Herbert Schildt
Oracle's Java Documentation
Online tutorials on Java Swing and game development
Stack Overflow discussions related to game logic and event handling

You might also like