Coders Packet

Simple guessing game using Java

By Kethireddy Chandra Karan Reddy

It is a simple guessing game using java AWT and Swing. The game is to pick random correct boxes from given boxes.

The code produces a window-based application upon execution. The game consists of three levels. In the first level, the user is displayed with 5 boxes. Only four of the given boxes are safe(right) and the one left is considered as the wrong box. The user needs to select the right box to enter the next level of the game.

In the second level, three boxes are displayed and two of them are safe. It is required to select the right and safe box to enter the final level. In the third or final level, two boxes are displayed. One box is safe and the other is not safe. Picking the right box in the final level results in winning the game. Choosing the wrong box at any level will quit the game by considering it as a loss.

Implementation of the game:

'Firstlevel', 'Secondlevel', and 'Thirdlevel' are the classes used in this program and the program is saved as

Upon compiling and  executing the, it creates an object for the 'Firstlevel' class and its constructor has the game code.5 boxes are displayed by using the 'Button' objects in the Java Frame.

Boxes are implemented as buttons in the code.The classes and sub packages imported in the program are as follows:

import java.awt.*;

import java.awt.event.*;

import java.lang.Thread;

import java.awt.Font;

import java.swing.*; 

'Math. random()' function is used to arrange all the boxes randomly in every level. Upon clicking a button, it calls the Action Listener corresponding to it and the background of the button is changed to green if it is the right box or else it will show red. If the wrong box chosen,game ends there (calling Frame.dispose()).If the right box is chosen, it will close the current frame and will create an object of 'Secondlevel' which results in displaying another frame with 3 boxes. Similarly, upon right box selection, it will direct to the final level by creating its object. In the 'Thirdlevel'  class, code is written to display the two buttons, and picking the right box pops up a message window showing win. Choosing the wrong box at any level results in popping up a message window displaying that the user lost the game. The Message window is popped before the game finishes(either win or loss) using the JOptionPane.


Download Complete Code


No comments yet