0% found this document useful (0 votes)
41 views17 pages

ADVANCED JAVA FRONT PG-merged

Uploaded by

sdnchethan
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)
41 views17 pages

ADVANCED JAVA FRONT PG-merged

Uploaded by

sdnchethan
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
You are on page 1/ 17

MVJ COLLEGE OF ENGINEERING

BANGALORE-560068

ACADEMIC YEAR- 2023-2024

DEPARTMENT OF INFORMATION SCIENCE


ENGINEERING
ADVANCED JAVA REPORT
SNAKE GAME
COURSE TITLE: ADVANCED JAVA
COURSE CODE: MVJ22IS42

SUBMITTED BY:
BASAVARAJU L: 1MJ22IS017
DHIRAJ ACHARYA: 1MJ22IS025
MOHAMED MUNTHASIR ABAAN: 1MJ22IS060
MOHAMMED MUNAZIR: 1MJ22IS061

SUBMITTED TO:
VENKATESH G
INTRODUCTION
The Snake game is a classic arcade game that has been enjoyed by players for decades. It
involves controlling a snake that moves around the screen, eating food to grow longer, and
avoiding collisions with the walls or itself. Implementing the Snake game in Java can be a
great way to practice object-oriented programming, handling user input, and managing game
state.

Here's an introduction to creating a Snake game using Java:

Overview of the Snake Game

1. Game Board: The game is played on a grid. The board can be represented as a 2D array
where each cell can be empty, contain part of the snake, or contain food.
2. Snake: The snake is made up of a series of segments, usually implemented as a list of
coordinates. It moves in a given direction, and each segment follows the one before it.
3. Food: Food appears randomly on the board. When the snake's head moves over the food,
the snake grows, and new food is placed on the board.
4. Collision Detection: The game must detect when the snake hits the wall or itself to end
the game.
5. User Input: The direction of the snake is controlled by user input, typically through
keyboard arrow keys.

Key Points to Implement


1. Movement: Update the snake's position based on its direction and ensure the body
follows the head.
2. Collision Detection: Implement logic to check if the snake's head collides with the walls
or itself.
3. Growth and Scoring: Increase the length of the snake when it eats food and keep track of
the score.
4. Game Over: Implement logic to end the game when a collision occurs and display a game-
over message.

This introduction covers the basic structure of a Snake game in Java. You can enhance it by
adding features such as levels, different types of food, and improved graphics.
IDENTITY
Advanced Java refers to the aspects of Java programming beyond the basic language
features, often involving enterprise-level applications, graphical user interfaces (GUIs), and
sophisticated data management. It includes various technologies and frameworks that enable
developers to build robust, scalable, and feature-rich applications.

Swing is one of the key libraries for building graphical user interfaces (GUIs) in Java. It is
part of the Java Foundation Classes (JFC) and provides a rich set of GUI components and
tools to create desktop applications.

Key Aspects of Advanced Java:

1. Java Enterprise Edition (Java EE):


Servlets and JSP: For web applications.
Enterprise JavaBeans (EJB): For business logic and transactions.
Java Persistence API (JPA): For managing relational data.
Java Message Service (JMS): For messaging and communication.
Java Server Faces (JSF): For building component-based user interfaces.
2. Concurrency and Multithreading:
Managing multiple threads for better performance and responsiveness.
Using java.util.concurrent package for high-level concurrency utilities like Executors,
Concurrent Collections, and synchronization aids.
3. Networking and I/O:
Java NIO (New Input/Output): For scalable I/O operations.
Networking APIs: For communication between distributed systems.
4. JavaFX:
A newer library for building modern, visually rich GUI applications.
Provides advanced features for 2D and 3D graphics, media, and web integration.
5. Design Patterns:
Implementing common design patterns such as Singleton, Factory, Observer, and MVC
(Model-View-Controller) to improve code maintainability and flexibility.

Swing Overview

Swing is a GUI toolkit that provides a set of lightweight components for building user
interfaces. It is built on top of the Abstract Window Toolkit (AWT) and offers a more
sophisticated set of components and functionalities.

Key Components of Swing:

1. JFrame: The main window of a Swing application.


2. JPanel: A container used to group and organize other components.
3. JButton, JLabel, JTextField: Basic components for user interaction.
4. JTable, JTree: For displaying tabular data and hierarchical data.
5. JMenuBar, JMenu, JMenuItem: For creating menus.
Swing Features:

Lightweight Components: Swing components are not dependent on native system


components, leading to a more consistent look and feel across platforms.
Pluggable Look and Feel: Allows customization of the appearance of the GUI components
to match different operating systems or styles.
Event Handling: Swing provides a comprehensive event handling model, using listeners
to respond to user actions.
PROGRAM 1
Interfaces:

1. ActionListener:
ActionListener is an interface in java that defines a single method,
actionPerformed(ActionEvent e), which is called when an action occurs.
Method(s):
actionPerformed(ActionEvent e)
2. KeyListener:
Purpose: This interface is used to receive keyboard events.
Method(s):
keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)

Classes:
1. java.awt.Dimension:
Purpose: Represents a width and height dimension.
2. java.awt.Graphics:
Purpose: Provides methods for drawing shapes, text, and images.
3. java.awt.Color:
Purpose: Defines colors used for drawing and rendering.
4. java.awt.Font:
Purpose: Represents font information for text rendering.
5. javax.swing.JPanel:
Purpose: A container that can be used to group and manage other Swing
components.
Method(s):
setPreferredSize(Dimension d)
setBackground(Color c)
addKeyListener(KeyListener l)
6. javax.swing.Timer:
Purpose: Fires action events at specified intervals.
Method(s):
start()
stop()
7. java.util.Random:
Purpose: Generates pseudo-random numbers.
Method(s):
nextInt(int bound)
8. java.util.ArrayList:
Purpose: Implements a resizable array.
Method(s):
add(E e)
get(int index)
size()
9. java.awt.event.ActionEvent:
Purpose: Represents an action event.
10. java.awt.event.KeyEvent:
Purpose: Represents a key event.

Summary
Interfaces: ActionListener and KeyListener.
Classes: Dimension, Graphics, Color, Font, JPanel, Timer, Random, ArrayList,
ActionEvent, KeyEvent, and the custom SnakeGame and Tile classes.
Methods:
In SnakeGame: Methods for handling the game logic, rendering, and user input.
In Tile: Constructor to initialize tile positions.

PROGRAM 2
Classes:

1) JFrame JFrame is a class in the Java Swing library used for creating graphical user
interfaces . It provides a window with standard decorations such as a title, border, and
buttons for closing, minimizing, and maximizing the window.

2) JPanel JPanel is a Java Swing component that provides a container for other
components.

3) JTextField JTextField is a Java Swing component that allows users to enter and edit text.
It's a single-line text field that can be used to input and display text, such as names,
password, etc.

4) JButton JButton is a Java Swing component that creates a button with a label or icon
that can be clicked by the user to perform an action.

5) JLabel JLabel is a Java Swing component that displays text, images, or both. It's a non-
editable label that can be used to display information, instructions, or decorative text in a
graphical user interface
METHODS:

1. setTitle() Is a method in Java Swing that sets the title of a window.


2. setDefaultCloseOperation() Is a method in Java Swing that sets the default
operation for a window when it is closed.
3. setSize() Is a method in Java Swing that sets the size of the window.
4. setText() Is a method in Java Swing that sets the text.
5. add(): Is a method in Java Swing that adds components into the container.
6. setVisible() Is a method in Java Swing that makes the frame visible if it is true.
7. setResizable() is a method in java Swing in which the window can be resized while
it’s running.
PROGRAM 1
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;

Tile snakeHead;

ArrayList<Tile> snakeBody;

Tile food;
Random random;

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;
gameLoop = new Timer(100, this);

gameLoop.start();

public void paintComponent(Graphics g) {

super.paintComponent(g);

draw(g);

public void draw(Graphics g) {

for(int i = 0; i < boardWidth/tileSize; i++) {

g.drawLine(i*tileSize, 0, i*tileSize, boardHeight);

g.drawLine(0, i*tileSize, boardWidth, i*tileSize);

g.setColor(Color.red);

g.fill3DRect(food.x*tileSize, food.y*tileSize, tileSize, tileSize, true);

g.setColor(Color.green);

g.fill3DRect(snakeHead.x*tileSize, snakeHead.y*tileSize, tileSize, tileSize, true);


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

Tile snakePart = snakeBody.get(i);

g.fill3DRect(snakePart.x*tileSize, snakePart.y*tileSize, tileSize, tileSize, true);

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() {


if (collision(snakeHead, food)) {

snakeBody.add(new Tile(food.x, food.y));

placeFood();

for (int i = snakeBody.size()-1; i >= 0; i--) {

Tile snakePart = snakeBody.get(i);

if (i == 0) {

snakePart.x = snakeHead.x;

snakePart.y = snakeHead.y;

else {

Tile prevSnakePart = snakeBody.get(i-1);

snakePart.x = prevSnakePart.x;

snakePart.y = prevSnakePart.y;

snakeHead.x += velocityX;

snakeHead.y += velocityY;

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

Tile snakePart = snakeBody.get(i);


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) {

move();

repaint();

if (gameOver) {

gameLoop.stop();

}
}

@Override

public void keyPressed(KeyEvent e) {

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;

PROGRAM 2
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();

}
OUTPUT

You might also like