This code is a 'game' where a square (bird) moves horizontally over the screen and
the player has to click (shoot) the square. You get 5 bullets per session
and a session is 5 birds.
the game frame:
Code:
/**
* Shooter mainframe
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Shooter extends JFrame implements ActionListener {
BorderLayout borderLayout1 = new BorderLayout();
JPanel buttonPanel = new JPanel();
JButton closeBtn = new JButton();
ShooterPanel shootPanel = null;
JButton startBtn = new JButton();
JLabel hitsMissLabel = new JLabel();
/**
* Constructor
*/
public Shooter() {
try {
shootPanel=new ShooterPanel(this);
jbInit();
closeBtn.addActionListener(this);
startBtn.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* Display number of hits/misses, invoked from the ShooterPanel
* @param txt
*/
public void setHitMissLabel(String txt) {
hitsMissLabel.setText(txt);
}
/**
* Set up GUI
* @throws Exception
*/
private void jbInit() throws Exception {
this.getContentPane().setLayout(borderLayout1);
closeBtn.setText("Close");
buttonPanel.setBorder(BorderFactory.createEtchedBorder());
startBtn.setText("Start");
hitsMissLabel.setBorder(BorderFactory.createLineBorder(Color.black));
hitsMissLabel.setPreferredSize(new Dimension(150, 22));
hitsMissLabel.setHorizontalAlignment(SwingConstants.CENTER);
hitsMissLabel.setText("Hits: 0, Misses: 0");
this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(closeBtn, null);
this.getContentPane().add(shootPanel, BorderLayout.CENTER);
buttonPanel.add(startBtn, null);
buttonPanel.add(hitsMissLabel, null);
}
/**
* Handle button clicks
* @param e
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource()==startBtn) {
shootPanel.startGame();
} else if (e.getSource()==closeBtn) {
System.exit(0);
}
}
// ****************** MAIN ********************
public static void main(String[] args) {
Shooter sht = new Shooter();
sht.setBounds(10,10,500,400);
sht.setVisible(true);
}
}
the game panel:
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
*
*/
public class ShooterPanel extends JPanel implements Runnable, MouseListener {
// change to modify game speed
private int freq=40;
private int hits=0;
private int misses=0;
private int bullets=0;
private int rounds=0;
// change to modify bird size
private Rectangle target=new Rectangle(0,0,30,30);
private boolean isRunning=false;
private Thread gameRunner=null;
private Shooter shooter=null;
/**
* Constructor
* @param shooter
*/
public ShooterPanel (Shooter shooter) {
this.shooter=shooter;
this.addMouseListener(this);
}
// random number part
private static Random rand=new Random(System.currentTimeMillis());
private static int getRandom(java.util.Random rand, int min, int max) {
double d=rand.nextDouble()*(double)max;
return (int)(d+min);
}
/**
* Start bird at random height
* @return
*/
private int getStartYPos() {
int max=this.getSize().height-target.height;
return getRandom(rand, 0, max);
}
// thread control methods
private synchronized void setRunning (boolean isRunning) {
this.isRunning=isRunning;
}
private synchronized boolean getRunning () {
return this.isRunning;
}
private synchronized boolean isHit (Point p) {
return this.target.contains(p);
}
// game start, invoked from the mainframe
public void startGame() {
bullets=5;
rounds=5;
hits=0;
misses=0;
gameRunner=new Thread(this);
setRunning(true);
gameRunner.start();
}
/**
* Set a bird at start position
*/
private synchronized void initializeTarget () {
int yPos=getStartYPos();
target.setLocation(0,yPos);
}
/**
* Move bird to the right
*/
private synchronized void moveTarget() {
// could have added code to make target wiggle up and down
target.x=target.x+4;
if (target.x >= this.getSize().width) {
rounds--;
if (rounds==0) {
setRunning(false);
} else {
initializeTarget();
}
}
}
/**
* Render game display
* @param g
*/
public void paint (Graphics g) {
update (g);
}
public void update (Graphics g) {
Color c= g.getColor();
g.setColor(Color.lightGray);
g.fillRect(0,0,this.getSize().width, this.getSize().height);
if (!getRunning()) {
g.setColor(Color.blue);
g.drawString("Game not started", 10,20);
} else {
g.setColor(Color.red);
g.fillRect(target.x, target.y, target.width, target.height);
if (bullets == 0) {
g.drawString("Out of bullets", 10, 20);
}
else {
g.drawString("Bullets left: " + bullets, 10, 20);
}
g.setColor(c);
}
}
/**
* The game action
*/
public void run() {
initializeTarget();
while (getRunning()) {
try {
gameRunner.sleep(freq);
moveTarget();
repaint();
}
catch (InterruptedException ex) {
return;
}
}
}
/**
* A shot
* @param e
*/
public void mousePressed(MouseEvent e) {
if (bullets==0) return;
if (isHit(e.getPoint())) { // a hit !
hits++;
initializeTarget();
} else {
misses++;
}
bullets--;
if (bullets==0) setRunning(false);
shooter.setHitMissLabel("Hits: "+hits+", Misses: "+misses);
repaint();
}
// don't need these
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
Bookmarks