SlideShare a Scribd company logo
create file name as "board.java"
write below code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private 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 Board() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("head.png");
head = iih.getImage();
}
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, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
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] >= B_HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= B_WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if(!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}
Next you Need to create file as "snake.java"
write below code
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Snake extends JFrame {
public Snake() {
add(new Board());
setResizable(false);
pack();
setTitle("Snake");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame ex = new Snake();
ex.setVisible(true);
}
});
}
}
Note: code contains 2 programs
before writting this code
1.you need create folder with what ever the name you want like ''folder1"
2. this folder should contains PNG Extension images with following names
3. import that that folder before start of the both two codes as "package com.folder1
Solution
create file name as "board.java"
write below code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private 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 Board() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("head.png");
head = iih.getImage();
}
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, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
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] >= B_HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= B_WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if(!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}
Next you Need to create file as "snake.java"
write below code
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Snake extends JFrame {
public Snake() {
add(new Board());
setResizable(false);
pack();
setTitle("Snake");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame ex = new Snake();
ex.setVisible(true);
}
});
}
}
Note: code contains 2 programs
before writting this code
1.you need create folder with what ever the name you want like ''folder1"
2. this folder should contains PNG Extension images with following names
3. import that that folder before start of the both two codes as "package com.folder1

More Related Content

PPTX
Game dev 101 part 3
PDF
Please help!!I wanted to know how to add a high score to this prog.pdf
PDF
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
PDF
This is Java,I am currently stumped on how to add a scoreboard for.pdf
DOCX
DAA Lab File C Programs
PDF
Real life XNA
PPT
Mobile Game and Application with J2ME - Collision Detection
PPTX
Making Games in JavaScript
Game dev 101 part 3
Please help!!I wanted to know how to add a high score to this prog.pdf
Sokoban Game Development Using Java ( Updated using Screenshots & Class Diagr...
This is Java,I am currently stumped on how to add a scoreboard for.pdf
DAA Lab File C Programs
Real life XNA
Mobile Game and Application with J2ME - Collision Detection
Making Games in JavaScript

Similar to create file name as board.javawrite below codeimport java.aw.pdf (20)

PPT
Mobile Game and Application with J2ME
PDF
import java.util.Scanner;public class Main {    public static in.pdf
DOC
Ocr code
PDF
package chapter15;import javafx.application.Application;import j.pdf
DOC
code for quiz in my sql
PDF
David Kopal - Write better React with ReasonML - Codemotion Milan 2018
PDF
Create a java project that - Draw a circle with three random init.pdf
PDF
662305 LAB13
PDF
玉転がしゲームで学ぶUnity入門
DOCX
Computer Graphics Lab File C Programs
PDF
HTML5って必要?
PDF
Programas decompiladores
PPTX
Aditazz 01-ul
PDF
Cpd lecture im 207
KEY
Sbaw090519
PDF
The Ring programming language version 1.5.2 book - Part 52 of 181
PDF
Introduction to d3js (and SVG)
PDF
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
PDF
The Ring programming language version 1.6 book - Part 55 of 189
PDF
Griffon @ Svwjug
Mobile Game and Application with J2ME
import java.util.Scanner;public class Main {    public static in.pdf
Ocr code
package chapter15;import javafx.application.Application;import j.pdf
code for quiz in my sql
David Kopal - Write better React with ReasonML - Codemotion Milan 2018
Create a java project that - Draw a circle with three random init.pdf
662305 LAB13
玉転がしゲームで学ぶUnity入門
Computer Graphics Lab File C Programs
HTML5って必要?
Programas decompiladores
Aditazz 01-ul
Cpd lecture im 207
Sbaw090519
The Ring programming language version 1.5.2 book - Part 52 of 181
Introduction to d3js (and SVG)
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
The Ring programming language version 1.6 book - Part 55 of 189
Griffon @ Svwjug

More from proloyankur01 (20)

PDF
System is a set of interacting or interdependent entities forming an.pdf
PDF
Solution Given thatBy definition of logarithm, we getSolution.pdf
PDF
C is the abbrevation for Carbon .pdf
PDF
Percent error actual - experimental actual x 100.AMU, atomic.pdf
PDF
Please follow the code and comments for description and outputs C.pdf
PDF
organization acted as the IdPThe fundamental concept introduced b.pdf
PDF
Let X = JohnSolutionLet X = John.pdf
PDF
In the United States, policy makers, health professionals, and patie.pdf
PDF
holding period return = (2D1P1Po)Solutionholding period retur.pdf
PDF
Dear,The answer is 25.SolutionDear,The answer is 25..pdf
PDF
Cybrcoin or commonly known as Bitcoin is gaining ground from the las.pdf
PDF
Cant see the questionSolutionCant see the question.pdf
PDF
Baud rate states that the symbol of frequency in a communication cha.pdf
PDF
b.) varies only in name from a one way analysis of varianceSolut.pdf
PDF
AnswerThe evolutionary history of humans since the most recent co.pdf
PDF
Answer-Cultural relativism is a complex concept that has its inte.pdf
PDF
Answer   The answer is (C)DoubleSolutionAnswer   The a.pdf
PDF
Advantages1.Easy to share data over a network2.Better communica.pdf
PDF
An S corporation is formed by filing an Articles of Incorporation wi.pdf
PDF
A)depository institutionsB) contractual savings institutionsC)in.pdf
System is a set of interacting or interdependent entities forming an.pdf
Solution Given thatBy definition of logarithm, we getSolution.pdf
C is the abbrevation for Carbon .pdf
Percent error actual - experimental actual x 100.AMU, atomic.pdf
Please follow the code and comments for description and outputs C.pdf
organization acted as the IdPThe fundamental concept introduced b.pdf
Let X = JohnSolutionLet X = John.pdf
In the United States, policy makers, health professionals, and patie.pdf
holding period return = (2D1P1Po)Solutionholding period retur.pdf
Dear,The answer is 25.SolutionDear,The answer is 25..pdf
Cybrcoin or commonly known as Bitcoin is gaining ground from the las.pdf
Cant see the questionSolutionCant see the question.pdf
Baud rate states that the symbol of frequency in a communication cha.pdf
b.) varies only in name from a one way analysis of varianceSolut.pdf
AnswerThe evolutionary history of humans since the most recent co.pdf
Answer-Cultural relativism is a complex concept that has its inte.pdf
Answer   The answer is (C)DoubleSolutionAnswer   The a.pdf
Advantages1.Easy to share data over a network2.Better communica.pdf
An S corporation is formed by filing an Articles of Incorporation wi.pdf
A)depository institutionsB) contractual savings institutionsC)in.pdf

Recently uploaded (20)

PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
master seminar digital applications in india
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Classroom Observation Tools for Teachers
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Pharmacology of Heart Failure /Pharmacotherapy of CHF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
O7-L3 Supply Chain Operations - ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
Chinmaya Tiranga quiz Grand Finale.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
master seminar digital applications in india
A systematic review of self-coping strategies used by university students to ...
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Classroom Observation Tools for Teachers
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Cell Types and Its function , kingdom of life
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Final Presentation General Medicine 03-08-2024.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS

create file name as board.javawrite below codeimport java.aw.pdf

  • 1. create file name as "board.java" write below code import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener { private final int B_WIDTH = 300; private final int B_HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = 900; private final int RAND_POS = 29; private 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;
  • 2. private Image apple; private Image head; public Board() { addKeyListener(new TAdapter()); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT)); loadImages(); initGame(); } private void loadImages() { ImageIcon iid = new ImageIcon("dot.png"); ball = iid.getImage(); ImageIcon iia = new ImageIcon("apple.png"); apple = iia.getImage(); ImageIcon iih = new ImageIcon("head.png"); head = iih.getImage(); } 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, this); timer.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) {
  • 3. if (inGame) { g.drawImage(apple, apple_x, apple_y, this); for (int z = 0; z < dots; z++) { if (z == 0) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } private void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2); } 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;
  • 4. } 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] >= B_HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= B_WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if(!inGame) { timer.stop(); } } private void locateApple() { int r = (int) (Math.random() * RAND_POS);
  • 5. apple_x = ((r * DOT_SIZE)); r = (int) (Math.random() * RAND_POS); apple_y = ((r * DOT_SIZE)); } @Override public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } private class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_UP) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == KeyEvent.VK_DOWN) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false;
  • 6. } } } } Next you Need to create file as "snake.java" write below code import java.awt.EventQueue; import javax.swing.JFrame; public class Snake extends JFrame { public Snake() { add(new Board()); setResizable(false); pack(); setTitle("Snake"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame ex = new Snake(); ex.setVisible(true); } }); } } Note: code contains 2 programs before writting this code 1.you need create folder with what ever the name you want like ''folder1" 2. this folder should contains PNG Extension images with following names 3. import that that folder before start of the both two codes as "package com.folder1 Solution create file name as "board.java"
  • 7. write below code import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener { private final int B_WIDTH = 300; private final int B_HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = 900; private final int RAND_POS = 29; private 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;
  • 8. public Board() { addKeyListener(new TAdapter()); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT)); loadImages(); initGame(); } private void loadImages() { ImageIcon iid = new ImageIcon("dot.png"); ball = iid.getImage(); ImageIcon iia = new ImageIcon("apple.png"); apple = iia.getImage(); ImageIcon iih = new ImageIcon("head.png"); head = iih.getImage(); } 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, this); timer.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { if (inGame) { g.drawImage(apple, apple_x, apple_y, this);
  • 9. for (int z = 0; z < dots; z++) { if (z == 0) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } private void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2); } 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) {
  • 10. 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] >= B_HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= B_WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if(!inGame) { timer.stop(); } } private void locateApple() { int r = (int) (Math.random() * RAND_POS); apple_x = ((r * DOT_SIZE)); r = (int) (Math.random() * RAND_POS);
  • 11. apple_y = ((r * DOT_SIZE)); } @Override public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } private class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == KeyEvent.VK_UP) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == KeyEvent.VK_DOWN) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false; } }
  • 12. } } Next you Need to create file as "snake.java" write below code import java.awt.EventQueue; import javax.swing.JFrame; public class Snake extends JFrame { public Snake() { add(new Board()); setResizable(false); pack(); setTitle("Snake"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame ex = new Snake(); ex.setVisible(true); } }); } } Note: code contains 2 programs before writting this code 1.you need create folder with what ever the name you want like ''folder1" 2. this folder should contains PNG Extension images with following names 3. import that that folder before start of the both two codes as "package com.folder1