书里面有设定游戏,本来想通过可视化做出来,就往后翻到GUI的章节学着做,最后只做了一个简陋的扫雷游戏,用到的都是书上提的东西,有时间想做一个更完善的。
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Simple implements ActionListener {
JButton[]btns=new JButton[100];
static ArrayList location=new ArrayList();
public static void main(String[] args) {
while(location.size()!=10)
{
int j=(int)(Math.random()*100);
if(!location.contains(j))
{
System.out.println(j);
location.add(j);
}
}
Simple gui=new Simple();
gui.go();
}
public void go()
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout = new GridLayout(10, 10);
JPanel panel = new JPanel(layout);
for(int i=0;i<100;i++)
{
btns[i]=new JButton();
btns[i].addActionListener(this);
panel.add(btns[i]);
}
frame.setContentPane(panel);
frame.setSize(1000, 1000);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
for(int i=0;i<100;i++)
{
if(event.getSource()==btns[i])
{
boolean flag=false;
for(int j=0;j<location.size();j++)
{
int val=(Integer)location.get(j);
System.out.println(val);
if(i==val)
{
String str="dead";
btns[i].setText(str);
flag=true;
}
}
if(!flag)
{
String str=""+i;
btns[i].setText(str);
}
else
JOptionPane.showMessageDialog(null,"游戏结束","错误操作",JOptionPane.PLAIN_MESSAGE);
}
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020022621451789.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RqZHh3d2o=,size_16,color_FFFFFF,t_70)