Duck Hunt – Java 2D Game

Shoot the duck game screenshot

Duck Hunt é um jogo de tiro ao alvo desenvolvido em Java 2D, serve como tutorial para desenvolvimento de jogos em Java Swing como desenvolvimento da lógica, padrões de jogos, estruturas de jogos e etc… Peguei esse código fonte no site http://www.gametutorial.net/article/Mouse-input—Shoot-the-duck onde você pode encontrar o código fonte original, aqui eu fiz algumas modificações. Também pode encontrar o mesmo código fonte nesse outro blog https://dewacoding.wordpress.com/2014/10/02/membuat-game-fps-duck/

Vamos as classes do jogo.

Duck.java


package com.company;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

/**
* The duck class.
*
* @author thinksmart
*/

public class Duck {

/**
* How much time must pass in order to create a new duck?
*/
public static long timeBetweenDucks = Framework.secInNanosec / 2;
/**
* Last time when the duck was created.
*/
public static long lastDuckTime = 0;

/**
* Duck lines. Where is starting location for the duck? Speed of the duck?
* How many points is a duck worth?
*/
public static int[][] duckLines = {
{ Framework.frameWidth, (int) (Framework.frameHeight * 0.60), -2,
20 },
{ Framework.frameWidth, (int) (Framework.frameHeight * 0.65), -3,
30 },
{ Framework.frameWidth, (int) (Framework.frameHeight * 0.70), -4,
40 },
{ Framework.frameWidth, (int) (Framework.frameHeight * 0.78), -5,
50 } };
/**
* Indicate which is next duck line.
*/
public static int nextDuckLines = 0;

/**
* X coordinate of the duck.
*/
public int x;
/**
* Y coordinate of the duck.
*/
public int y;

/**
* How fast the duck should move? And to which direction?
*/
private int speed;

/**
* How many points this duck is worth?
*/
public int score;

/**
* Duck image.
*/
private BufferedImage duckImg;

/**
* Creates new duck.
*
* @param x
* Starting x coordinate.
* @param y
* Starting y coordinate.
* @param speed
* The speed of this duck.
* @param score
* How many points this duck is worth?
* @param duckImg
* Image of the duck.
*/
public Duck(int x, int y, int speed, int score, BufferedImage duckImg) {
this.x = x;
this.y = y;

this.speed = speed;

this.score = score;

this.duckImg = duckImg;
}

/**
* Move the duck.
*/
public void Update() {
x += speed;
}

/**
* Draw the duck to the screen.
*
* @param g2d
* Graphics2D
*/
public void Draw(Graphics2D g2d) {
g2d.drawImage(duckImg, x, y, null);
}
}[ /sourcecode ]

<strong>Window.java</strong>

[ sourcecode language=”Java” ]

package com.company;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
* Creates frame and set its properties.
*
* @author thinksmart
*/

public class Window extends JFrame {

private static final long serialVersionUID = 1L;

private Window() {
// Sets the title for this frame.
this.setTitle("Duck Hunt Game - J. Marcos B.");
/**
// Sets size of the frame.
if (true) // Full screen mode
{
// Disables decorations for this frame.
this.setUndecorated(true);
// Puts the frame to full screen.
this.setExtendedState(this.MAXIMIZED_BOTH);
} else // Window mode
{
*/

// Size of the frame.
this.setSize(800, 600);
// Puts frame to center of the screen.
this.setLocationRelativeTo(null);
// So that frame cannot be resizable by the user.
this.setResizable(false);
//this.setResizable(true);
/**
}

*/

// Exit the application when user close frame.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setContentPane(new Framework());

this.setVisible(true);
}

public static void main(String[] args) {
// Use the event dispatch thread to build the UI for thread-safety.
SwingUtilities.invokeLater(new Runnable() {

public void run() {
new Window();
}
});
}
}

Canvas.java


package com.company;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

/**
* Create a JPanel on which we draw and listen for keyboard and mouse events.
*
* @author thinksmart
*/

public abstract class Canvas extends JPanel implements KeyListener,
MouseListener {

private static final long serialVersionUID = 1L;

// Keyboard states - Here are stored states for keyboard keys - is it down
// or not.
private static boolean[] keyboardState = new boolean[525];

// Mouse states - Here are stored states for mouse keys - is it down or not.
private static boolean[] mouseState = new boolean[3];

public Canvas() {
// We use double buffer to draw on the screen.
this.setDoubleBuffered(true);
this.setFocusable(true);
this.setBackground(Color.black);

// If you will draw your own mouse cursor or if you just want that mouse
// cursor disapear,
// insert "true" into if condition and mouse cursor will be removed.
if (true) {
BufferedImage blankCursorImg = new BufferedImage(16, 16,
BufferedImage.TYPE_INT_ARGB);
Cursor blankCursor = Toolkit.getDefaultToolkit()
.createCustomCursor(blankCursorImg, new Point(0, 0), null);
this.setCursor(blankCursor);
}

// Adds the keyboard listener to JPanel to receive key events from this
// component.
this.addKeyListener(this);
// Adds the mouse listener to JPanel to receive mouse events from this
// component.
this.addMouseListener(this);
}

// This method is overridden in Framework.java and is used for drawing to
// the screen.
public abstract void Draw(Graphics2D g2d);

public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
Draw(g2d);
}

// Keyboard
/**
* Is keyboard key "key" down?
*
* @param key
* Number of key for which you want to check the state.
* @return true if the key is down, false if the key is not down.
*/
public static boolean keyboardKeyState(int key) {
return keyboardState[key];
}

// Methods of the keyboard listener.

public void keyPressed(KeyEvent e) {
keyboardState[e.getKeyCode()] = true;
}

public void keyReleased(KeyEvent e) {
keyboardState[e.getKeyCode()] = false;
keyReleasedFramework(e);
}

public void keyTyped(KeyEvent e) {
}

public abstract void keyReleasedFramework(KeyEvent e);

// Mouse
/**
* Is mouse button "button" down? Parameter "button" can be
* "MouseEvent.BUTTON1" - Indicates mouse button #1 or "MouseEvent.BUTTON2"
* - Indicates mouse button #2 ...
*
* @param button
* Number of mouse button for which you want to check the state.
* @return true if the button is down, false if the button is not down.
*/
public static boolean mouseButtonState(int button) {
return mouseState[button - 1];
}

// Sets mouse key status.
private void mouseKeyStatus(MouseEvent e, boolean status) {
if (e.getButton() == MouseEvent.BUTTON1)
mouseState[0] = status;
else if (e.getButton() == MouseEvent.BUTTON2)
mouseState[1] = status;
else if (e.getButton() == MouseEvent.BUTTON3)
mouseState[2] = status;
}

// Methods of the mouse listener.

public void mousePressed(MouseEvent e) {
mouseKeyStatus(e, true);
}

public void mouseReleased(MouseEvent e) {
mouseKeyStatus(e, false);
}

public void mouseClicked(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

}

Framework.java


package com.company;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

/**
* Framework that controls the game (Game.java) that created it, update it and
* draw it on the screen.
*
* @author thinksmart
*/

public class Framework extends Canvas {

private static final long serialVersionUID = 1L;
/**
* Width of the frame.
*/
public static int frameWidth;
/**
* Height of the frame.
*/
public static int frameHeight;

/**
* Time of one second in nanoseconds. 1 second = 1 000 000 000 nanoseconds
*/
public static final long secInNanosec = 1000000000L;

/**
* Time of one millisecond in nanoseconds. 1 millisecond = 1 000 000
* nanoseconds
*/
public static final long milisecInNanosec = 1000000L;

/**
* FPS - Frames per second How many times per second the game should update?
*/
private final int GAME_FPS = 60;
/**
* Pause between updates. It is in nanoseconds.
*/
private final long GAME_UPDATE_PERIOD = secInNanosec / GAME_FPS;

/**
* Possible states of the game
*/
public static enum GameState {
STARTING, VISUALIZING, GAME_CONTENT_LOADING, MAIN_MENU, OPTIONS, PLAYING, GAMEOVER, DESTROYED
}

/**
* Current state of the game
*/
public static GameState gameState;

/**
* Elapsed game time in nanoseconds.
*/
private long gameTime;
// It is used for calculating elapsed time.
private long lastTime;

// The actual game
private Game game;

/**
* Image for menu.
*/
private BufferedImage shootTheDuckMenuImg;

public Framework() {
super();

gameState = GameState.VISUALIZING;

// We start game in new thread.
Thread gameThread = new Thread() {
@Override
public void run() {
try {
GameLoop();
} catch (IOException e) {
e.printStackTrace();
}
}
};
gameThread.start();
}

/**
* Set variables and objects. This method is intended to set the variables
* and objects for this class, variables and objects for the actual game can
* be set in Game.java.
*/
private void Initialize() {

}

/**
* Load files - images, sounds, ... This method is intended to load files
* for this class, files for the actual game can be loaded in Game.java.
*/
private void LoadContent() throws IOException {
URL shootTheDuckMenuImgUrl = this.getClass().getResource(
"/resources/menu.jpg");
shootTheDuckMenuImg = ImageIO.read(shootTheDuckMenuImgUrl);
}

/**
* In specific intervals of time (GAME_UPDATE_PERIOD) the game/logic is
* updated and then the game is drawn on the screen.
*/
private void GameLoop() throws IOException {
// This two variables are used in VISUALIZING state of the game. We used
// them to wait some time so that we get correct frame/window
// resolution.
long visualizingTime = 0, lastVisualizingTime = System.nanoTime();

// This variables are used for calculating the time that defines for how
// long we should put threat to sleep to meet the GAME_FPS.
long beginTime, timeTaken, timeLeft;

while (true) {
beginTime = System.nanoTime();

switch (gameState) {
case PLAYING:
gameTime += System.nanoTime() - lastTime;

game.UpdateGame(gameTime, mousePosition());

lastTime = System.nanoTime();
break;
case GAMEOVER:
// ...
break;
case MAIN_MENU:
// ...
break;
case OPTIONS:
// ...
break;
case GAME_CONTENT_LOADING:
// ...
break;
case STARTING:
// Sets variables and objects.
Initialize();
// Load files - images, sounds, ...
LoadContent();

// When all things that are called above finished, we change
// game status to main menu.
gameState = GameState.MAIN_MENU;
break;
case VISUALIZING:
// On Ubuntu OS (when I tested on my old computer)
// this.getWidth() method doesn't return the correct value
// immediately (eg. for frame that should be 800px width,
// returns 0 than 790 and at last 798px).
// So we wait one second for the window/frame to be set to its
// correct size. Just in case we
// also insert 'this.getWidth() > 1' condition in case when the
// window/frame size wasn't set in time,
// so that we although get approximately size.
if (this.getWidth() > 1 && visualizingTime > secInNanosec) {
frameWidth = this.getWidth();
frameHeight = this.getHeight();

// When we get size of frame we change status.
gameState = GameState.STARTING;
} else {
visualizingTime += System.nanoTime() - lastVisualizingTime;
lastVisualizingTime = System.nanoTime();
}
break;
default:
break;
}

// Repaint the screen.
repaint();

// Here we calculate the time that defines for how long we should
// put threat to sleep to meet the GAME_FPS.
timeTaken = System.nanoTime() - beginTime;
timeLeft = (GAME_UPDATE_PERIOD - timeTaken) / milisecInNanosec; // In
// milliseconds
// If the time is less than 10 milliseconds, then we will put thread
// to sleep for 10 millisecond so that some other thread can do some
// work.
if (timeLeft < 10)
timeLeft = 10; // set a minimum
try {
// Provides the necessary delay and also yields control so that
// other thread can do work.
Thread.sleep(timeLeft);
} catch (InterruptedException ex) {
}
}
}

/**
* Draw the game to the screen. It is called through repaint() method in
* GameLoop() method.
*/
@Override
public void Draw(Graphics2D g2d) {
switch (gameState) {
case PLAYING:
game.Draw(g2d, mousePosition());
break;
case GAMEOVER:
game.DrawGameOver(g2d, mousePosition());
break;
case MAIN_MENU:
g2d.drawImage(shootTheDuckMenuImg, 0, 0, frameWidth, frameHeight,
null);
g2d.drawString("Use left mouse button to shot the duck.",
frameWidth / 2 - 83, (int) (frameHeight * 0.65));
g2d.drawString("Click with left mouse button to start the game.",
frameWidth / 2 - 100, (int) (frameHeight * 0.67));
g2d.drawString("Press ESC any time to exit the game.",
frameWidth / 2 - 75, (int) (frameHeight * 0.70));
g2d.setColor(Color.white);
g2d.drawString("WWW.GAMETUTORIAL.NET", 7, frameHeight - 5);
break;
case OPTIONS:
// ...
break;
case GAME_CONTENT_LOADING:
g2d.setColor(Color.white);
g2d.drawString("GAME is LOADING", frameWidth / 2 - 50,
frameHeight / 2);
break;
default:
break;
}
}

/**
* Starts new game.
*/
private void newGame() {
// We set gameTime to zero and lastTime to current time for later
// calculations.
gameTime = 0;
lastTime = System.nanoTime();

game = new Game();
}

/**
* Restart game - reset game time and call RestartGame() method of game
* object so that reset some variables.
*/
private void restartGame() {
// We set gameTime to zero and lastTime to current time for later
// calculations.
gameTime = 0;
lastTime = System.nanoTime();

game.RestartGame();

// We change game status so that the game can start.
gameState = GameState.PLAYING;
}

/**
* Returns the position of the mouse pointer in game frame/window. If mouse
* position is null than this method return 0,0 coordinate.
*
* @return Point of mouse coordinates.
*/
private Point mousePosition() {
try {
Point mp = this.getMousePosition();

if (mp != null)
return this.getMousePosition();
else
return new Point(0, 0);
} catch (Exception e) {
return new Point(0, 0);
}
}

/**
* This method is called when keyboard key is released.
*
* @param e
* KeyEvent
*/
@Override
public void keyReleasedFramework(KeyEvent e) {
switch (gameState) {
case GAMEOVER:
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
System.exit(0);
else if (e.getKeyCode() == KeyEvent.VK_SPACE
|| e.getKeyCode() == KeyEvent.VK_ENTER)
restartGame();
break;
case PLAYING:
case MAIN_MENU:
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
System.exit(0);
break;
default:
break;
}
}

/**
* This method is called when mouse button is clicked.
*
* @param e
* MouseEvent
*/
@Override
public void mouseClicked(MouseEvent e) {
switch (gameState) {
case MAIN_MENU:
if (e.getButton() == MouseEvent.BUTTON1)
newGame();
break;
default:
break;
}
}
}

Game.java


package com.company;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
* Actual game.
*
* @author thinksmart
*/

//http://www.gametutorial.net/article/Mouse-input---Shoot-the-duck
//https://dewacoding.wordpress.com/2014/10/02/membuat-game-fps-duck/
public class Game {

/**
* We use this to generate a random number.
*/
private Random random;

/**
* Font that we will use to write statistic to the screen.
*/
private Font font;

/**
* Array list of the ducks.
*/
private ArrayList<Duck> ducks;

/**
* How many ducks leave the screen alive?
*/
private int runawayDucks;

/**
* How many ducks the player killed?
*/
private int killedDucks;

/**
* For each killed duck, the player gets points.
*/
private int score;

/**
* How many times a player is shot?
*/
private int shoots;

/**
* Last time of the shoot.
*/
private long lastTimeShoot;
/**
* The time which must elapse between shots.
*/
private long timeBetweenShots;

/**
* Game background image.
*/
private BufferedImage backgroundImg;

/**
* Bottom grass.
*/
private BufferedImage grassImg;

/**
* Duck image.
*/
private BufferedImage duckImg;

/**
* Shotgun sight image.
*/
private BufferedImage sightImg;

/**
* Middle width of the sight image.
*/
private int sightImgMiddleWidth;
/**
* Middle height of the sight image.
*/
private int sightImgMiddleHeight;

public Game() {
Framework.gameState = Framework.GameState.GAME_CONTENT_LOADING;

Thread threadForInitGame = new Thread() {
@Override
public void run() {
// Sets variables and objects for the game.
Initialize();
// Load game files (images, sounds, ...)
LoadContent();

Framework.gameState = Framework.GameState.PLAYING;
}
};
threadForInitGame.start();
}

/**
* Set variables and objects for the game.
*/
private void Initialize() {
random = new Random();
font = new Font("monospaced", Font.BOLD, 18);

ducks = new ArrayList<Duck>();

runawayDucks = 0;
killedDucks = 0;
score = 0;
shoots = 0;

lastTimeShoot = 0;
timeBetweenShots = Framework.secInNanosec / 3;
}

/**
* Load game files - images, sounds, ...
*/
private void LoadContent() {
try {
URL backgroundImgUrl = this.getClass().getResource(
"/resources/background.jpg");
backgroundImg = ImageIO.read(backgroundImgUrl);

URL grassImgUrl = this.getClass().getResource(
"/resources/grass.png");
grassImg = ImageIO.read(grassImgUrl);

//URL duckImgUrl = this.getClass().getResource("/resources/duck.png");
URL duckImgUrl = this.getClass().getResource("/resources/duck01.png");
duckImg = ImageIO.read(duckImgUrl);

URL sightImgUrl = this.getClass().getResource(
"/resources/sight.png");
sightImg = ImageIO.read(sightImgUrl);
sightImgMiddleWidth = sightImg.getWidth() / 2;
sightImgMiddleHeight = sightImg.getHeight() / 2;
} catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
}

/**
* Restart game - reset some variables.
*/
public void RestartGame() {
// Removes all of the ducks from this list.
ducks.clear();

// We set last duckt time to zero.
Duck.lastDuckTime = 0;

runawayDucks = 0;
killedDucks = 0;
score = 0;
shoots = 0;

lastTimeShoot = 0;
}

/**
* Update game logic.
*
* @param gameTime
* gameTime of the game.
* @param mousePosition
* current mouse position.
*/
public void UpdateGame(long gameTime, Point mousePosition) {
// Creates a new duck, if it's the time, and add it to the array list.
if (System.nanoTime() - Duck.lastDuckTime >= Duck.timeBetweenDucks) {
// Here we create new duck and add it to the array list.
ducks.add(new Duck(Duck.duckLines[Duck.nextDuckLines][0]
+ random.nextInt(200),
Duck.duckLines[Duck.nextDuckLines][1],
Duck.duckLines[Duck.nextDuckLines][2],
Duck.duckLines[Duck.nextDuckLines][3], duckImg));

// Here we increase nextDuckLines so that next duck will be created
// in next line.
Duck.nextDuckLines++;
if (Duck.nextDuckLines >= Duck.duckLines.length)
Duck.nextDuckLines = 0;

Duck.lastDuckTime = System.nanoTime();
}

// Update all of the ducks.
for (int i = 0; i < ducks.size(); i++) {
// Move the duck.
ducks.get(i).Update();

// Checks if the duck leaves the screen and remove it if it does.
if (ducks.get(i).x < 0 - duckImg.getWidth()) {
ducks.remove(i);
runawayDucks++;
}
}

// Does player shoots?
if (Canvas.mouseButtonState(MouseEvent.BUTTON1)) {
// Checks if it can shoot again.
if (System.nanoTime() - lastTimeShoot >= timeBetweenShots) {

// **********************************************************************
// Manage sound mp3
String shot = "sounds/shot.mp3";
InputStream openfire = Game.class.getClassLoader().getResourceAsStream(shot);
MP3 shotduck = new MP3();
shotduck.playMusic(openfire);
shotduck.start();
// **********************************************************************

shoots++;

// We go over all the ducks and we look if any of them was
// shoot.
for (int i = 0; i < ducks.size(); i++) {
// We check, if the mouse was over ducks head or body, when
// player has shot.
if (new Rectangle(ducks.get(i).x + 18, ducks.get(i).y, 27,
30).contains(mousePosition)
|| new Rectangle(ducks.get(i).x + 30,
ducks.get(i).y + 30, 88, 25)
.contains(mousePosition)) {
killedDucks++;
score += ducks.get(i).score;

// **********************************************************************
// Manage sound mp3
String ducksound = "sounds/duck.mp3";
InputStream duck = Game.class.getClassLoader().getResourceAsStream(ducksound);
MP3 duckscream = new MP3();
duckscream.playMusic(duck);
duckscream.start();
// **********************************************************************

// Remove the duck from the array list.
ducks.remove(i);

// We found the duck that player shoot so we can leave
// the for loop.
break;
}
}

lastTimeShoot = System.nanoTime();
}
}

// When 200 ducks runaway, the game ends.
if (runawayDucks >= 200)
Framework.gameState = Framework.GameState.GAMEOVER;
}

/**
* Draw the game to the screen.
*
* @param g2d
* Graphics2D
* @param mousePosition
* current mouse position.
*/
public void Draw(Graphics2D g2d, Point mousePosition) {
g2d.drawImage(backgroundImg, 0, 0, Framework.frameWidth,
Framework.frameHeight, null);

// Here we draw all the ducks.
for (int i = 0; i < ducks.size(); i++) {
ducks.get(i).Draw(g2d);
}

g2d.drawImage(grassImg, 0,
Framework.frameHeight - grassImg.getHeight(),
Framework.frameWidth, grassImg.getHeight(), null);

g2d.drawImage(sightImg, mousePosition.x - sightImgMiddleWidth,
mousePosition.y - sightImgMiddleHeight, null);

g2d.setFont(font);
g2d.setColor(Color.darkGray);

g2d.drawString("RUNAWAY: " + runawayDucks, 10, 21);
g2d.drawString("KILLS: " + killedDucks, 160, 21);
g2d.drawString("SHOOTS: " + shoots, 299, 21);
g2d.drawString("SCORE: " + score, 440, 21);
}

/**
* Draw the game over screen.
*
* @param g2d
* Graphics2D
* @param mousePosition
* Current mouse position.
*/
public void DrawGameOver(Graphics2D g2d, Point mousePosition) {
Draw(g2d, mousePosition);

// The first text is used for shade.
g2d.setColor(Color.black);
g2d.drawString("Game Over", Framework.frameWidth / 2 - 39,
(int) (Framework.frameHeight * 0.65) + 1);
g2d.drawString("Press space or enter to restart.",
Framework.frameWidth / 2 - 149,
(int) (Framework.frameHeight * 0.70) + 1);
g2d.setColor(Color.red);
g2d.drawString("Game Over", Framework.frameWidth / 2 - 40,
(int) (Framework.frameHeight * 0.65));
g2d.drawString("Press space or enter to restart.",
Framework.frameWidth / 2 - 150,
(int) (Framework.frameHeight * 0.70));
}
}

Mp3.java


package com.company;

import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.InputStream;

import javax.swing.JOptionPane;
//API Java Zoom
import javazoom.jl.player.Player;

//Download API Java Zoom
//http://www.javazoom.net/mp3spi/mp3spi.html
//Libs: mp3spi1.9.5.jar, jl1.0.1.jar and tritonus_share.jar
public class MP3 extends Thread {

// private String filename;
private InputStream filename;
private Player player;

// constructor that takes the name of an MP3 file
public void playMusic(InputStream in) {
this.filename = in;
}

// Closes the Player
public void close() {
if (player != null)
player.close();
}

// play the MP3 file to the sound card
// run in new thread to play in background
public void run() {
try {
BufferedInputStream bis = new BufferedInputStream(filename);
player = new Player(bis);
player.play();
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Problem playing file mp3! "
+ e, "Duck Hunt Game - J. Marcos B.",
JOptionPane.ERROR_MESSAGE);
System.out.println("Problem playing file mp3! " + e);
}
}

}

Com essas classes você já pode fazer o jogo funcionar, não esqueça das imagens do jogo e os arquivos de áudios e a biblioteca (API) Java Zoom para gerenciar o funcionamento dos áudios mp3 do jogo.

duck.mp3

shot.mp3

Bibliotecas (API) usadas nesse jogo:

Download API Java Zoom
http://www.javazoom.net/mp3spi/mp3spi.html
Libs: mp3spi1.9.5.jar, jl1.0.1.jar e tritonus_share.jar

Bom, agora para você que não é desenvolvedor e só que jogar o jogo aqui vai o executável para baixar.

Duck Hunt Game – J. Marcos B.jar

Pronto.

Anúncios

jHQ: Hellraiser – Os Cânones Da Dor

Uma boa ou má ideia? Uma nova maneira de ler historias em quadrinhos? Ajuda ou não ajuda a leitura nesses tempos corrido? Uma ideia tosca, bizarra… ou o quê? Em tempos de profunda crise econômica ajudaria a alavancar a leitura de HQs?

Download: Hellraiser – Os Cânones Da Dor.jar

Subtitle Box – My Subtitles Collection

My movies collection, my subtitles collection.

Download: Subtitle Box.jar

Subtitle Box by J. Marcos B.jar

Subtitles Index:

1 – 1984 – Nineteen Eighty-Four – Michael Radford – 1984
2 – 2001 – Uma Odisséia No Espaço – 2001 – A Space Odyssey – Stanley Kubrick – 1968
3 – 9 Canções – 9 Songs – Michael Winterbottom – 2004
4 – A Criada – The Handmaiden – Park Chan-Wook – 2016
5 – A Dança Dos Vampiros – Dance Of The Vampires – Roman Polanski – 1967
6 – A Encruzilhada – Crossroads – Walter Hill – 1986
7 – A Estrada Da Vida – La Strada – Federico Fellini – 1954
8 – A Febre Do Rato – Rat Fever – Cláudio Assis – 2011
9 – A Honra Do Poderoso Prizzi – Prizzi’s Honor – John Huston – 1985
10 – A Hora Mais Escura – Zero Dark Thirty – Kathryn Bigelow – 2012
11 – A Nação Do Medo – Fatherland – Christopher Menaul – 1994
12 – A Navalha Na Carne – Razor In The Flesh – Braz Chediak – 1969
13 – A Pervertida – Trasgredire – Tinto Brass – 2000
14 – A Última Tentação De Cristo – The Last Temptation Of Christ – Martin Scorsese – 1988
15 – A Volta Do Parafuso – The Turn Of The Screw – Tim Fywell – 2009
16 – Acerto De Contas – The Big Easy – Jim McBride – 1986
17 – Achados E Perdidos – Achados E Perdidos – José Joffily – 2005
18 – Admirável Mundo Novo – Brave New World – Leslie Libman/Larry Williams – 1998
19 – Akira – Akira – Katsuhiro Otomo – 1988
20 – Alcova – L’Alcova – Joe D’Amato – 1985
21 – Alien – Covenant – Alien Covenant – Ridley Scott – 2017
22 – Alien – O Reino Do Homem – Alien Reign Of Man – Justin Price – 2017
23 – Almas Gêmeas – Heavenly Creatures – Peter Jackson – 1994
24 – Amarelo Manga – Mango Yellow – Cláudio Assis – 2002
25 – Ambição Em Alta Voltagem – Dead Presidents – Allen Hughes/Albert Hughes – 1995
26 – Amém – Amen – Costa Gravas – 2002
27 – Amor – Love – Gaspard Noé – 2015
28 – Amor E Restos Humanos – Love & Human Remains – Denys Arcand – 1993
29 – Amor Estranho Amor – Love Strange Love – Walter Hugo Khouri – 1982
30 – Amores Brutos – Amores Perros – Alejandro González Iñárritu – 2000
31 – Anatomia Do Inferno – Anatomie De L’Enfer – Catherine Breillat – 2004
32 – Anjos Rebeldes – God’s Army / The Prophecy – Gregory Widen – 1995
33 – Apocalypse Now – Apocalypse Now – Francis Ford Coppola – 1979
34 – Aprisionados – Caught – Robert M. Young – 1996
35 – Arizona Nunca Mais – Raising Arizona – Joel Coen/Ethan Coen – 1987
36 – Arquitetura Da Destruição – Undergangens Arkitektur – Peter Cohen – 1989
37 – As Duas Faces Da Lei – Gang Related – Jim Kouf – 1997
38 – As Férias Do Sr. Hulot – Les Vacances De Mr. Hulot – Jacques Tati – 1953
39 – Atômica – Atomic Blonde – David Leitch – 2017
40 – Babel – Babel – Alejandro González Iñárritu – 2006
41 – Barton Fink – Delírios De Hollywood – Barton Fink – Joel Coen/Ethan Coen – 1991
42 – Bicho De Sete Cabeças – Brainstorm – Laís Bodanzky – 2000
43 – Blade Runner – O Caçador De Andróides – Blade Runner – Ridley Scott – 1982
44 – Blade Runner 2049 – Blade Runner 2049 – Denis Villeneuve – 2017
45 – Blade Runner 2049 – 2036 Amanhecer Dos Nexus – Blade Runner 2049 – 2036 Nexus Dawn – Luke Scott – 2017
46 – Blade Runner 2049 – 2048 Sem Escapatória – Blade Runner 2049 – 2048 Nowhere To Run – Luke Scott – 2017
47 – Blade Runner 2049 – Blacaute 2022 – Blade Runner 2049 – Black Out 2022 – Shinichiro Watanabe – 2017
48 – Blow-up – Depois Daquele Beijo – Blow-Up – Michelangelo Antonioni – 1966
49 – Bully – Bully – Larry Clark – 2001
50 – Chinatown – Chinatown – Roman Polanski – 1974
51 – Cidade Dos Sonhos – Mulholland Drive – David Lynch – 2001
52 – Cinzas E Diamantes – Popiol I Diament – Andrzej Wajda – 1958
53 – Classic Albums Metallica – The Black Album – Classic Albums Metallica – The Black Album – Matthew Longfellow – 2001
54 – Clube Dos Cinco – The Breakfast Club – John Hughes – 1985
55 – Coisas Para Fazer Em Denver Quando Você Está Morto – Things To Do In Denver When You´re Dead – Gary Fleder – 1995
56 – Coração Satânico – Harry Angel – Alan Parker – 1987
57 – Coração Sevalgem – Wild At Heart – David Lynch – 1990
58 – Cthulhu – Cthulhu – Dan Gildark – 2007
59 – De Quem É A Vida, Afinal? – Whose Life Is It Anyway – John Badham – 1981
60 – Deadpool – Deadpool – Tim Miller – 2016
61 – Death Note – Death Note – Adam Wingard – 2017
62 – Death Note – Iluminando Um Novo Mundo – Death Note – Light Up The New World – Katsunari Mano – 2016
63 – Deite Comigo – Lie With Me – Clement Virgo – 2005
64 – Desafio À Corrupção – The Hustler – Robert Rossen – 1961
65 – Distrito 9 – District 9 – Neill Blomkamp – 2009
66 – Do Inferno – From Hell – Allen Hughes / Albert Hughes – 2001
67 – Drugstore Cowboy – Drugstore Cowboy – Gus Van Sant – 1989
68 – Eles Não Usam Black-Tie – They Don’t Wear Black Tie – Leon Hirszman – 1981
69 – Ensaio Sobre A Cegueira – Blindness – Fernando Meirelles – 2008
70 – Entre Quatro Paredes – In The Bedroom – Todd Field – 2001
71 – Equilibrium – Equilibrium – Kurt Wimmer – 2002
72 – Eros – Eros – Michelangelo Antonioni/Wong Kar-Wai/Steven Soderbergh – 2004
73 – Expresso Para Neon City – Neon City – Monte Markham – 1991
74 – Fahrenheit 451 – Farenheit 451 – François Truffaut – 1966
75 – Fargo – Uma Comédia De Erros – Fargo – Joel Coen/Ethan Coen – 1996
76 – Feios, Sujos E Malvados – Brutti, Sporchi E Cattivi – Ettore Scola – 1976
77 – Foda-me – Baise-moi – Virginie Despentes/Coralie Trinh Thi – 2000
78 – Fome De Viver – The Hunger – Tony Scott – 1983
79 – Fragmentado – Split – M. Night Shyamalan – 2016
80 – Freejack – Os Imortais – Freejack – Geoff Murphy – 1992
81 – Frenesi – Frenzy – Alfred Hitchcock – 1972
82 – Fúria De Titãns – Clash Of The Titans – Louis Leterrier – 2010
83 – Garganta Profunda – Deep Throat – Gerard Damiano – 1972
84 – Garota Sombria Caminha Pela Noite – A Girl Walks Home Alone At Night – Ana Lily Amirpour – 2014
85 – Gia – Fama E Destruição – Gia – Michael Cristofer – 1985
86 – Hangar 18 – Hangar 18 – James L. Conway – 1980
87 – Hans Staden – Hans Staden – Luiz Alberto Pereira – 1999
88 – Heavy Metal – Universo Em Fantasia – Heavy Metal – Gerald Potterton – 1981
89 – Homo Sapien 1900 – Homo Sapiens 1900 – Peter Cohen – 1998
90 – Insurreição – Uprising – Jon Avnet – 2001
91 – Irreversível – Irreversible – Gaspar Noé – 2002
92 – Jesus De Montreal – Jesus Of Montreal – Denys Arcand – 1989
93 – Ken Park – Ken Park – Larry Clark – 2002
94 – Ladrões De Sabonete – Ladri Di Saponette – Maurizio Nichetti – 1989
95 – Lellebelle – Lellebelle – Mischa Kamp – 2010
96 – Ligações Criminosas – Romanzo Criminale – Michele Placido – 2005
97 – Lolita – Lolita – Stanley Kubrick – 1962
98 – Magnólia – Magnolia – Paul Thomas Anderson – 1999
99 – Marquis De Sade’s Prosperities Of Vice – Akutoku No Sakae – Akio Jissôji – 1988
100 – Metrópolis – Metropolis – Fritz Lang – 1927
101 – Microcosmos – Fantástica Aventura Da Natureza – Microcosmos – Le Peuple De L’herbe – Claude Nuridsany/Marie Pérennou – 1996
102 – Millennium – Os Homens Que Não Amavam As Mulheres – The Girl With The Dragon Tattoo – David Lynch – 2012
103 – Missão Saturno 3 – Saturn 3 – Stanley Donen/John Barry – 1980
104 – Monella – A Travessa – Monella – Frivolous Lola – Tinto Brass – 1998
105 – Morrer Mil Vezes – 8 Million Ways To Die – Hal Ashby – 1986
106 – Mortalmente Perigosa – Gun Crazy – Joseph H. Lewis – 1950
107 – Nascido Para Matar – Full Metal Jacket – Stanley Kubrick – 1987
108 – Neblina E Sombras – Shadows And Fog – Woody Allen – 1991
109 – Nemesis – O Exterminador De Andróides – Nemises – Albert Pyun – 1992
110 – Nina – Nina – Heitor Dhalia – 2004
111 – Numa Noite Escura – One Dark Night – Tom McLoughlin – 1983
112 – O Bandido Da Luz Vermelha – The Red Light Bandit – Rogério Sganzerla – 1968
113 – O Buraco Da Agulha – Eye Of The Needle – Richard Marquand – 1981
114 – O Carniçal – The Ghoul – Freddie Francis – 1975
115 – O Chantagista Eng – Johnny Skidmarks – John Raffo – 1998
116 – O Círculo Do Poder – The Inner Circle – Andrei Konchalovsky – 1991
117 – O Contador – The Accountant – Gavin O’Connor – 2016
118 – O Demônio Das Honze Horas – Pierrot Le Fou – Jean-Luc Godard – 1965
119 – O Destino Bate A Sua Porta – The Postman Always Rings Twice – Tay Garnett – 1946
120 – O Destruidor – Split Second – Tony Maylam/Ian Sharp – 1992
121 – O Enigma Do Horizonte – Event Horizon – Paul W. S. Anderson – 1997
122 – O Exorcista II – O Herege – Exorcist II – The Heretic – John Boorman – 1977
123 – O Fabuloso Destino De Amélie Poulain – Le Fabuleux Destin d’Amélie Poulain – Jean-Pierre Jeunet – 2001
124 – O Grupo Baader-Meinhof – Der Baader Meinhof Komplex – Uli Edel – 2008
125 – O Império Dos Sentidos – In The Realm Of The Senses – Nagisa Oshima – 1976
126 – O Mestre Das Ilusões – Lord Of Illusions – Clive Barker – 1995
127 – O Monstro – Il Mostro – Roberto Benigni – 1994
128 – O Nome da Rosa – Le Nom De La Rose – Jean-Jacques Annaud – 1986
129 – O Pagador De Promesas – The Given Word – Anselmo Duarte – 1962
130 – O Pequeno Diabo – Il Piccolo Diavolo – Roberto Benigni – 1988
131 – O Preço Da Ambição – Gold Coast – Peter Weller – 1997
132 – O Preço Da Traição – Mulholland Falls – Lee Tamahori – 1996
133 – O Preço Do Desejo Eng – Payback – Anthony Hickox – 1995
134 – O Quinto Poder – The Fifth Estate – Bill Condon – 2013
135 – O Sal Da Terra – The Salt Of The Earth – Wim Wenders/Juliano Ribeiro Salgado – 2014
136 – O Segredo De Mary Reilly – Mary Reilly – Stephen Frears – 1996
137 – O Silêncio Do Lago – The Vanishing – George Sluizer – 1993
138 – O Silêncio Do Lago – Spoorloos – George Sluizer – 1988
139 – O Silêncio Dos Inocentes – The Silence Of The Lambs – Jonathan Demme – 1991
140 – Oito E meio – 8 ½ – Otto E Mezzo – Federico Fellini – 1963
141 – Oldboy – Oldboy – Park Chan-wook – 2003
142 – Os Aventureiros Do Bairro Proibido – Big Trouble In Little China – John Carpenter – 1986
143 – Os Cafajestes – The Unscrupulous Ones – Ruy Guerra – 1962
144 – Os Fuzis – The Guns – Ruy Guerra – 1964
145 – Os Imortais – Immortel Ad Vitam – Enki Bilal – 2004
146 – Os Implacáveis – The Getaway – Sam Peckinpah – 1972
147 – Os Reis Da Rua – Street Kings – David Ayer – 2008
148 – Os Rivais – Tin Men – Barry Levinson – 1987
149 – Os Sonhadores – The Dreamers – Bernardo Bertolucci – 2003
150 – Os Substitutos – The Surrogates – Jonathan Mostow – 2009
151 – Paixão Selvagem – Je T’aime… Moi Non Plus – Serge Gainsbourg – 1976
152 – Paixões Violentas – Against All Odds – Taylor Hackford – 1984
153 – Panteras Negras – Panther – Mario Van Peeble – 1985
154 – Paris, Texas – Paris, Texas – Wim Wenders – 1984
155 – Phoenix – A Última Cartada – Phoenix – Danny Cannon – 1998
156 – Pink Floyd – Delicate Sound Of Thunder – Pink Floyd – Delicate Sound Of Thunder – Wayne Isham – 1989
157 – Pink Floyd – Pulse – Pink Floyd – P.U.L.S.E. Live At Earl’s Court London – Disk I – David Mallet – 1994
158 – Pink Floyd – Pulse – Pink Floyd – P.U.L.S.E. Live At Earl’s Court London – Disk II – David Mallet – 1994
159 – Pink Floyd The Wall – Pink Floyd The Wall – Alan Parker – 1982
160 – Platoon – Platoon – Oliver Stone – 1986
161 – Prata Queimada – Plata Quemada – Marcelo Piñeyro – 2000
162 – Prova De Fogo – The Tuskegee Airmen – Robert Markowitz – 1995
163 – Pulp Fiction – Tempo De Violência – Pulp Fiction – Quentin Tarantino – 1994
164 – Quadrophenia – Quadrophenia – Franc Roddam – 1979
165 – Queime Depois Que Ler – Burn After Reading – Joel Coen/Ethan Coen – 2008
166 – Quero Ser John Malkovich – Being John Malkovich – Spike Jonze – 1999
167 – Rabbits – Rabbits – David Lynch – 2002
168 – Repo Man – A Onda Punk – Rapo Man – Alex Cox – 1984
169 – Riddick 3 – Riddick 3 – David Twohy – 2013
170 – Romance X – Romance – Catherine Breillat – 1999
171 – Salò Ou Os 120 Dias De Sodoma – Salò O Le 120 Giornate Di Sodoma – Pier Paolo Pasolini – 1975
172 – Scarface – Scarface – Brian De Palma – 1983
173 – Segredos De Hollywood – Hollywood Confidential – Reynaldo Villalobos – 1997
174 – Sem Suspeita – Above Suspicion – Steven Schachter – 1995
175 – Sob A Pele – Under The Skin – Jonathan Glazer – 2013
176 – Sociedade Dos Poetas Mortos – Dead Poets Society – Peter Weir – 1989
177 – Solaris – Solaris – Andrei Tarkovski – 1972
178 – Sonho De Uma Noite De Verão – A Midsummer Nights Dream – Michael Hoffman – 1999
179 – Sorgo Vermelho – Red Sorghum – Zhang Yimou – 1987
180 – Suburbia – Suburbia – Penelope Spheeris – 1984
181 – Terra Em Transe – Earth Entranced – Glauber Rocha – 1967
182 – Testemunha Do Silêncio – Silent Fall – Bruce Beresford – 1994
183 – Tocaia – Stakeout – John Badham – 1987
184 – Todas As Mulheres Fazem – Cosi Fan Tutte – Tinto Brass – 1992
185 – Touro Indomável – Raging Bull – Martin Scorsese – 1980
186 – Twin Peaks – Os Últimos Dias De Laura Palmer – Twin Peaks – Fire Walk With Me – David Lynch – 1992
187 – Último Tango Em Paris – Le Dernier Tango A Paris – Bernardo Bertolucci – 1972
188 – Um Plano Simples – A Simple Plan – Sam Raimi – 1998
189 – Um Tiro No Escuro – A Shot In The Dark – Blake Edwards – 1964
190 – Uma Mulher Para Dois – Mad Dog And Glory – John McNaughton – 1993
191 – Urotsukidoji – A Lenda Do Demônio – Urotsukidoji – Hideki Takayama – 1986
192 – Valerian E A Cidade Dos Mil Planetas – Valerian And The City Of A Thousand Planets – Luc Besson – 2017
193 – Viagem Alucinante – Enter The Void – Gaspar Noé – 2009
194 – Vida – Live – Daniel Espinosa – 2017
195 – Vidas Secas – Barren Lives – Nelson Pereira Dos Santos – 1963
196 – Vidas Sem Rumo – The Outsiders – Francis Ford Coppola – 1983
197 – Viva Zapata! – Viva Zapata! – Elia Kazan – 1952
198 – Viver E Morrer Em Los Angeles – To Live And Die In L.A. – William Friedkin – 1985
199 – Warlock – O Demônio – Warlock – Steve Miner – 1989
200 – Wassup Rockers – Desafios Da Rua – Wassup Rockers – Larry Clark – 2005
201 – Zulu – Zulu – Jérôme Salle – 2013
202 – Zonas Úmidas – Feuchtgebiete – David Wnendt – 2013

My Subtitles Collection

SplatterPix by Delmator

SplatterPix by Delmator

Site: http://www.java-gaming.org/index.php?topic=27571.0

Source code:

BonusOne.java

BonusTwo.java

Burn.java

Enemy.java

EnemyExplode.java

Explosion.java

Laser.java

MainFrame.java

MainPanel.java

Missile.java

Particles.java

Power.java

PowerBits.java

PowerExplosion.java

Ship.java

Sounds.java

SplatterPix by Delmator.jar
https://www.4shared.com/file/61ZSU360ca/SplatterPix_by_Delmator.html

Tank Game In Java by Jinchong Zhou

Game name: tankGame.jar
Author: Jinchong Zhou
Date: March 2012
Modified: 05/10/2017

Site: http://www-personal.umich.edu/~rexzhou/

Game description: A 2D java Game.

Tank game is a java 2D tank shooting game. The player has controls a yellow tank and his or her purpose is to kill all the enemy tanks (in blue). The game has totally seven rounds, with increading difficulty.

To play the game, click the start new game item bar in the Menu bar in the left up corner.
Press ¡ü¡ú¡ý¡û to move the tank in the corresponding direction, and press button J on the keyboard to make a shot.
The player’s tank have three lifes in total, in other words, one round fails if the player’s tanks get shot three times before it kills all the enemies.

Site: https://github.com/JinchonZhou/tankGame

Class tankgame_2.java

/* 
 * Author: Jinchong Zhou
 * Created on March, 2012
 * Original by: http://www-personal.umich.edu/~rexzhou/
 * File:   tankgame_2.java
 * Modified on Jan, 2014
 * Site: https://github.com/JinchonZhou/tankGame
 * Last modified on: May 10, 2017 by J. Marcos B. 
 * Site: https://isjavado.wordpress.com/
 */

//package tankgame3;

//import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.*;
import java.io.*;

//import javax.sound.sampled.*;

class status {

    final static int totalLevel = 7;

    int level;

    // 0:nothing, 1:lose 2:win 3:prevlose 4: prevwin
    int win;

    boolean change;

    status() {
        this.level = 0;
        this.win = 0;
        this.change = false;
    }
}

public class tankgame_2 extends JFrame implements ActionListener, Runnable {

    private static final long serialVersionUID = 1L;
    MyPanel mp = null;
    MyStartPanel msp = null;
    winPanel wp = null;
    winPanel2 wp2 = null;
    losePanel lp = null;
    JMenuBar jmb = null;
    JMenu jm1 = null;
    JMenuItem jmi1 = null;
    JMenuItem jmi2 = null;
    JMenuItem jmi3 = null;
    JMenuItem jmi4 = null;
    JMenuItem jmi5 = null;

    // Recorder rec = null;
    status currStatus = new status();

    public static void main(String[] args) {

        tankgame_2 myGame = new tankgame_2();

        Thread tt = new Thread(myGame);
        tt.start();
    }

    public tankgame_2() {

        // Recorder rec = new Recorder();
        jmb = new JMenuBar();
        jm1 = new JMenu("Game");
        jm1.setMnemonic('G');
        jm1.setToolTipText("Play");
        jm1.setCursor(new Cursor(Cursor.HAND_CURSOR));

        jmi1 = new JMenuItem("Start New Game");
        jmi1.setToolTipText("Start New Game");
        jmi1.setMnemonic('S');
        jmi1.setCursor(new Cursor(Cursor.HAND_CURSOR));

        jmi3 = new JMenuItem("Next Round");
        jmi3.setToolTipText("Next Round");
        jmi3.setMnemonic('N');
        jmi3.setCursor(new Cursor(Cursor.HAND_CURSOR));

        jmi4 = new JMenuItem("Try Again");
        jmi4.setToolTipText("Try Again");
        jmi4.setMnemonic('T');
        jmi4.setCursor(new Cursor(Cursor.HAND_CURSOR));

        jmi5 = new JMenuItem("Exit");
        jmi5.setToolTipText("Exit");
        jmi5.setMnemonic('E');
        jmi5.setCursor(new Cursor(Cursor.HAND_CURSOR));

        jmi5.addActionListener(this);
        jmi5.setActionCommand("Exit");

        jmi3.addActionListener(this);
        jmi3.setActionCommand("Next");

        jmi4.addActionListener(this);
        jmi4.setActionCommand("Again");

        jmi3.setEnabled(false);
        jmi4.setEnabled(false);

        jm1.add(jmi1);

        jm1.add(jmi3);
        jm1.add(jmi4);
        jm1.add(jmi5);
        jmb.add(jm1);

        msp = new MyStartPanel();
        Thread tt = new Thread(msp);
        tt.start();

        jmi1.addActionListener(this);
        jmi1.setActionCommand("New");
        this.setJMenuBar(jmb);
        this.add(msp);

        this.setSize(500, 450);
        this.setTitle("Tank Game by Jinchong Zhou");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        if (e.getActionCommand().equals("New")) {

            if (currStatus.level > 0)
                this.remove(mp);
            else
                this.remove(msp);

            if (currStatus.win == 4)
                this.remove(wp);

            if (currStatus.win == 3)
                this.remove(lp);

            mp = new MyPanel(1, currStatus);
            Thread t = new Thread(mp);
            this.addKeyListener(mp);
            this.add(mp);
            currStatus.level = 1;
            t.start();
            this.setVisible(true);
            // jmi2.setEnabled(false);
        }

        if (e.getActionCommand().equals("Exit")) {

            System.exit(0);
        }

        if (e.getActionCommand().equals("Next")) {

            currStatus.level++;
            currStatus.change = true;
        }

        if (e.getActionCommand().equals("Again")) {

            currStatus.change = true;

        }

    }

    public void run() {

        while (true) {

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
            if (currStatus.change) {

                currStatus.change = false;

                if (currStatus.win == 1) {

                    jmi4.setEnabled(true);
                    jmi3.setEnabled(false);
                    lp = new losePanel();
                    this.add(lp);
                    this.remove(mp);
                    currStatus.win = 3;

                    this.setVisible(true);
                }

                else if (currStatus.win == 2) {

                    jmi3.setEnabled(true);
                    jmi4.setEnabled(false);
                    // if (currStatus.level == currStatus.totalLevel) {
                    if (currStatus.level == status.totalLevel) {

                        wp2 = new winPanel2();
                        jmi3.setEnabled(false);
                        this.add(wp2);

                    }

                    else {

                        wp = new winPanel();
                        this.add(wp);
                    }
                    this.remove(mp);
                    currStatus.win = 4;

                    this.setVisible(true);
                }

                else {

                    if (currStatus.win == 4) {
                        this.remove(wp);

                    } else if (currStatus.win == 3) {
                        this.remove(lp);
                    }
                    currStatus.win = 0;
                    mp = new MyPanel(currStatus.level, currStatus);
                    this.addKeyListener(mp);
                    this.add(mp);
                    Thread t = new Thread(mp);
                    this.remove(msp);
                    t.start();
                    this.setVisible(true);
                }
            }
        }
    }
}

// my panel
class MyPanel extends JPanel implements java.awt.event.KeyListener, Runnable {

    private static final long serialVersionUID = 1L;
    status myStatus;
    final static int width = 400;
    final static int height = 300;
    Hero hero = null;
    Vector<EnemyTank> ets = new Vector<EnemyTank>();
    final static int enNum[] = { 10, 14, 17, 22, 28, 32, 35, 40 };
    int enSize;

    // three image makes one bomb
    Image image1, image2, image3 = null;

    Vector<Bomb> bombs = new Vector<Bomb>();

    int mylife = 3;

    private FileReader fr = null;

    private BufferedReader br = null;

    public MyPanel(int level, status parentStatus) {

        enSize = enNum[level];

        myStatus = parentStatus;

        image1 = Toolkit.getDefaultToolkit().getImage(
                Panel.class.getResource("/bomb_1.gif"));

        image2 = Toolkit.getDefaultToolkit().getImage(
                Panel.class.getResource("/bomb_2.gif"));

        image3 = Toolkit.getDefaultToolkit().getImage(
                Panel.class.getResource("/bomb_3.gif"));

        hero = new Hero((int) (Math.random() * width),
                (int) (Math.random() * height));

        for (int i = 0; i < enSize; i++) {

            EnemyTank et = new EnemyTank((int) (Math.random() * width),
                    (int) (Math.random() * height));
            Thread t = new Thread(et);
            t.start();
            ets.add(et);

        }
    }

    public void showinfo(Graphics g) {

        this.drawTank(70, 320, g, 0, 1);
        g.setColor(Color.black);
        g.drawString(enSize + " ", 95, 340);
        this.drawTank(120, 320, g, 0, 0);
        g.setColor(Color.black);
        g.drawString(mylife + " ", 145, 340);
        g.drawString("level: " + myStatus.level, 185, 340);
    }

    public void paint(Graphics g) {

        super.paint(g);
        this.showinfo(g);

        if (mylife > 0)
            this.drawTank(hero.getX(), hero.getY(), g, hero.getDirect(), 0);

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

            if (hero.s.get(i - 1).isLive) {
                g.setColor(Color.red);
                g.draw3DRect(hero.s.get(i - 1).x, hero.s.get(i - 1).y, 1, 1,
                        false);
            } else {
                hero.s.remove(i - 1);
                i--;
            }
        }

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

            if (ets.get(i).isLive) {
                this.drawTank(ets.get(i).getX(), ets.get(i).getY(), g,
                        ets.get(i).getDirect(), 1);

                for (int j = 1; j <= ets.get(i).s.size(); j++) {
                    if (ets.get(i).s.get(j - 1).isLive == true) {
                        g.setColor(Color.black);
                        g.draw3DRect(ets.get(i).s.get(j - 1).x,
                                ets.get(i).s.get(j - 1).y, 1, 1, false);
                    } else {
                        ets.get(i).s.remove(j - 1);
                        j--;
                    }
                }
            } else {
                ets.remove(i);
                i--;
            }
        }

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

            Bomb b = bombs.get(i);

            if (b.life > 6)
                g.drawImage(image1, b.x, b.y, 30, 30, this);

            else if (b.life > 3)
                g.drawImage(image2, b.x, b.y, 30, 30, this);

            else
                g.drawImage(image3, b.x, b.y, 30, 30, this);

            b.lifeDown();
            if (b.life == 0) {
                bombs.remove(i);
                i--;
            }
        }
    }

    // function to judge whether a bullet has shot the tank
    public void hittank(Shot s, Tank et) {
        switch (et.getDirect()) {
        case 0:
        case 2:
            if (s.x >= et.x && s.x <= et.x + 20 && s.y >= et.y
                    && s.y <= et.y + 30) {
                s.isLive = false;
                et.isLive = false;
                enSize--;

                // create a bomb
                Bomb newbomb = new Bomb(et.getX(), et.getY());
                bombs.add(newbomb);
            }
            break;
        case 1:
        case 3:
            if (s.x > et.x && s.x < et.x + 30 && s.y > et.y && s.y < et.y + 20) {
                s.isLive = false;
                et.isLive = false;
                enSize--;

                // create a bomb
                Bomb newbomb = new Bomb(et.getX(), et.getY());
                bombs.add(newbomb);
            }
        }
    }

    public void hitmytank(Shot s, Tank et) {
        switch (et.getDirect()) {
        case 0:
        case 2:
            if (s.x >= et.x && s.x <= et.x + 20 && s.y >= et.y
                    && s.y <= et.y + 30) {
                s.isLive = false;
                mylife--;

                // create a bomb
                Bomb newbomb = new Bomb(et.getX(), et.getY());
                bombs.add(newbomb);
            }
            break;

        case 1:
        case 3:

            if (s.x > et.x && s.x < et.x + 30 && s.y > et.y && s.y < et.y + 20) {

                s.isLive = false;
                mylife--;

                // create a bomb
                Bomb newbomb = new Bomb(et.getX(), et.getY());
                bombs.add(newbomb);
            }
        }
    }

    public void drawTank(int x, int y, Graphics g, int direct, int type) {
        switch (type) {
        case 0:
            g.setColor(Color.yellow);
            break;
        case 1:
            g.setColor(Color.blue);
        }

        switch (direct) {
        case 0:
            g.fill3DRect(x, y, 5, 30, false);
            g.fill3DRect(x + 15, y, 5, 30, false);
            g.fill3DRect(x + 5, y + 5, 10, 20, false);
            g.fillOval(x + 4, y + 10, 10, 10);
            g.drawLine(x + 9, y + 15, x + 9, y - 4);
            break;

        case 1:
            g.fill3DRect(x + 5, y + 5, 30, 5, false);
            g.fill3DRect(x + 5, y + 20, 30, 4, false);
            g.fill3DRect(x + 10, y + 10, 20, 10, false);
            g.fillOval(x + 15, y + 10, 10, 10);
            g.drawLine(x + 20, y + 15, x + 40, y + 15);
            break;

        case 2:
            g.fill3DRect(x, y, 5, 30, false);
            g.fill3DRect(x + 15, y, 5, 30, false);
            g.fill3DRect(x + 5, y + 5, 10, 20, false);
            g.fillOval(x + 4, y + 10, 10, 10);
            g.drawLine(x + 9, y + 15, x + 9, y + 28);
            break;

        case 3:
            g.fill3DRect(x + 5, y + 5, 30, 5, false);
            g.fill3DRect(x + 5, y + 20, 30, 4, false);
            g.fill3DRect(x + 10, y + 10, 20, 10, false);
            g.fillOval(x + 15, y + 10, 10, 10);
            g.drawLine(x + 20, y + 15, x - 5, y + 15);
            break;
        }
    }

    public void keyPressed(KeyEvent e) {

        if ((e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S)
                && hero.y < 280) {

            hero.setDirect(2);
            hero.setY(hero.getY() + hero.getSpeed());

            this.repaint();
        }

        else if ((e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W)
                && hero.y > 0) {

            hero.setDirect(0);
            hero.setY(hero.getY() - hero.getSpeed());

            this.repaint();
        }

        else if ((e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A)
                && hero.x > 0) {

            hero.setDirect(3);
            hero.setX(hero.getX() - hero.getSpeed());
            this.repaint();
        }

        else if ((e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D)
                && hero.x < 380) {

            hero.setDirect(1);
            hero.setX(hero.getX() + hero.getSpeed());
            this.repaint();
        }

        if (e.getKeyCode() == KeyEvent.VK_J) {
            if (this.hero.s.size() < 5) {
                hero.shotEnemy();
                this.repaint();
            }
        }

        if (e.getKeyCode() == KeyEvent.VK_L) {
            // this.getRecording();
        }
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {

    }

    public void run() {

        while (!this.myStatus.change) {

            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 0; i < ets.size(); i++) {
                for (int j = 0; j < hero.s.size(); j++)
                    this.hittank(hero.s.get(j), ets.get(i));
            }

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

                EnemyTank t = ets.get(i);
                for (int j = 0; j < t.s.size(); j++)
                    this.hitmytank(t.s.get(j), hero);
            }

            this.repaint();

            if (mylife == 0) {

                this.myStatus.win = 1;
                this.myStatus.change = true;

            }

            if (ets.size() == 0) {

                this.myStatus.win = 2;
                this.myStatus.change = true;
            }
        }
    }

    public BufferedReader getBr() {
        return br;
    }

    public void setBr(BufferedReader br) {
        this.br = br;
    }

    public FileReader getFr() {
        return fr;
    }

    public void setFr(FileReader fr) {
        this.fr = fr;
    }
}

class MyStartPanel extends JPanel implements Runnable {

    private static final long serialVersionUID = 1L;
    int n = 0;

    public MyStartPanel() {
    }

    public void paint(Graphics g) {

        super.paint(g);
        g.fillRect(0, 0, 400, 300);

        if (n % 2 == 0) {

            Font myFont = new Font("Times New Roman", Font.BOLD, 20);
            g.setFont(myFont);
            g.setColor(Color.yellow);
            g.drawString("click start new game to start", 70, 120);
        }
    }

    public void run() {

        while (true) {
            try {
                Thread.sleep(800);
                n++;
                repaint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class winPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    public winPanel() {
    }

    public void paint(Graphics g) {

        super.paint(g);
        g.fillRect(0, 0, 400, 300);

        Font myFont = new Font("Times New Roman", Font.BOLD, 20);
        g.setFont(myFont);
        g.setColor(Color.yellow);
        g.drawString("You win!", 120, 120);
        g.drawString("Click next round or exit", 70, 150);
    }
}

class losePanel extends JPanel {

    private static final long serialVersionUID = 1L;

    public losePanel() {
    }

    public void paint(Graphics g) {

        super.paint(g);
        g.fillRect(0, 0, 400, 300);

        Font myFont = new Font("Times New Roman", Font.BOLD, 20);
        g.setFont(myFont);
        g.setColor(Color.yellow);
        g.drawString("You lose! Click try again or exit", 55, 120);
    }
}

class winPanel2 extends JPanel {

    private static final long serialVersionUID = 1L;

    public winPanel2() {
    }

    public void paint(Graphics g) {

        super.paint(g);
        g.fillRect(0, 0, 400, 300);
        Font myFont = new Font("Times New Roman", Font.BOLD, 20);
        g.setFont(myFont);
        g.setColor(Color.yellow);
        g.drawString("You passed all rounds, Great!", 50, 120);

    }
}

Class member.java

/* 
 * Author: Jinchong Zhou
 * Created on March, 2012
 * Original by: http://www-personal.umich.edu/~rexzhou/
 * File:   member.java
 * Modified on Jan, 2014
 * Site: https://github.com/JinchonZhou/tankGame
 * Last modified on: May 10, 2017 by J. Marcos B. 
 * Site: https://isjavado.wordpress.com/
 */

//package tankgame3;

//import java.io.*;
import java.util.Vector;
import java.util.Random;

public class member {
}

class Tank {

    // horizontal coordinate value for tank
    int x = 0;
    int color;
    boolean isLive = true;
    int direct = 1;
    int speed = 2;

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    // 0 represents up, 1=right, 2=down, 3=left

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public int getDirect() {
        return direct;
    }

    public void setDirect(int direct) {
        this.direct = direct;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    // vertical coordinate value
    int y = 0;

    public Tank(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Shot implements Runnable {
    int x, y, direct, speed;
    boolean isLive = true;

    Shot(int x, int y, int direct, int speed) {
        this.x = x;
        this.y = y;
        this.direct = direct;
        this.speed = speed;
    }

    public void run() {
        while (isLive) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            switch (direct) {
            case 0:
                y -= speed;
                break;
            case 1:
                x += speed;
                break;
            case 2:
                y += speed;
                break;
            case 3:
                x -= speed;
                break;
            }
            if (x < 0 || x > 400 || y < 0 || y > 300) {
                isLive = false;
            }
        }
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getDirect() {
        return direct;
    }

    public void setDirect(int direct) {
        this.direct = direct;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public boolean isLive() {
        return isLive;
    }

    public void setLive(boolean isLive) {
        this.isLive = isLive;
    }
}

class Hero extends Tank {

    Vector<Shot> s = new Vector<Shot>();

    public Hero(int x, int y) {
        super(x, y);
        this.x = 0;
        this.y = 100;
    }

    public void shotEnemy() {
        switch (this.getDirect()) {

        case 0:
            Shot s1 = new Shot(x + 9, y - 4, 0, this.getSpeed() * 6);
            Thread t1 = new Thread(s1);
            t1.start();
            s.add(s1);
            break;

        case 1:
            Shot s2 = new Shot(x + 40, y + 15, 1, this.getSpeed() * 6);
            Thread t2 = new Thread(s2);
            t2.start();
            s.add(s2);
            break;

        case 2:
            Shot s3 = new Shot(x + 9, y + 28, 2, this.getSpeed() * 6);
            Thread t3 = new Thread(s3);
            t3.start();
            s.add(s3);
            break;

        case 3:
            Shot s4 = new Shot(x - 5, y + 15, 3, this.getSpeed() * 6);
            Thread t4 = new Thread(s4);
            t4.start();
            s.add(s4);
            break;
        }
    }
}

class EnemyTank extends Tank implements Runnable {

    Vector<Shot> s = new Vector<Shot>();

    public EnemyTank(int x, int y) {
        super(x, y);
        Random random = new Random();
        int w = random.nextInt(4);
        this.direct = w;
    }

    public void shotEnemy() {

        switch (this.getDirect()) {
        case 0:
            Shot s1 = new Shot(x + 9, y - 4, 0, this.getSpeed() * 6);
            Thread t1 = new Thread(s1);
            t1.start();
            s.add(s1);
            break;
        case 1:
            Shot s2 = new Shot(x + 40, y + 15, 1, this.getSpeed() * 6);
            Thread t2 = new Thread(s2);
            t2.start();
            s.add(s2);
            break;
        case 2:
            Shot s3 = new Shot(x + 9, y + 28, 2, this.getSpeed() * 6);
            Thread t3 = new Thread(s3);
            t3.start();
            s.add(s3);
            break;
        case 3:
            Shot s4 = new Shot(x - 5, y + 15, 3, this.getSpeed() * 6);
            Thread t4 = new Thread(s4);
            t4.start();
            s.add(s4);
            break;
        }
    }

    public void run() {

        while (true) {

            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Random randomnumber = new Random();
            int w = randomnumber.nextInt(4);
            int p;
            this.setDirect(w);

            switch (this.direct) {
            case 0:
                for (int i = 0; i < 30; i++) {

                    p = randomnumber.nextInt(100);
                    if (p == 0 && this.s.size() < 3) {
                        this.shotEnemy();
                    }
                    if (y > 0)
                        this.y -= this.speed;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 1:
                for (int i = 0; i < 30; i++) {

                    p = randomnumber.nextInt(100);

                    if (p == 0 && this.s.size() < 3)
                        this.shotEnemy();
                    if (x < 380)
                        this.x += this.speed;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 2:
                for (int i = 0; i < 30; i++) {
                    p = randomnumber.nextInt(100);
                    if (p == 0 && this.s.size() < 3)
                        this.shotEnemy();
                    if (y < 280)
                        this.y += this.speed;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 3:
                for (int i = 0; i < 30; i++) {
                    p = randomnumber.nextInt(100);
                    if (p == 0 && this.s.size() < 3)
                        this.shotEnemy();
                    if (x > 0)
                        this.x -= this.speed;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class Bomb {

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getLife() {
        return life;
    }

    public void setLife(int life) {
        this.life = life;
    }

    public boolean isLive() {
        return isLive;
    }

    public void setLive(boolean isLive) {
        this.isLive = isLive;
    }

    int x, y;
    int life = 9;
    boolean isLive = true;

    public Bomb(int x, int y) {
        this.x = x;
        this.y = y;
        this.life = 9;
    }

    public void lifeDown() {
        if (life > 0)
            life--;
        else
            this.isLive = false;
    }
}

Download Link: https://www.4shared.com/file/DFNEboqAei/Tank_Game_by_Jinchong_Zhou.html

 

 

 

 

 

 

 

 

 

 

Have a fun :)