In Java, create a game that helps new mouse users improve their hand-eye coordin
ID: 3661547 • Letter: I
Question
In Java, create a game that helps new mouse users improve their hand-eye coordination. Within a JFrame, display an array of 48 JPanels (changed below) in a GridLayout using eight rows and six columns. Randomly display an X on one of the panels. When the user clicks the correct panel (the one displaying the X), remove the X and display it on a different panel. After the user has succesfully "hit" the correct panel 10 times, display a congratulatory message that includes the user's percentage (hits divided by clicks). Save the file as JCatchTheMouse.java.
Additionally, use 48 JButtons instead of an array of 48 JPanels. Once the user clicks on the tenth correct button, display the course id (CSC 102) by using a JOptionPane message dialog.
Explanation / Answer
import java.io.*; //program uses I/O Stream
import java.awt.*; //program uses Font and Color
import java.awt.event.*; //program uses MouseListeners
import javax.swing.*; //program uses JFrame
import java.util.*; //program uses Calendar
//classJCatchTheMouseTimed3
public class JCatchTheMouseTimed3 extends JFrame
implements MouseListener,
ActionListener
{ //declaration of class constants
final int PANEL_QNTTY = 48;
final int BUTTON_NUM = 36;
//declaration of class-level variables
boolean isCorrect = false;
int currentXnum = 0;
int mouseClickCount = 0;
long beginTime = 0, endTime = 0;
double totalTime = 0;
static double best = 0;
Random rand = new Random();
//GregorianCalendar beginClock = new GregorianCalendar();
//GregorianCalendar endClock = new GregorianCalendar();
//static File bestTimeFile;
static String filePath = "C:\Users\Ben\Desktop\Lesson 13\CatchTheMouse";
static String fileName = "bestTime.dat";
static DataInputStream istream;
static DataOutputStream ostream;
Container con = new Container();
Object locale;
int localeNum = 0;
//declaration of JFrame components
//layouts
GridLayout sixByEightGrid = new GridLayout(6, 8, 1, 1);
//panels
JPanel masterPanel = new JPanel(sixByEightGrid);
JPanel[] panelArray = new JPanel[PANEL_QNTTY];
//labels
JLabel[] labelArray = new JLabel[PANEL_QNTTY];
//buttons
JButton startButton = new JButton("START");
//colors
//fonts
Font xFont = new Font("Arial Black", Font.BOLD, 86);
Font bFont = new Font("Arial Black", Font.ITALIC, 24);
//////////////////////////////////////////////////////
//constructor
public JCatchTheMouseTimed3()
{
super("Catch The Mouse Game with Score File");
addComponents();
setFont();
setColor();
}//end of constructor
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
//main method runs java program
public static void main(String[] args)
{
//declaration of program-level variables
JCatchTheMouseTimed3 display = new JCatchTheMouseTimed3();
File bestTimeFile = new File(filePath, fileName);
try
{
ostream = new DataOutputStream(new FileOutputStream(bestTimeFile));
System.out.println("File for time output successfully created.");
}
catch(IOException ioe)
{
System.err.println("IOE in createOutputFile: " + ioe.getMessage());
}
try
{
istream = new DataInputStream(new FileInputStream(bestTimeFile));
}
catch(IOException ioe)
{
System.err.println("IOE in createInputFile: " + ioe.getMessage());
}
best = readTimeFromFile();
System.out.println("CAN READ: " + bestTimeFile.canRead()
+ " CAN WRITE: " + bestTimeFile.canWrite());
showIntroduction();
writeTimeToFile(best);
display.setVisible(true);
display.setResizable(false);
display.setBounds(0, 0, 1280, 770);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end of method main
public void addComponents()
{
con = getContentPane();
con.add(masterPanel);
for(int i = 0; i < PANEL_QNTTY; i++)
{
panelArray[i] = new JPanel();
}
for(int i = 0; i < PANEL_QNTTY; i++)
{
masterPanel.add(panelArray[i]);
}
for(int i = 0; i < PANEL_QNTTY; i++)
{
labelArray[i] = new JLabel("X");
}
for(int i = 0; i < PANEL_QNTTY; i++)
{
panelArray[i].add(labelArray[i]);
}
panelArray[BUTTON_NUM].add(startButton);
startButton.setBackground(Color.BLACK);
startButton.setForeground(Color.RED);
//adds listeners for button and mouse controls
addMouseListener(this);
for(int i = 0; i < PANEL_QNTTY; i++)
{
panelArray[i].addMouseListener(this);
labelArray[i].addMouseListener(this);
}
startButton.addActionListener(this);
}//end addComponents()
public void setFont()
{
for(int i = 0; i < PANEL_QNTTY; i++)
{
labelArray[i].setFont(xFont);
}
startButton.setFont(bFont);
}//end setFont()
public void setColor()
{
for(int i = 0; i < PANEL_QNTTY; i++)
{
if(i == 0 || i % 2 == 0)
{
panelArray[i].setBackground(Color.BLACK);
}
else if(i % 2 != 0)
{
panelArray[i].setBackground(Color.WHITE);
}
if(i % 2 == 0 && ((i >= 8 && i < 16) ||
(i >= 24 && i < 32) || (i >= 40 && i < 48)))
{
panelArray[i].setBackground(Color.WHITE);
}
else if(i % 2 != 0 && ((i >= 8 && i < 16) ||
(i >= 24 && i < 32) || (i >= 40 && i < 48)))
{
panelArray[i].setBackground(Color.BLACK);
}
}//end for loop for panel colors
for(int i = 0; i < PANEL_QNTTY; i++)
{
labelArray[i].setForeground(Color.RED);
labelArray[i].setVisible(false);
}//end for loop for X Labels
}//end setColor()
public void actionPerformed(ActionEvent e)
{//when Start Button is pressed, this starts the time counter
//(beginTime is activated). It also removes the button,
//and displays the first random X.
beginTime = System.currentTimeMillis();
//System.out.println("In actionPerformed: Begin Time = " + beginTime);
startButton.setVisible(false);
startButton.setEnabled(false);
panelArray[BUTTON_NUM].remove(startButton);
panelArray[BUTTON_NUM].setBackground(Color.BLACK);
displayRandomX();
}//end actionPerformed()
public void displayRandomX()
{
//this for loop 'cleans' the screen of all Xs
for(int i = 0; i < PANEL_QNTTY; i++)
{
labelArray[i].setVisible(false);
}
//this section generates a random number and
//displays that panel number's X
////**(currentNumberX stores the current "correct" X)**////
currentXnum = rand.nextInt(PANEL_QNTTY);
//System.out.println("In displayRandomX(): Current panel #: " + currentXnum);
labelArray[currentXnum].setVisible(true);
}//end displayRandomX()
//mouseEntered method allows the current cursor position to be known
//this location is stored in the variable object "locale"
public void mouseEntered(MouseEvent e)
{
locale = e.getComponent();
}//end mouseEntered()
public void mouseClicked(MouseEvent e)
{
int whichButton = e.getButton();
for(int i = 0; i < PANEL_QNTTY; i++)
{//this converts the current component for 'mouse entered' event
//to a numeric format
if(locale == panelArray[i] || locale == labelArray[i])
{
localeNum = i;
//System.out.println("In mouseClicked: localeNum = "
// + localeNum + " ");
}
}//(end of numeric component conversion for loop)
//localeNum stores the current numeric equivalent
//of the component that the cursor is now in.
//if localeNum equals the "correct" X, then
//a "correct" mouse hover event on the X has occurred
if(localeNum == currentXnum)
{
isCorrect = true;
//System.out.println("isCorrect is now True.");
}
////if a correct mouse hover event exists AND the left
//mouse button is clicked, then a correct mouse click
//has occurred. Now a mouseClickCount can be incremented.
////also, the current X can be wiped clean by method
//displayRandomX() and a new X displayed.
if(isCorrect && (whichButton == MouseEvent.BUTTON1))
{
mouseClickCount += 1;
displayRandomX();
}
if(mouseClickCount == 10)
{
//generate "end time" to calculate total time elapsed
//for 10 correct X hits
endTime = System.currentTimeMillis();
totalTime = endTime - beginTime;
System.out.println("End Time: " + endTime + " ms");
System.out.println("Beginning Time: " + beginTime + " ms");
System.out.println(" - _____________");
System.out.println("TOTAL TIME: "
+ totalTime + " ms = " + (totalTime / 1000 + " s"));
//perform file storage for this game's total time
writeTimeToFile(totalTime, best);
//perform final display and end game
displayResults();
closeFiles();
endGame();
}//end if statement for final (10th) successful click count event
//these two statements reset the mouse hover and click criteria
locale = null;
isCorrect = false;
}//end mouseClicked()
public void mouseExited(MouseEvent e)
{
}//end mouseExited()
public void mousePressed(MouseEvent e)
{
}//end mousePressed()
public void mouseReleased(MouseEvent e)
{
}//end mouseReleased()
public void mouseDragged(MouseEvent e)
{
}//end mouseDragged()
public void mouseMoved(MouseEvent e)
{
}//end mouseMoved()
public static void createOutputFile()
{
try
{
File bestTimeFile = new File(filePath, fileName);
ostream = new DataOutputStream(new FileOutputStream(bestTimeFile));
System.out.println("File for time output successfully created.");
}
catch(IOException ioe)
{
System.err.println("IOE in createOutputFile: " + ioe.getMessage());
}
}//end createOutputFile()
public static double readTimeFromFile()
{
double previousTime = 0;
try
{
previousTime = istream.readDouble();
JOptionPane.showMessageDialog(null,
"Your Time To Beat: " + previousTime + " seconds",
"Record Time From Previous Game", JOptionPane.PLAIN_MESSAGE);
}
catch(IOException ioe)
{
System.err.println("IOE in readTimeFromFile: " + ioe.getMessage());
JOptionPane.showMessageDialog(null,
"Your Time To Beat: " + previousTime + " seconds",
"Record Time From Previous Game", JOptionPane.PLAIN_MESSAGE);
previousTime = 0;
}
return previousTime;
}//end readTimeFromFile()
public static void createInputFile()
{
}//end createInputFile()
public static void writeTimeToFile(double b)
{
try
{
ostream.writeDouble(b);
System.out.println("Write to File SUCCESSFUL! (b)");
}
catch(IOException ioe)
{
System.err.println("IOE in writeTimeToFile(b): " + ioe.getMessage());
}
}//end of writeTimeToFile(b)
public void writeTimeToFile(double t, double b)
{
double timeInSeconds = t / 1000;
try
{
if(timeInSeconds < b || b == 0)
{
ostream.writeDouble(timeInSeconds);
System.out.println("Time: " + timeInSeconds
+ " seconds SUCCESSFULLY written to file!");
JOptionPane.showMessageDialog(null,
"You just beat the fastest time on record! "
+ "Your new fastest time is " + timeInSeconds + " seconds "
+ "Keep up the lightning fast speed!",
"New Record Time", JOptionPane.INFORMATION_MESSAGE);
}
else
{
ostream.writeDouble(b);
}
}
catch(IOException ioe)
{
System.err.println("IOE in writeTimeToFile: " + ioe.getMessage());
}
}//end writeTimeToFile(t, b)
public static void showIntroduction()
{
String intro = "This simple game will help you build up your "
+ "hand-eye coordination! By having you use the "
+ "mouse to click Xs as they bounce across the "
+ "screen, you'll pick up speed until you're the "
+ "envy of everyone at the office! You will be "
+ "clicking everything that comes across your "
+ "computer screen with ease as you blow the "
+ "the competition away! You'll be the hero "
+ "everyone at the water cooler talks about! "
+ "HOW TO PLAY: "
+ "It's simple: Just click the red Xs as quickly "
+ "as possible to beat the previous score! There "
+ "will be 10 Xs in all, so roll up your sleeves!";
JOptionPane.showMessageDialog(null,
intro, "How To Play This Game", JOptionPane.PLAIN_MESSAGE);
}//end showIntroduction()
public void displayResults()
{
String message = "";
if(totalTime > 12000)
{
message = "Nice work! Play again to improve your time!";
}
else if(totalTime > 10000 && totalTime <= 12000)
{
message = "WOW! You're faster than lightning! Keep it up!";
}
else
{
message = "Incredible! You must be the fastest player on earth!";
}
JOptionPane.showMessageDialog(null,
"Your time for this game: " + (totalTime / 1000) + " seconds "
+ message, "Your Time", JOptionPane.PLAIN_MESSAGE);
}//end displayResults()
public void closeFiles()
{
try
{
istream.close();
ostream.close();
}
catch(IOException ioe)
{
System.err.println("IOE in closeFiles: File Close Failed.." + ioe.getMessage());
}
}
public void endGame()
{
closeFiles();
int answer = 1;
answer = JOptionPane.showConfirmDialog(null,
"Do you wish to close the screen and exit the game?");
if(answer == 0)
System.exit(0);
}//end endGame()
}//end of class JCatchTheMouseTimed3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.