Java拼图游戏

      学习java编程不到两个月,断断续续的学习了一些java swing的基本知识

今天觉得工作上暂无重要的任务,花了几个小时时间写了个拼图游戏(主要是

想训练一下java事件处理)!甚是有成就感!收获不小!
   
     

/*
 * GridLayoutDemo.java requires no other files.
 */

import java.awt.*;
import javax.swing.*;
import java.net.URL;
import java.util.*;

import java.awt.event.MouseMotionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

import java.awt.MenuComponent;
import java.awt.Dialog;
import java.awt.event.*;
import java.util.Timer;

//import java.awt.PopupMenu;

import java.lang.Math;

//import java.awt.Insets;

public class Sandy {
     public final static boolean RIGHT_TO_LEFT = false;
     public final static boolean EASY_GAME=false;
     public final static boolean HARD_GAME=true;
   
     static boolean BEGIN_GAME=false;
     static boolean FINISHED_GAME=false;
    
     static boolean DIFICULTY_GAME=EASY_GAME;
    
     static int TIME_PRO=0;
     static Timer timer;
    
     static JFrame Frame;
    
     static CheckboxMenuItem a1;
     static CheckboxMenuItem a2;
   
     final static int NUM_IMAGES = 9;
     static Container  pane;
     static ImageIcon[] images;
     static int[] sort;
    
     static int x_ClickPos=-1;
     static int y_ClickPos=-1;
     static int x_ReleasePos=-1;
     static int y_ReleasePos=-1;
    
   //  static Insets insetsofpane;
     static int x_paneWidth=480;
     static int y_paneHeighth=360;
   
  
    public static void addComponentsToPane(Container pane1) {
       
       
         pane=new Container();
         pane=pane1;
        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(
                ComponentOrientation.RIGHT_TO_LEFT);
        }
         pane.setLayout(new GridLayout(0,3));
        
        
           InitSort(); 
                   
           addstaticTopanel();//pane,images, sort);     
          
         //   insetsofpane=new Insets(0,0,0,0);
         //   insetsofpane=pane.getInsets();
          //  x_paneWidth=insetsofpane.right-insetsofpane.left;
         //   y_paneHeighth=insetsofpane.bottom-insetsofpane.top;
  
          pane.addMouseMotionListener(
                 new MouseMotionListener()
                 {
                             public void mouseMoved(MouseEvent e)
                              {
                                //   System.out.println(e.getComponent().getClass().getName()+e.getX()+"  "+e.getY());
                           }
                           public void mouseDragged(MouseEvent e)
                           {
                                //  System.out.println(e.getComponent().getClass().getName());
                           }
                 }
              ); 
             
          pane.addMouseListener(
                 new MouseListener()
                 {
                       public void mousePressed(MouseEvent e)
                       {
                           //Dialog dlg=new Dialog(Frame,"win",true);
                        // dlg.setUndecorated(true);
                       //  dlg.setSize(100,100);
                       //    dlg.setVisible(true);
                       //    dlg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
                    }

                    public void mouseReleased(MouseEvent e)
                    {
     
                    }

                    public void mouseEntered(MouseEvent e)
                    {
 
                    }

                     public void mouseExited(MouseEvent e)
                     {
  
                     }

                     public void mouseClicked(MouseEvent e)
                     {
                           if(BEGIN_GAME==false)return; //if player have not began the game;
                          
                        pane.removeAll();
                       
                        if(x_ClickPos==-1)
                        {
                            x_ClickPos=e.getX()*3/x_paneWidth;
                            y_ClickPos=e.getY()*3/y_paneHeighth;
                            if(sort[y_ClickPos*3+x_ClickPos]==8)
                            {
                                x_ClickPos=-1;
                              y_ClickPos=-1;                       
                            }
                            System.out.println(1);//e.getComponent().getClass().getName()+x_paneWidth);
                        }
                        else if(DIFICULTY_GAME==EASY_GAME)
                        {
                            x_ReleasePos=e.getX()*3/x_paneWidth;
                            y_ReleasePos=e.getY()*3/y_paneHeighth;                  
                            if(sort[y_ReleasePos*3+x_ReleasePos]==8)
                            {
                                sort[y_ReleasePos*3+x_ReleasePos]=sort[y_ClickPos*3+x_ClickPos];
                                sort[y_ClickPos*3+x_ClickPos]=8;
                                x_ClickPos=-1;
                              y_ClickPos=-1; 
                              System.out.println(2);
                            }
                            else
                            {
                                x_ClickPos=e.getX()*3/x_paneWidth;
                              y_ClickPos=e.getY()*3/y_paneHeighth;                          
                              System.out.println(3);
                            }
                            System.out.println(4);
                        } 
                        else if(DIFICULTY_GAME==HARD_GAME)
                        {
                        //    Math ma=new Math();
                            x_ReleasePos=e.getX()*3/x_paneWidth;
                            y_ReleasePos=e.getY()*3/y_paneHeighth;
                            if(sort[y_ReleasePos*3+x_ReleasePos]==8&&(java.lang.Math.abs(x_ReleasePos-x_ClickPos)+java.lang.Math.abs(y_ReleasePos-y_ClickPos)==1))
                            {
                                sort[y_ReleasePos*3+x_ReleasePos]=sort[y_ClickPos*3+x_ClickPos];
                                sort[y_ClickPos*3+x_ClickPos]=8;
                                x_ClickPos=-1;
                              y_ClickPos=-1; 
                              System.out.println(5);
                            }
                            else if(sort[y_ReleasePos*3+x_ReleasePos]!=8)
                            {
                                x_ClickPos=e.getX()*3/x_paneWidth;
                              y_ClickPos=e.getY()*3/y_paneHeighth;                          
                              System.out.println(6);
                            }
                            System.out.println(7);
                                                                              
                        }  

                      
                        //judge if the game is finished!
                        int i;
                        for(i=0;i<8;i++)
                        {
                            if(sort[i]!=i)break;                           
                        }
                        if(i==8)
                        {
                            FINISHED_GAME=true;
                            BEGIN_GAME=false;
                            Frame.setTitle("Congratulations!FINISHED at "+TIME_PRO+" second!");
                            timer.cancel();
                            TIME_PRO=0;
                        }
                                                                 
                        //Reconstruct the Pane
                            addstaticTopanel();
                            pane.validate();
 
                     }
                                        
                 }
           );
    }
      
    /*  Add the picture to the panel */
   
    public static void addstaticTopanel()//Container pane,ImageIcon[] images,int[] sort)
    {
        for (int i = 0; i < NUM_IMAGES; i++) {
                     JLabel IconLabel = new JLabel();
                     if(sort[i]!=8||FINISHED_GAME==true)
                     {
                 images[i] = createImageIcon("/images/image" + (sort[i]+1) + ".jpg");
                 IconLabel.setIcon(images[i]);//i]);//sort[i]]);
                 }
                
                 IconLabel.setText(""); 
                 pane.add(IconLabel);//1[i]); 
 
        }//endl for
             
    }
     
   /* Initial the sort of the picture */
    public static void InitSort()
    {
         images = new ImageIcon[NUM_IMAGES];
        sort=new int[NUM_IMAGES];  
       
        if(BEGIN_GAME==false)
        {
                   for(int i=0;i<=8;i++)
                   {
                      sort[i]=i;                           
                   }
                   return;
        }
               
        for(int j=0;j<NUM_IMAGES;j++)
        {
             sort[j]=-1;
        }
        Calendar calend = new GregorianCalendar();
         Random rd=new Random(calend.get(Calendar.SECOND));
        for(int j=0;j<NUM_IMAGES;)
         {
          int n=rd.nextInt();          
            n=n%9;
          if(n<0)n=-n;   
             if(sort[n]==-1)sort[n]=j++;       
          }
         
        for(int j=0;j<NUM_IMAGES;j++)
        {
             String str=new String();
          str=""+sort[j];
            System.out.println(str);
        }
           
    }
   
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
         Frame = new JFrame("GridLayoutDemo");
        Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
        Frame.setResizable(false);
        //Set up the content pane.
        addComponentsToPane(Frame.getContentPane());
                   
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu("MENU");
  
   //Add begin menu!!!!!!!!!!!!!
        MenuItem menuFileExit = new MenuItem("begin new game");      
        menuFileExit.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                BEGIN_GAME=true;
                FINISHED_GAME=false;
               
                pane.removeAll();
              InitSort();              
            addstaticTopanel();//pane,images, sort);
            pane.validate();
            
              System.out.println("begin");
            Frame.setTitle("A Small Game!");
       
            if(TIME_PRO>0)
            {
                TIME_PRO=0;
                return;
            }       
       
        /* Set Timer for the game!*/     
               int delay = 1000;   // delay for 5 sec.
             int period = 1000;  // repeat every sec.
             timer = new Timer();
   
             timer.scheduleAtFixedRate(new TimerTask() {
                      public void run() {
                                  // Task here ...
                                  TIME_PRO++;
                                  Frame.setTitle("you have used "+TIME_PRO+" second already!");                                
                          }
                  }, delay, period);
             
          }
        }    
      );
        menuFile.add(menuFileExit);
 
  //Add Dif menu!!!!!!!!!!!!!!!!!
       Menu menuDif=new Menu("Difficulty!");         
         a1=new CheckboxMenuItem("Easy");
         a2=new CheckboxMenuItem("Hard");    
        menuDif.add(a1);
        menuDif.add(a2);
       
        a1.setState(true);
        a1.addItemListener(
        new ItemListener()
        {
            public void itemStateChanged(ItemEvent e)
            {
                a1.setState(true);
                a2.setState(false);
                DIFICULTY_GAME=EASY_GAME;
                System.out.println(DIFICULTY_GAME);
            }
           
        }
        );
        a2.addItemListener(
        new ItemListener()
        {
            public void itemStateChanged(ItemEvent e)
            {
                DIFICULTY_GAME=HARD_GAME;
                a1.setState(false);
                a2.setState(true);
                System.out.println(DIFICULTY_GAME);
            }
           
        }
        );
        menuFile.add(menuDif);
       
       
        menuBar.add(menuFile);
        Frame.setMenuBar(menuBar);
        
        Frame.setTitle("A Small Game!");
        //Display the window.
        Frame.pack();
        Frame.setVisible(true);
    }
   
    public static ImageIcon createImageIcon(String path) {
        java.net.URL imageURL = Sandy.class.getResource(path);

        if (imageURL == null) {
            System.err.println("Resource not found: "
                               + path);
            return null;
        } else {
            return new ImageIcon(imageURL);
        }
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值