SlideShare a Scribd company logo
1 of 12
Download to read offline
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

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

Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2MEJenchoke Tachagomain
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfanwarsadath111
 
package chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfpackage chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfKARTIKINDIA
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
David Kopal - Write better React with ReasonML - Codemotion Milan 2018
David Kopal - Write better React with ReasonML - Codemotion Milan 2018David Kopal - Write better React with ReasonML - Codemotion Milan 2018
David Kopal - Write better React with ReasonML - Codemotion Milan 2018Codemotion
 
Create a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdfCreate a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdfarihantmobileselepun
 
玉転がしゲームで学ぶUnity入門
玉転がしゲームで学ぶUnity入門玉転がしゲームで学ぶUnity入門
玉転がしゲームで学ぶUnity入門nakamura001
 
Computer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsComputer Graphics Lab File C Programs
Computer Graphics Lab File C ProgramsKandarp Tiwari
 
HTML5って必要?
HTML5って必要?HTML5って必要?
HTML5って必要?GCS2013
 
Programas decompiladores
Programas decompiladoresProgramas decompiladores
Programas decompiladoresZulay Limaico
 
Cpd lecture im 207
Cpd lecture im 207Cpd lecture im 207
Cpd lecture im 207Syed Tanveer
 
The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181Mahmoud Samir Fayed
 
Introduction to d3js (and SVG)
Introduction to d3js (and SVG)Introduction to d3js (and SVG)
Introduction to d3js (and SVG)zahid-mian
 
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfImport java.awt.; Import acm.program.; Import acm.graphics.;.pdf
Import java.awt.; Import acm.program.; Import acm.graphics.;.pdfapexcomputer54
 
The Ring programming language version 1.6 book - Part 55 of 189
The Ring programming language version 1.6 book - Part 55 of 189The Ring programming language version 1.6 book - Part 55 of 189
The Ring programming language version 1.6 book - Part 55 of 189Mahmoud Samir Fayed
 

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

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

More from proloyankur01

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

More from proloyankur01 (20)

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

Recently uploaded

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 

Recently uploaded (20)

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 

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