Hi Friends,
Here I’m posting about my first Java game ~ HitME..!!! Through this post you will understand about:
· Concept of Java Threads.
· Codes for Jframe and other components.
· Java code to close a window.
· Actions related to Buttons and Button Array.
· Random Number generation in Java.
HitME is the Java game in which several Buttons will be provided within a frame. To win the game, you have to click the Button when it become Green in color. Only 5 chances are allowed after that you will loose the game.
Without much “blah-blahs” on theoretical backgrounds, it will be better to get into the code.
Here we go..!!!!(Complete code is given at the end of this post)
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import java.util.Random;
Import all necessary packages. Swing and awt( 1 and 2) for graphics,subpackage awt.event(3) for event handling and util.Random(4) for the Random number generation.
· Codes for Jframe and other components.
5. class GameFrame extends Thread implements ActionListener
6. {
a. int i,n=0,Chances=5;
b. JFrame f;
c. JLabel chanceLabel;
d. JButton b[]=new JButton[50];
e. Random currButton=new Random();
The class GameFrame defines the design of our Game. In line (5) we inherited Thread Base class( to use Thread)and used interface ActionListener. We should override its abstract method actionPerformed(ActionEvent a) (to recognize ButtonClick and other actions, Deep notion of them is not necessary here)
Apparently (5.a) defines total no:of chances, (5.c) defines Frame and so on.
7. GameFrame() {
i. f=new JFrame("GAME");
ii. f.setSize(600,400);
iii. f.setLayout(new FlowLayout());
8. for(i=0;i<49;i++)
9. {
b. b[i]=new JButton("HIT ME");
c. b[i].setActionCommand("Button"+i);
d. b[i].addActionListener(this);
e. b[i].setForeground(Color.blue);
f. f.add(b[i]);
10. }
11. chanceLabel =new JLabel("\n\n\nCHANCES LEFT :"+Chances);
12. f.add(chanceLabel);
13. f.setVisible(true);
Within the constructor of GameFrame, we defined the structure
- Statements (7.i) to(7.iii) are only for Frame.
- Statements 8 and 9 generates 49 buttons, 9.c sets a unique string with each Button with setActionCommnad () to identify which button has been clicked.
- 9.e to give color to Button. Several options for colors are available as gree,magenta, balck etc.
- We added all Buttons in line 9.f.
- In 12 we added a Label to show the number of chances left.
- In 13, we made visibility true, which is a very important step.
· Java code to close a window.
14. f.addWindowListener(new WindowAdapter() {
15. public void windowClosing(WindowEvent e) {
16. System.exit(0);
17. stop();
18. }});
16-18 is the code to close the window.
· Concept of Java Threads.
· Random Number generation in Java.
19.public void run()
a. {
i. try
ii. {
iii. while(true)
iv. {
v. n=currButton.nextInt(49);
vi. b[n].setForeground(Color.green);
vii. sleep(600);
viii. b[n].setForeground(Color.blue);
ix. }
x. }
xi. catch(Exception e)
xii. {
xiii. }}
The code that should be executed by Thread is given in run() method.
- Here we needed to generate random numbers so that Button are made Green at random. To do so while made an endless while loop(19.a.iii)
- currButton is an Object of Random class imported as import java.util.Random. currButton.nextInt(49) yield a random number between 0 1nd 49 so that we can choose any button at random.(19.a.v).
- Set the button color(vi).
- To persist the green color for some time we make Thread inactive by sleep() (vii)
- After that particular time we made the button to prior state by setting default color.(viii)
- Since sleep() is an error generating method we should include this fragment in try-catch block.
Handle Button Click
19. public void actionPerformed(ActionEvent a)
a. {
b. String s="Button"+n;
c. if(!s.equals(a.getActionCommand()))
d. {
e. if(Chances>1)
f. {
g. Chances--;
h. chanceLabel.setText("\n\n\nCHANCES LEFT :"+Chances);
i. }
j. else
k. {
l. JOptionPane.showMessageDialog(f," BETTER LUCK NEXT TIME.!!!YOU LOSE");
m. System.exit(0);
n. stop();
o. }
p. }
q. else
r. {
s. JOptionPane.showMessageDialog(f,"CONGRATULATIONS!!!!!YOU WIN");
t. stop();
u. }
v. }
w. }
Here we define the abstract method actionPerformed () which will be active whenever a Button is clicked.
- String s="Button"+n; store the code for exact button Green active at that time as n points to the active Button. For eg, if 5 th Button is Green at present, s will be “Button 5”.<b>
- a.getActionCommand() will return the string associated with clicked button< for eg: it return Button 3 if we clicked third Button). <c>
- If wrong Button is clicked, if condition in <c> is valid and check the no: of chances left. Disply it in a label< h>
- If all chances are over, pop up a messageBox <l>
- If correct button is clicked Display a winner meassage <s>
NB: If we close the main process<ie, our frame> the Thread will continue its work in background. To avoid this at the moment one wins or looses, the thread should be terminated usind stop().
See lines(19.n) and (19.t)
20.class HitMe
{
a. public static void main(String a[])
b. {
i. GameFrame x=new GameFrame();
ii. x.start();
c. }
b. }
At last make another class(It should contain a main()class) to invoke this GameFrame .
20.i calls the constructor.
20.ii will make the Thread runnable. Using start() method.
The complete code is as follows:
HitME.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
class GameFrame extends Thread implements ActionListener
{
int i,n=0,Chances=5;
JFrame f;
JLabel chanceLabel;
JButton b[]=new JButton[50];
Random currButton=new Random();
GameFrame()
{
f=new JFrame("GAME");
f.setSize(600,400);
f.setLayout(new FlowLayout());
for(i=0;i<49;i++)
{
b[i]=new JButton("HIT ME");
b[i].setActionCommand("Button"+i);
b[i].addActionListener(this);
b[i].setForeground(Color.blue);
f.add(b[i]);
}
JOptionPane.showMessageDialog(f,"HIT ME GAME\nClick Green Button To WIN..!!!!\n Total Chances: 5");
chanceLabel =new JLabel("CHANCES LEFT :"+Chances);
f.add(chanceLabel);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
stop();
}});
}
public void run()
{
try
{
while(true)
{
n=currButton.nextInt(49);
b[n].setForeground(Color.green);
sleep(600);
b[n].setForeground(Color.blue);
}
}
catch(Exception e)
{}
}
public void actionPerformed(ActionEvent a)
{
String s="Button"+n;
if(!s.equals(a.getActionCommand()))
{
if(Chances>1)
{
Chances--;
chanceLabel.setText("CHANCES LEFT :"+Chances);
}
else
{
JOptionPane.showMessageDialog(f,"BETTER LUCK NEXT TIME.!!!\nYOU LOSE");
System.exit(0);
stop(); }
}
else
{
JOptionPane.showMessageDialog(f,"CONGRATULATIONS!!!!!YOU WIN");
System.exit(0);
stop(); }
}
}
class HitME
{
public static void main(String a[])
{
GameFrame x=new GameFrame();
x.start();
}
}
Random currButton=new Random();
GameFrame()
{
f=new JFrame("GAME");
f.setSize(600,400);
f.setLayout(new FlowLayout());
for(i=0;i<49;i++)
{
b[i]=new JButton("HIT ME");
b[i].setActionCommand("Button"+i);
b[i].addActionListener(this);
b[i].setForeground(Color.blue);
f.add(b[i]);
}
JOptionPane.showMessageDialog(f,"HIT ME GAME\nClick Green Button To WIN..!!!!\n Total Chances: 5");
chanceLabel =new JLabel("CHANCES LEFT :"+Chances);
f.add(chanceLabel);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
stop();
}});
}
public void run()
{
try
{
while(true)
{
n=currButton.nextInt(49);
b[n].setForeground(Color.green);
sleep(600);
b[n].setForeground(Color.blue);
}
}
catch(Exception e)
{}
}
public void actionPerformed(ActionEvent a)
{
String s="Button"+n;
if(!s.equals(a.getActionCommand()))
{
if(Chances>1)
{
Chances--;
chanceLabel.setText("CHANCES LEFT :"+Chances);
}
else
{
JOptionPane.showMessageDialog(f,"BETTER LUCK NEXT TIME.!!!\nYOU LOSE");
System.exit(0);
stop(); }
}
else
{
JOptionPane.showMessageDialog(f,"CONGRATULATIONS!!!!!YOU WIN");
System.exit(0);
stop(); }
}
}
class HitME
{
public static void main(String a[])
{
GameFrame x=new GameFrame();
x.start();
}
}
I hope this post was useful for you.!! I'm waiting for youe valuable suggestions. Please comment here ur Feedback..!!
Thank you..!
Bye..!! :)
Bye..!! :)
2 comments :
How do you import the first files? (javax.swing.*, etc.)
How do you save/compile it?
Post a Comment