Snake Game

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

ABSTRACT:

Snake game is a simple console application without


graphics. In this project, you can play the popular
“Snake Game” just like you played it elsewhere. You
must use the up, down, right or left arrows to move the
snake. Foods are provided at the several co-ordinates
of the screen for the snake to eat.
Every time the snake eats the food, its length will by
increased by one element along with the score. I have
used Python as Programming language for writing the
code for the project and VsCode for writing the
programs. Operating system used Windows 10.

INTRODUCTION:
playing games is fun and exciting it gives us relief from stress and
unwind from our stressful works. Many of us spend our vacant time
or others that use most of their time in playing and exploring new
games. Today, with the rapid development of technology we have,
games that are rising up together with it. Nowadays with the
technology we have many games that are developing for computer
most specifically for windows. With the high technology equipped
with these computers, computer games become robust and attract
many people to buy or have this gadget for them to experience
what's inside it which makes it a trend for the new generation of
gadget.
Snake game is a computer action game; whose goal is to control a
snake to move and collect food in a map. It has been around since
the earliest days of home computing and has re-emerged in recent
years on mobile phones.
It isn't the world's greatest game, but it does give you an idea of
what you can achieve with a simple python program, and perhaps
the basis by which to extend the principles and create
more interesting games on your own.
To move the snake, use 'up arrow' for up, 'down arrow'
for down, 'left arrow' for left and ‘right arrow' for right.
Press 'Q' to exit the game at any time, press 'C' to
continue the game.
The aim of the game is to collect the dots (food) and
avoid the obstacles (crosses borders). As you collect
the food, the snake gets longer. The score also
increases. There is no concept of lives. Once You hit an
obstacle, that's it, game over.

Objective:
The objective of the project was to develop a Snake
Game application using Java programming language.
This classic arcade game serves as a platform to
demonstrate various programming concepts while
providing an engaging and interactive user experience.
The primary goal was to create a functional and
enjoyable game that not only entertains users but also
serves as an educational tool for learning Java
programming principles such as object-oriented
programming, event handling, and game development
techniques. Through this project, participants aimed to
strengthen their understanding of Java and enhance
their programming skills by implementing core features
of the Snake Game.
Features:
1.Snake Movement and Control:
 The snake is represented as an Array List of
points (segments), where each point represents a
segment of the snake's body.
 The direction of the snake's movement is
controlled by the user input through arrow keys
(UP, DOWN, LEFT, RIGHT).
 The snake moves one step at a time in the
direction specified by the user input.

2.Food Generation and Consumption:


 Food pellets are randomly generated on the game
grid.
 When the snake's head collides with a food pellet,
it consumes the food, grows longer, and earns
points.
 Upon consuming food, a new food pellet is
generated at a random location on the grid.

3.Collision Detection:
 Collision detection ensures that the game
responds appropriately to collisions between the
snake and the boundaries of the game window or
between the snake's head and its body segments.
 If the snake collides with the walls or itself, the
game ends (game over).
4.Rendering and GUI:
 The game grid, snake, and food are rendered
using Java's Graphics class.
 The GUI is created using Java Swing components,
including JFrame and JPanel.
 The game window displays the grid, snake, and
food, updating them as the game progresses.
5.Game Loop:
 The game loop is implemented using a Timer
object, which repeatedly executes a set of actions
at a fixed interval (DELAY).
 Within the game loop, the snake's movement,
collision detection, and rendering are handled.

6. Score Tracking:
 Although not explicitly implemented in the
provided code, score tracking can be added by
incrementing a score variable each time the
snake consumes food.
 The score can be displayed on the game window
to keep track of the player's progress.

7.Game Over Screen:


 When the game ends due to collision with walls or
itself, a "Game Over" message is displayed on the
screen.
 This message indicates to the player that the
game has ended, and they can no longer control
the snake.

8.Main Method:
 The main method initializes the Snake Game
object and sets it visible, starting the game.
 It ensures that the game runs on the Event
Dispatch Thread (EDT) for proper Swing
concurrency.

These features collectively create a basic version of the


Snake Game, allowing players to control a snake, eat
food pellets, and avoid collisions until the game ends.
Further enhancements and modifications can be made
to improve the game's functionality and user
experience.

Technologies Used:
1.Java Programming Language:
 Java is a widely used, object-oriented
programming language known for its platform
independence and robustness.
 It provides the foundation for the game's logic
and functionality.

2.Java Swing:
 Java Swing is a set of GUI (Graphical User
Interface) components for Java applications.
 It allows developers to create rich, interactive
user interfaces for desktop applications.
 In this project, Swing is used to create the game
window, handle user input, and render graphical
elements such as the game grid, snake, and food.

3.Integrated Development Environment (IDE):


 IDEs such as Eclipse or IntelliJ IDEA provide an
integrated environment for Java development.
 They offer features like code editing, debugging,
and project management, which streamline the
development process.
 Developers can write, test, and debug code
efficiently using these tools.

These technologies collectively enable the


development of the Snake Game in Java, providing the
necessary tools and libraries to create a functional and
interactive gaming experience.

Implementation:
1.Game Logic:
 The game logic includes defining the behavior of
the snake, food generation, collision detection,
and score tracking.
 It determines how the game progresses based on
user input and game events.

2.User Interface:
 The user interface comprises the graphical
elements displayed to the player, such as the
game window, grid, snake, food, and score
display.
 It provides a visual representation of the game
state and allows the player to interact with the
game.

3.Event Handling:
 Event handling is used to capture user input (e.g.,
arrow key presses) and respond accordingly.
 It enables the player to control the movement of
the snake and interact with the game
environment.

4.Rendering:
 Rendering involves drawing the game elements
on the screen, including the game grid, snake,
food, and score display.
 It ensures that the game graphics are updated
appropriately as the game progresses.

5.Game Loop:
 The game loop controls the flow of the game,
repeatedly executing actions such as updating
the game state, checking for collisions, and
rendering the game elements.
 It ensures smooth gameplay and responsiveness
to user input.

Overall, the implementation of the Snake Game


involves combining these components to create a
cohesive gaming experience. The game logic drives the
behavior of the game, while the user interface, event
handling, rendering, and game loop work together to
provide an interactive and enjoyable gameplay
experience.

Code Structure:
1.Main Class (Snake Game):
 The ‘Snake Game’ class serves as the main class
that initializes and runs the game.
 It extends ‘JFrame’ to create the game window.
 The main method creates an instance of ‘Snake
Game’, making the game visible to the player.

2.Snake Class:
 Although not explicitly separated into its own
class in the provided code, the snake is
represented as an Array List of points (segments).
 Each point represents a segment of the snake's
body.
 The movement and behavior of the snake are
handled within the ‘Snake Game’ class.

3.Food Class:
 The food pellet is represented by a ‘Point’ object.
 The food's position is randomly generated on the
game grid.
 The consumption of food and generation of new
food pellets are managed within the ‘Snake Game’
class.

4. Game Panel Class:


 In the provided code, the rendering of the game
elements is handled directly within the ‘Snake
Game’ class.
 However, in more complex implementations, you
may create a separate ‘Game Panel’ class that
extends ‘JPanel’ to handle rendering.
 This class would be responsible for drawing the
game grid, snake, food, and other graphical
elements.

5. Game Frame Class:


 Again, not explicitly separated in the provided
code, but in more modular implementations, you
might have a ‘Game Frame’ class that extends
‘JFrame’ to create the game window.
 It could handle additional functionalities related to
the window, such as resizing behavior, layout
management, and event handling.

Overall, the code structure demonstrates a basic


implementation of the Snake Game within a single class
(‘Snake Game’), where all game logic, rendering, and
event handling are contained. For larger and more
complex projects, it's common to modularize the code
further by separating concerns into different classes to
improve maintainability and scalability.

Future Enhancements:
1.Levels with Increasing Difficulty:
 Introduce multiple levels with progressively
challenging obstacles, such as faster snake
movement speed, additional barriers, or more
complex mazes.
 Each level could have different objectives or
variations in gameplay to keep the game
engaging.

2.Sound Effects and Background Music:


 Enhance the gaming experience with sound
effects for actions such as eating food, collisions,
and game over.
 Add background music to create ambiance and
immerse players further into the game
environment.

3.Multiplayer Functionality:
 Implement multiplayer mode to allow multiple
players to compete or cooperate in the same
game instance.
 Players could compete for the highest score or
collaborate to achieve common goals.

4.Power-Ups and Obstacles:


 Introduce power-ups that provide temporary
advantages, such as increased speed, longer
snake length, or invincibility.
 Include obstacles that add complexity to the
gameplay, such as walls that appear and
disappear or moving obstacles that the snake
must avoid.

5.Customization Options:
 Provide players with customization options to
personalize their gaming experience, such as
choosing different snake skins, backgrounds, or
grid layouts.
 Allow players to adjust game settings, such as
difficulty level, speed, and game rules, to tailor
the gameplay to their preferences.

6.Achievements and Leaderboards:


 Implement achievement system to reward players
for accomplishing specific milestones or
completing challenges.
 Include leaderboards to track and compare
players' scores globally or among friends,
fostering competition and engagement.

7.Mobile Compatibility:
 Adapt the game for mobile platforms, optimizing
the user interface and controls for touch screens.
 Make the game available on app stores to reach a
broader audience and provide convenience for
players who prefer gaming on mobile devices.

These enhancements aim to add depth, variety, and


replay value to the Snake Game, making it more
enjoyable and engaging for players. By incorporating
new features and expanding the game's capabilities,
developers can keep the game fresh and attract a wider
audience.

Challenges Faced:
1.Smooth Snake Movement: Implementing smooth
and responsive movement of the snake without
causing flickering or lag in the game was
challenging. Ensuring that the snake moves at a
consistent speed and responds promptly to user
input required careful handling of game loop timing
and rendering.

2.Managing Snake Growth: Managing the growth of


the snake and ensuring that new segments are
added correctly without disrupting the game
mechanics posed a challenge. Coordinating the
addition of new segments to the snake's body
while maintaining its movement dynamics and
collision detection logic required careful design and
implementation.

3.Collision Detection Algorithms: Implementing


efficient collision detection algorithms to handle
collisions with walls and the snake's own body was
a significant challenge. Developing algorithms that
accurately detect collisions while minimizing
computational overhead and ensuring smooth
gameplay experience was crucial for the overall
success of the game.

4.Game State Management: Managing the game


state, including starting, pausing, and ending the
game, presented challenges. Coordinating various
game components and transitions between
different states while maintaining consistency and
avoiding conflicts required robust state
management techniques.
5.User Interface Design: Designing a user-friendly
and visually appealing interface for the game
presented challenges. Balancing aesthetics with
functionality, ensuring intuitive user interaction,
and optimizing the layout for different screen sizes
and resolutions required careful consideration and
testing.

Addressing these challenges required collaboration,


problem-solving skills, and iterative refinement of code
and design. Overcoming these obstacles contributed to
the successful development of the Snake Game project
and provided valuable learning experiences for the
development team.

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class SnakeGame extends JFrame {

public static final int WIDTH = 600;


public static final int HEIGHT = 600;
public static final int UNIT_SIZE = 20;
public static final int GAME_UNITS = (WIDTH *
HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
public static final int DELAY = 75;
public static final Color SNAKE_COLOR = new
Color(34, 139, 34); // Green color
public static final Color FOOD_COLOR = new
Color(178, 34, 34); // Red color

private ArrayList<Point> snakeBody;


private Point food;
private char direction;
private boolean running;
private Timer timer;
private Random random;

public SnakeGame() {
setTitle("Snake Game");
setSize(WIDTH, HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
setLocationRelativeTo(null);

snakeBody = new ArrayList<>();


random = new Random();
direction = 'R';
running = true;
snakeBody.add(new Point(WIDTH / 2, HEIGHT / 2));
food = new Point(random.nextInt(WIDTH /
UNIT_SIZE) * UNIT_SIZE, random.nextInt(HEIGHT /
UNIT_SIZE) * UNIT_SIZE);

addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (direction != 'R')
direction = 'L';
break;
case KeyEvent.VK_RIGHT:
if (direction != 'L')
direction = 'R';
break;
case KeyEvent.VK_UP:
if (direction != 'D')
direction = 'U';
break;
case KeyEvent.VK_DOWN:
if (direction != 'U')
direction = 'D';
break;
}
}
});

timer = new Timer(DELAY, new ActionListener() {


@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkFood();
checkCollisions();
repaint();
}
}
});

timer.start();
}

private void move() {


Point head = snakeBody.get(0);
Point newHead = new Point(head.x, head.y);

switch (direction) {
case 'L':
newHead.x -= UNIT_SIZE;
break;
case 'R':
newHead.x += UNIT_SIZE;
break;
case 'U':
newHead.y -= UNIT_SIZE;
break;
case 'D':
newHead.y += UNIT_SIZE;
break;
}

snakeBody.add(0, newHead);
if (!snakeBody.get(0).equals(food)) {
snakeBody.remove(snakeBody.size() - 1);
} else {
food.setLocation(random.nextInt(WIDTH /
UNIT_SIZE) * UNIT_SIZE, random.nextInt(HEIGHT /
UNIT_SIZE) * UNIT_SIZE);
}
}

private void checkFood() {


if (snakeBody.get(0).equals(food)) {
food.setLocation(random.nextInt(WIDTH /
UNIT_SIZE) * UNIT_SIZE, random.nextInt(HEIGHT /
UNIT_SIZE) * UNIT_SIZE);
}
}

private void checkCollisions() {


Point head = snakeBody.get(0);
if (head.x < 0 || head.x >= WIDTH || head.y < 0 ||
head.y >= HEIGHT) {
running = false;
}

for (int i = 1; i < snakeBody.size(); i++) {


if (head.equals(snakeBody.get(i))) {
running = false;
break;
}
}
}

@Override
public void paint(Graphics g) {
super.paint(g);
draw(g);
}

private void draw(Graphics g) {


if (running) {
// Draw background
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);

// Draw food
g.setColor(FOOD_COLOR);
g.fillOval(food.x, food.y, UNIT_SIZE, UNIT_SIZE);

// Draw snake
for (Point point : snakeBody) {
g.setColor(SNAKE_COLOR);
g.fillRect(point.x, point.y, UNIT_SIZE,
UNIT_SIZE);
}
} else {
gameOver(g);
}
}

private void gameOver(Graphics g) {


g.setColor(Color.RED);
g.setFont(new Font("Arial", Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Game Over", (WIDTH -
metrics.stringWidth("Game Over")) / 2, HEIGHT / 2);
}

public void resetGame() {


snakeBody.clear();
snakeBody.add(new Point(WIDTH / 2, HEIGHT / 2));
direction = 'R';
running = true;
food.setLocation(random.nextInt(WIDTH /
UNIT_SIZE) * UNIT_SIZE, random.nextInt(HEIGHT /
UNIT_SIZE) * UNIT_SIZE);
timer.restart();
repaint();
}

public static void main(String[] args) {


EventQueue.invokeLater(() -> {
SnakeGame game = new SnakeGame();
game.setVisible(true);

// Create restart button


JButton restartButton = new JButton("Restart");
restartButton.addActionListener(new
ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Reset game state
game.resetGame();
}
});

// Add restart button to a panel


JPanel buttonPanel = new JPanel();
buttonPanel.add(restartButton);

// Add button panel to the game frame


game.add(buttonPanel, BorderLayout.SOUTH);
game.setFocusable(true); // Ensure the frame
receives key events
});
}
}

Output:
CONCLUSION:
The project in python programming of Snake Game is a
simple console application with very simple graphics. In
this project, you can play the popular "Snake Game"
just like you played it elsewhere. You have to use the
up, down, right, or left arrows to move the snake.
Foods are provided at the several co-ordinates of the
screen for the snake to eat. Every time the snake eats
the food, its length will increase by one element along
with the score.
It isn't the world's greatest game, but it does give you
an idea of
what you can achieve with a relatively simple python
programming, and perhaps the basis by which to
extend the principles and create more interesting
games on your own.

You might also like