- 注册时间
- 2004-8-29
- 最后登录
- 1970-1-1
|
这是我写的第一个JAVA GUI程序,前两天乘着周末不用上班看了下JAVA的Swing编程,顺便写了个扫雷游戏练练手~.
代码很简单,因为是第一次弄Swing编程,估计有些地方处理的不好.
发贴只是为了纪念一下第一个GUI程序^_^
- /**
- * Created by IntelliJ IDEA.
- * User: Eastsun
- * Date: 2006-7-23
- * Time: 17:30:16
- * To change this template use File | Settings | File Templates.
- */
- package mine;
- import java.util.*;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.border.*;
- import java.net.*;
- class Timer implements Runnable{
- private Thread thread;
- private JLabel label;
- long startTime;
- public void startTimer(){//开始计时
- startTime = System.currentTimeMillis();
- thread = new Thread(this);
- thread.start();
- }
- private static String formatStr(long n){
- if(n < 10) return "00" + n;
- else if(n < 100) return "0" + n;
- else if(n < 1000) return String.valueOf(n);
- else return "...";
- }
- public void stopTimer(){//停止计时
- thread = null;
- }
- public void run(){
- while(thread != null){
- long curTime = System.currentTimeMillis();
- label.setText(formatStr((curTime - startTime) / 1000));
- try{
- thread.sleep(500);
- } catch(Exception e){
- }
- }
- }
- public Timer(JLabel label){
- this.label = label;
- }
- }
- public class Mine extends JFrame{
- private static final int STATUS_M = 1, STATUS_O = 2, STATUS_F = 4;
- private static final int BUTTON_HGAP = 2, BUTTON_VGAP = 2, BUTTON_WIDTH = 30, BUTTON_HEIGHT = 30;
- private static final int EASY_LEVEL = 0, NORMAL_LEVEL = 1, HARD_LEVEL = 2, DEFINE_LEVEL = 3;
- private Icon numIcon[];
- private Icon mineIcon;
- private Icon smileIcon, laughIcon, cryIcon;
- private Block[][] blocks = null;
- private int height, width, mine, level, mark, remainder; //mark用来计数:打开的和标记的总数,当等于height*width时游戏获胜 ,remainder;剩余的雷
- private JPanel panel = null, bar = null;
- private JLabel left, mid, right;
- private Timer timer;
- private boolean flags = false; //是否已经开始游戏
- public Mine(){
- super("扫雷");
- initSource();
- setJMenuBar(getMenu());
- setLevel(NORMAL_LEVEL);
- refresh();
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setResizable(false);
- setVisible(true);
- }
- public Icon getIcon(String filename){
- URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader();
- URL url = null;
- Image image = null;
- url = urlLoader.findResource(filename);
- image = Toolkit.getDefaultToolkit().getImage(url);
- MediaTracker mediatracker = new MediaTracker(this);
- try {
- mediatracker.addImage(image, 0);
- mediatracker.waitForID(0);
- }
- catch (InterruptedException _ex) {
- image = null;
- }
- if (mediatracker.isErrorID(0)) {
- image = null;
- }
- return new ImageIcon(image);
- }
- private void initSource(){
- numIcon = new Icon[9];
- for(int n = 0; n <= 8; n++) numIcon[n] = getIcon("image/"+n + "x.jpg");
- mineIcon = getIcon("image/mine.jpg");
- smileIcon = getIcon("image/smile.gif");
- laughIcon = getIcon("image/laugh.gif");
- cryIcon = getIcon("image/cry.gif");
-
- left = new JLabel();
- mid = new JLabel();
- right = new JLabel();
- timer = new Timer(right);
- }
- private JMenuBar getMenu(){
- //设置菜单,只需在构造函数中调用一次
- JMenuBar menuBar = new JMenuBar();
- JMenu gameMenu = new JMenu("游 戏");
- menuBar.add(gameMenu);
- JMenuItem newGame = new JMenuItem("开 局");
- gameMenu.add(newGame);
- newGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, ActionEvent.ALT_MASK));
- newGame.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- refresh();
- }
- });
- gameMenu.addSeparator();
- ButtonGroup levelGroup = new ButtonGroup();
- JMenuItem easyLevel = new JRadioButtonMenuItem("初 级");
- levelGroup.add(easyLevel);
- gameMenu.add(easyLevel);
- easyLevel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
- easyLevel.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- setLevel(EASY_LEVEL);
- refresh();
- }
- });
- JMenuItem normalLevel = new JRadioButtonMenuItem("中 级");
- levelGroup.add(normalLevel);
- gameMenu.add(normalLevel);
- normalLevel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
- normalLevel.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- setLevel(NORMAL_LEVEL);
- refresh();
- }
- });
- JMenuItem hardLevel = new JRadioButtonMenuItem("高 级");
- levelGroup.add(hardLevel);
- gameMenu.add(hardLevel);
- hardLevel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.ALT_MASK));
- hardLevel.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- setLevel(HARD_LEVEL);
- refresh();
- }
- });
- normalLevel.setSelected(true);
- gameMenu.addSeparator();
- JMenuItem exitItem = new JMenuItem("退 出");
- gameMenu.add(exitItem);
- exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));
- exitItem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- System.exit(0);
- }
- });
- JMenu aboutMenu = new JMenu("关 于");
- menuBar.add(aboutMenu);
- JMenuItem aboutItem = new JMenuItem("About");
- aboutMenu.add(aboutItem);
- aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK));
- aboutItem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- JOptionPane.showMessageDialog(null, " By Eastsun", "About", JOptionPane.INFORMATION_MESSAGE);
- }
- });
- return menuBar;
- }
- private void fail(){
- timer.stopTimer();
- mid.setIcon(cryIcon);
- for(int h = 0; h < height; h++)
- for(int w = 0; w < width; w++){
- blocks[h][w].setOpen();
- if(blocks[h][w].isMine()) blocks[h][w].setIcon(mineIcon);
- }
- JOptionPane.showMessageDialog(null, " 你挂了!", "lost", JOptionPane.INFORMATION_MESSAGE);
- }
- private void win(){
- timer.stopTimer();
- mid.setIcon(laughIcon);
- JOptionPane.showMessageDialog(null, " 你赢了!", "win", JOptionPane.INFORMATION_MESSAGE);
- }
- private void generateGame(int x, int y){
- //生成一地图,并保证blocks[y][x]处无雷
- Random rand = new Random();
- int[] num = new int[width * height];
- for(int n = 0; n < height * width; n++) num[n] = n;
- for(int n = 0; n < mine; n++){
- int r = Math.abs(rand.nextInt());
- int p = r % (height * width - n) + n;
- blocks[num[p] / width][num[p] % width].setMine();
- num[p] = num[n];
- }
- while(blocks[y][x].isMine()){
- int r = Math.abs(rand.nextInt()) % (width * height);
- int h = r / width, w = r % width;
- if(!blocks[h][w].isMine()){
- blocks[h][w].setMine();
- blocks[y][x].clear();
- break;
- }
- }
- return;
- }
- private void setLevel(int l){ //设置
- switch(l){
- case EASY_LEVEL:
- height = 9;
- width = 9;
- mine = 10;
- level = EASY_LEVEL;
- break;
- case NORMAL_LEVEL:
- height = 12;
- width = 15;
- mine = 40;
- level = NORMAL_LEVEL;
- break;
- case HARD_LEVEL:
- height = 19;
- width = 29;
- mine = 100;
- level = HARD_LEVEL;
- break;
- }
- return;
- }
- private void refresh(){//刷新游戏,在setLevel或newGame之后执行
- if(blocks == null||blocks.length != height||blocks[0].length != width){
- //第一次游戏或游戏设置已经改变
- if(panel != null){
- this.getContentPane().remove(panel);
- this.getContentPane().remove(bar);
- }
- panel = new JPanel(new GridLayout(height, width, BUTTON_HGAP, BUTTON_VGAP));
- panel.setPreferredSize(new Dimension(width * (BUTTON_WIDTH + BUTTON_HGAP) - BUTTON_HGAP, height * (BUTTON_HEIGHT + BUTTON_VGAP) - BUTTON_VGAP));
- blocks = new Block[height][width];
- for(int h = 0; h < height; h++)
- for(int w = 0; w < width; w++){
- blocks[h][w] = new Block(w, h);
- panel.add(blocks[h][w]);
- }
- panel.setBorder(BorderFactory.createEmptyBorder(0, 6, 6, 6));
- bar = new JPanel(new GridLayout(1, 3));
- bar.setPreferredSize(new Dimension(width * (BUTTON_WIDTH + BUTTON_HGAP) - BUTTON_HGAP, 30));
- bar.setBorder(BorderFactory.createEmptyBorder(6, 6, 0, 6));
- bar.add(left, BorderLayout.WEST);
- bar.add(mid, BorderLayout.CENTER);
- bar.add(right, BorderLayout.EAST);
- this.getContentPane().setPreferredSize(new Dimension(width * (BUTTON_WIDTH + BUTTON_HGAP) - BUTTON_HGAP + 12, height * (BUTTON_HEIGHT + BUTTON_VGAP) - BUTTON_VGAP + 42));
- this.getContentPane().add(bar, BorderLayout.NORTH);
- this.getContentPane().add(panel, BorderLayout.SOUTH);
- this.pack();
- } else{
- for(int h = 0; h < height; h++)
- for(int w = 0; w < width; w++)
- blocks[h][w].clear();
- }
- left.setText(String.valueOf(mine));
- left.setHorizontalAlignment(JLabel.CENTER);
- mid.setIcon(smileIcon);
- mid.setHorizontalAlignment(JLabel.CENTER);
- right.setText("000");
- right.setHorizontalAlignment(JLabel.CENTER);
- timer.stopTimer();
- flags = false;
- mark = 0;
- remainder = mine;
- }
- class Block extends JButton implements MouseListener{
- private int x, y, status;
- public void mouseClicked(MouseEvent e){
- if(isOpen()) return;
- if(!flags){
- generateGame(x, y);
- timer.startTimer();
- flags = true;
- }
- if(SwingUtilities.isLeftMouseButton(e)){
- if((status&STATUS_F) != 0) return;
- if(isMine()){
- fail();
- //refresh();
- } else open();
- } else{//right
- if(isFlag()){
- this.setBackground(Color.ORANGE);
- status = (status^STATUS_F);
- mark --;
- remainder ++;
- } else{
- this.setBackground(Color.RED);
- status = (status|STATUS_F);
- mark ++;
- remainder --;
- }
- left.setText(String.valueOf(remainder));
- }
- if(mark == height * width) win();
- }
- public void mousePressed(MouseEvent e){
- }
- public void mouseEntered(MouseEvent e){
- }
- public void mouseExited(MouseEvent e){
- }
- public void mouseReleased(MouseEvent e){
- }
- public Block(int x, int y){
- this.x = x;
- this.y = y;
- this.status = 0;
- this.addMouseListener(this);
- this.setBackground(Color.ORANGE);
- }
- public boolean isMine(){
- return ((status&STATUS_M) != 0);
- }
- public int getNum(){
- int count = 0;
- if(x > 0){
- if(y > 0&&blocks[y - 1][x - 1].isMine()) count++;
- if(blocks[y][x - 1].isMine()) count++;
- if(y + 1 < height&&blocks[y + 1][x - 1].isMine()) count++;
- }
- if(y > 0&&blocks[y - 1][x].isMine()) count++;
- if(y + 1 < height&&blocks[y + 1][x].isMine()) count++;
- if(x + 1 < width){
- if(y > 0&&blocks[y - 1][x + 1].isMine()) count++;
- if(blocks[y][x + 1].isMine()) count++;
- if(y + 1 < height&&blocks[y + 1][x + 1].isMine()) count++;
- }
- return count;
- }
- public void clear(){
- status = 0;
- this.setIcon(null);
- this.setBackground(Color.ORANGE);
- }
- public void setMine(){
- status = STATUS_M;
- }
- public boolean isFlag(){
- return ((status&STATUS_F) != 0);
- }
- public void setOpen(){ //设置为打开状态
- status = (status|STATUS_O);
- setIcon(numIcon[getNum()]);
- }
- public boolean isOpen(){
- return ((status&STATUS_O) != 0);
- }
- private void open(){
- if(isOpen()||isFlag()) return;
- setOpen();
- mark ++;
- if(getNum() == 0){
- if(x > 0){
- blocks[y][x - 1].open();
- if(y > 0) blocks[y - 1][x - 1].open();
- if(y + 1 < height) blocks[y + 1][x - 1].open();
- }
- if(y > 0) blocks[y - 1][x].open();
- if(y + 1 < height) blocks[y + 1][x].open();
- if(x + 1 < width){
- blocks[y][x + 1].open();
- if(y > 0) blocks[y - 1][x + 1].open();
- if(y + 1 < height) blocks[y + 1][x + 1].open();
- }
- }
- }
- }
- public static void main(String[] args){
- new Mine();
- }
- }
复制代码
附1:程序的源代码及资源
附2:可以直接点击运行的jar程序(需要装JAVA运行时环境)
|
|