📄 game.java
字号:
// This is a MiniMinesweeper programme
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**Game class*/
public class Game extends JFrame
{
//creat nine buttons
JButton[] button = new JButton[9];
int num=0;
//set a random number
int x = (int)(Math.random()*9);
public Game()
{
//Set FlowLayout manager to arrange the components inside the frame
Container container = getContentPane();
container.setLayout(new GridLayout(3,3,0,0));
for (int i = 0; i < 9; i++)
{
//add button to the frame
button[i] = new JButton();
container.add(button[i]);
}
//creat a listener object
ButtonListener1 Listener1 = new ButtonListener1();
for (int j = 0; j < 9; j++){
//register listener
button[j].addActionListener(Listener1);}
ButtonListener2 Listener2 = new ButtonListener2();
button[x].addActionListener(Listener2);
}
class ButtonListener1 implements ActionListener
{
/**This method will be invoked when you did not click the bomb*/
public void actionPerformed(ActionEvent e)
{
num++;
((JButton)(e.getSource())).setBackground(Color.white);
if(num == 8){
int option = JOptionPane.showConfirmDialog(new JFrame(), "You win!Would you like to play again?","", 0,1);
switch (option){
case(0):
{Game frame = new Game();
frame.setTitle("Game!");
frame.setVisible(true);
frame.setSize(250,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
break;
}
case(1):
{System.exit(0);}}
}
}
}
class ButtonListener2 implements ActionListener
{
/**This method will be invoked when a bomb is clicked*/
public void actionPerformed(ActionEvent e)
{
button[x].setBackground(Color.black);
int option = JOptionPane.showConfirmDialog(new JFrame(),"BOOoom!!!Would you like to play again?","",0,1);
switch (option){
case (0):
{
Game frame = new Game();
frame.setTitle("Game!");
frame.setVisible(true);
frame.setSize(250,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
break;}
case(1):
{System.exit(0);}
}
}
}
/**main method */
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,"Welcome to Mini-MineSweeper!\n"
+"The object of the game os to click on all\n"
+"the squares EXCEPT the one with the bomb.\n"
+"(There is only one bomb). To choose a square\n"
+" to display please simply click onthe square.","Message",JOptionPane.INFORMATION_MESSAGE);
Game frame = new Game();
frame.setTitle("Game!");
frame.setVisible(true);
frame.setSize(250,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -