0% found this document useful (0 votes)
26 views5 pages

Java Snake Game Source Code

this document contains java programming code for a snake game

Uploaded by

Nanthakishore N
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views5 pages

Java Snake Game Source Code

this document contains java programming code for a snake game

Uploaded by

Nanthakishore N
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

*;

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class SnakeGame extends JFrame {

private static final int WIDTH = 300;

private static final int HEIGHT = 300;

private static final int DOT_SIZE = 10;

private static final int ALL_DOTS = 900;

private static final int RAND_POS = 29;

private static final int DELAY = 140;

private final int x[] = new int[ALL_DOTS];

private final int y[] = new int[ALL_DOTS];

private int dots;

private int apple_x;

private int apple_y;

private boolean leftDirection = false;

private boolean rightDirection = true;

private boolean upDirection = false;

private boolean downDirection = false;

private boolean inGame = true;


private Timer timer;

private Image ball;

private Image apple;

private Image head;

public SnakeGame() {

initBoard();

private void initBoard() {

addKeyListener(new TAdapter());

setBackground([Link]);

setFocusable(true);

setPreferredSize(new Dimension(WIDTH, HEIGHT));

loadImages();

initGame();

private void loadImages() {

ImageIcon iid = new ImageIcon("src/resources/[Link]");

ball = [Link]();

ImageIcon iia = new ImageIcon("src/resources/[Link]");

apple = [Link]();

ImageIcon iih = new ImageIcon("src/resources/[Link]");

head = [Link]();
}

private void initGame() {

dots = 3;

for (int z = 0; z < dots; z++) {

x[z] = 50 - z * 10;

y[z] = 50;

locateApple();

timer = new Timer(DELAY, new GameCycle());

[Link]();

private void locateApple() {

int r = (int) ([Link]() * RAND_POS);

apple_x = ((r * DOT_SIZE));

r = (int) ([Link]() * RAND_POS);

apple_y = ((r * DOT_SIZE));

private void checkApple() {

if ((x[0] == apple_x) && (y[0] == apple_y)) {

dots++;

locateApple();

}
}

private void move() {

for (int z = dots; z > 0; z--) {

x[z] = x[(z - 1)];

y[z] = y[(z - 1)];

if (leftDirection) {

x[0] -= DOT_SIZE;

if (rightDirection) {

x[0] += DOT_SIZE;

if (upDirection) {

y[0] -= DOT_SIZE;

if (downDirection) {

y[0] += DOT_SIZE;

private void checkCollision() {

for (int z = dots; z > 0; z--) {

if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {

inGame = false;
}

if (y[0] >= HEIGHT) {

Common questions

Powered by AI

The Timer object in the SnakeGame class is used to control the game's pace by triggering actions at regular intervals, specifically set by the DELAY constant (140 ms). It interacts with the GameCycle class, which implements ActionListener and contains the actionPerformed method to update the game's state. This includes moving the snake, checking for collisions, and determining if the snake has eaten an apple. By starting this Timer in the initGame() method, it ensures the game continuously cycles through these updates, producing a smooth gameplay experience.

Directional control in the SnakeGame is managed through boolean flags (leftDirection, rightDirection, upDirection, downDirection) that dictate the movement direction of the snake. These flags are toggled by a key listener, specifically the keyPressed method in the TAdapter class, responding to player input via arrow keys. The move() method uses these flags to update the position of the snake's head by incrementing or decrementing its coordinates. This approach ensures controlled, responsive direction changes while adhering to game rules that prevent immediate 180-degree turns, maintaining gameplay fluidity and logic.

The SnakeGame class supports keyboard input handling through the use of the KeyAdapter abstract class. This is implemented by adding a key listener to the game board in the initBoard() method using the line addKeyListener(new TAdapter()). The TAdapter class, which extends KeyAdapter, overrides the keyPressed method to update the direction of the snake's movement based on arrow key inputs by changing the boolean values of direction flags such as leftDirection, rightDirection, upDirection, and downDirection.

The SnakeGame class uses the loadImages() method to load images for game elements by utilizing the ImageIcon class. Specifically, it loads images for the snake's body (ball), the apple (apple), and the snake's head (head) from the 'src/resources/' directory. These images are then assigned to the respective Image variables which are used to draw the game elements on the screen. This process integrates visual representations effectively into the game's graphical interface.

Randomness is incorporated into the SnakeGame through the locateApple() method, which determines the apple's position. It uses Math.random() to generate random numbers that are then scaled by RAND_POS and multiplied by DOT_SIZE to ensure the apple appears at a random position on the game grid each time it is placed. This randomness adds an element of unpredictability and challenge, encouraging players to adapt to different scenarios to collect the apple, enhancing replayability.

Loading images in the SnakeGame class is handled by the loadImages() method, which uses ImageIcon to fetch images from a specific directory. Challenges may include file path errors, missing resources, or performance lags if images are large or improperly managed. These can be addressed by adopting best practices such as confirming file path accuracy, using try-catch blocks for error handling, preloading images during application initialization to counter delays, and optimizing images for performance, using resources efficiently. Testing the game for directory accessibility and responsiveness is also critical to mitigate potential runtime issues.

The SnakeGame class determines the initial position of the snake by setting the first three dots of the snake's body in a row starting at coordinates (50, 50), with each subsequent dot positioned 10 units to the left as specified in the initGame() method. This is achieved by initializing the x and y arrays for the snake's body's dots. For the apple, its position is set using the locateApple() method, which randomly generates a position by multiplying a random number by the DOT_SIZE (10 units) within the RAND_POS (29 positions) limits.

In the SnakeGame, the constants WIDTH and HEIGHT define the game's window size, ensuring the playing field is square and manageable for a visually simplistic design. DOT_SIZE establishes the size of each unit (or 'dot') that makes up the snake and the placement grid for apples, allowing consistent movement and interaction within a uniform grid system. ALL_DOTS signifies the maximum number of potential units the snake can occupy, which is useful for managing array size and preventing overflow errors, maintaining efficient resource management in the game's architecture.

The architecture of the SnakeGame class facilitates simple 2D game development by emphasizing modular design and clear separation of concerns. It divides the game's responsibilities into distinct methods for initialization (initBoard and initGame), game updates (move, checkApple, and checkCollision), and graphics handling (loadImages). The use of a Timer with regular intervals allows for consistent game state updates and user interactions through keyboard input by leveraging KeyAdapter. This modular approach allows developers to add features or troubleshoot specific functionalities without affecting the entire system.

The SnakeGame class uses the checkCollision() method to determine if a collision has occurred that should end the game. This includes checking if the snake's head collides with any part of its body by iterating through the x and y arrays of the snake's positions. If the head's position matches any body position (from the fifth dot onward), the game state variable inGame is set to false, indicating the game should end. Additionally, boundary checks ensure the snake's head does not cross the game's frame boundaries, further enforcing the game-over condition when violated.

You might also like