数字华容道
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Hrdao extends JFrame implements ActionListener
{JMenuBar menubar=new JMenuBar();
JMenu menu1=new JMenu("文件(F)");
JMenuItem kaishi = new JMenuItem("开始",'K');
JMenuItem exit = new JMenuItem("退出",'E');
private static JButton[] Button1;
private GridLayout layout1;
private static Container cp;
private JPanel panel;
private static JLabel win; //用来显示胜利信息.
private static int i,weizhiP,Gesu,width,height;
public Hrdao(int ROW,int COL)
{
super("数字华容道");
super.setJMenuBar(menubar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Gesu=ROW*COL;
menu1.add(kaishi);
menu1.add(exit);
menu1.setMnemonic('F');
menubar.add(menu1);
kaishi.addActionListener(this);
exit.addActionListener(this);
layout1=new GridLayout(ROW,COL);
Button1=new JButton[Gesu];
cp=getContentPane();
panel=new JPanel(layout1);
win=new JLabel("你真棒!");
win.setFont(new Font("仿宋",Font.BOLD,14));
for (i=0 ;i<Gesu;i++)
{ if (i==Gesu-1) Button1[i]=new JButton(" ");
else Button1[i]=new JButton(String.valueOf(i+1));
Button1[i].addActionListener(this);
panel.add(Button1[i]);
}
weizhiP=Gesu-1;
cp.add(panel,"Center");
}
public void actionPerformed(ActionEvent e1)
{ if (e1.getSource()==kaishi) {Start();return;}
if (e1.getSource()==exit) {System.exit(0);return;}
for (i=0 ;i<Gesu;i++)
{ if (e1.getSource()==Button1[i])
{ if (!Button1[i].getLabel().equals(" "))
{if ((Button1[weizhiP].getX()==Button1[i].getX() || Button1[weizhiP].getY()==Button1[i].getY()) && (Button1[weizhiP].getX()+width==Button1[i].getX() || Button1[weizhiP].getX()-width==Button1[i].getX() || Button1[weizhiP].getY()+height==Button1[i].getY() || Button1[weizhiP].getY()-height==Button1[i].getY()))
{Button1[weizhiP].setLabel(Button1[i].getLabel());Button1[i].setLabel(" ");weizhiP=i;break;}
}
}
}
win();
}
void win()
{ for(i=0;i<Gesu-1;i++)
if (Integer.parseInt(Button1[i].getLabel())!=(i+1)) break;
if (i==Gesu-1) System.out.println("你真棒!");
}
void Start()
{int tmp=(int)(Math.random()*(Gesu-1))+1,p=0,tmpB;
Button1[0].setLabel(String.valueOf(tmp));
while(p<=(Gesu-3))
{ tmp=(int)(Math.random()*(Gesu-1))+1;
for(i=0;i<=p;i++)
{tmpB=Integer.parseInt(Button1[i].getLabel());
if (tmpB==tmp) break;
}
if (i>p) {Button1[i].setLabel(String.valueOf(tmp));p++;}
}
Button1[Gesu-1].setLabel(" ");
weizhiP=Gesu-1;
}
public static void main(String[] args)
{
Hrdao hrd=new Hrdao(4,4); //设置长宽
hrd.setVisible(true);
hrd.setLocation(320,250);
hrd.setResizable(false);
hrd.pack();
width=Button1[0].getWidth();height=Button1[0].getHeight();
win.setLocation(hrd.getWidth()/2,hrd.getHeight()/2);
}
}