做游戏?
类似的。看看应该有帮助。 觉得有用给分哦。
复制 成 3个文件。在文件家里 运行 
javac *.javajava SlidingPuzzleAWT 3 5
/*----------------------------------------------------------------
** SlidingPuzzle.java
** @author   Jia Yu
** @version  1.1 last update 04-10-2002
** PURPOSE:  the class could be used to represent the board for the SLIDING PUZZLE game
** Input:    the rol and col of a element
** Output:   the board of SLIDING PUZZLE game,state of completement,the number of movement
*/public class SlidingPuzzle
{
  // the array for hold the SlidingPuzzle
  private int[][] basisM;
  // the variable hold the total number of movment
  private int movement;  /*
  ** SlidingPuzzle
  ** @param          the size of the board, row, column
  ** Precondition    row and col not null
  ** Postcondition   the basisM has been initialized, the movement be set to 0
  */
  public SlidingPuzzle(int row,int col)
  {
    if (row >=1 && col >=1)
    {
      basisM = new int [row][col];
    }
    resetM();
  }// end SlidingPuzzle  /*
  ** resetM()        reset the puzzle
  ** Precondition    none
  ** Postcondition   the basisM has been filled with random numbers,
  **                 the movement be set to 0
  */
  public void resetM()
  {
    movement=0;
    randomM(basisM);
  }//end resetM  /*
  ** moveElement(int row,int col)
  ** @param          row and column of the element
  ** @return         a boolean value
  ** Precondition    row and col not null
  ** Postcondition   the basisM has been changed
  */
  public boolean moveElement(int row,int col)
  {    //String dir = new String();
    if ((row >=0 && row < basisM.length) &&(col>=0 && col<basisM[row].length))
    {
      if (col-1>=0)
      {
        if (basisM[row][col-1]==0)
        {
          basisM[row][col-1]=basisM[row][col];
          basisM[row][col]=0;
          movement++;
          return true;
          //dir="left";
        }
      }
      if (col+1<basisM[row].length)
      {
        if (basisM[row][col+1]==0)
        {
          basisM[row][col+1]=basisM[row][col];
          basisM[row][col]=0;
          movement++;
          return true;
          //dir="right";
        }
      }
      if (row-1>=0)
      {
        if (basisM[row-1][col]==0)
        {
          basisM[row-1][col]=basisM[row][col];
          basisM[row][col]=0;
          movement++;
          return true;
          //dir="up";
        }
      }
      if (row+1<basisM.length)
      {
        if (basisM[row+1][col]==0)
        {
          basisM[row+1][col]=basisM[row][col];
          basisM[row][col]=0;
          movement++;
          return true;
          //dir="down";
        }
      }
    }// end If
    return false;
  } // end moveElement  /*
  ** getNumOfMove()  return the movement
  ** @param          none
  ** @return         the movement moad so far
  ** Precondition    movement has to be initialized
  ** Postcondition   none
  */
  public int getNumOfMove()
  {
    return movement;
  }//end getNumOfMove  public int[][] getMatrix()
  {
    int[][] tempM = new int[basisM.length][basisM[0].length];
    tempM = basisM;
    return tempM;
  }//end getMatrix  /*
  ** completedM
  ** @param          none
  ** @return         a boolean value shows the state of completement
  ** Precondition    basisM has to be initialized
  ** Postcondition   none
  */
  public boolean completedM()
  {
    for(int i=0;i<basisM.length;i++)
    {
      for(int j=0;j<basisM[i].length;j++)
      {
        if (i==basisM.length-1 && j==basisM[basisM.length-1].length-1)
        {        }
        else {
          if (i*basisM[i].length+j+1 != basisM[i][j])
          {
            return false;
          }
        }
      }
    }
    return true;
  }// end completedM
  /*
  ** moveE
  ** @param          a 2 dimensional array
  ** @return         none
  ** Precondition    m has to be initialized
  ** Postcondition   the array m has been filled with random numbers
  */
  private void randomM (int[][] m)
  {
    int[] tempNum = new int[m.length*m[0].length];
    int lengthM = tempNum.length-1;
    int indexNum =0;
    for (int i=0; i <tempNum.length;i++)
    {
      tempNum[i]=i;
    }
    for (int i=0; i < m.length;i++)
    {
      for(int j=0; j < m[i].length;j++)
      {
        indexNum=getRumNum(0,lengthM);
        m[i][j]= tempNum[indexNum];
        tempNum[indexNum]=tempNum[lengthM];
        lengthM--;
      }
    }
  }// end randomM  /*
  ** getRumNum
  ** @param          min and max number of the range
  ** @return         a random number in the range
  ** Precondition    none
  ** Postcondition   none
  */
  private int getRumNum(int min, int max)
  {
    return (int)(min + Math.random() * max);
  }//end getRumNum
}//end class
//----------------------------------------------------------------

解决方案 »

  1.   

    /*----------------------------------------------------------------
    ** SlidingPuzzleAWT.java
    ** @author   Jia Yu
    ** @version  1.0 last update 19-08-2002
    ** PURPOSE:  the class presents the GUI for the SlidingPuzzle class 
    ** Input:    mouse click 
    ** Output:   the tiles and the movement
    */import java.awt.*;
    import java.awt.event.*;public class SlidingPuzzleAWT extends Frame
    {
      //the button for reseting the puzzle
      private Button restart = new Button("Restart game");
      // the the canvas for drew the tiles
      private SlidingPuzzleCanvas theCanvas;
      // the label shows the number of movement
      private Label theLabel = new Label("Movement: 0   ");
      // the label shows the state of the program
      private Label StateBar = new Label(" Click the tile to move it.");  /*
      ** SlidingPuzzleAWT(int row,int col)
      ** @param          row and column of the element
      ** Precondition    row and col not null
      ** Postcondition   layout all the objects, set them to default value,
      **                 add addMouseListener
      */
      public SlidingPuzzleAWT(int row,int col)
      {
        super();
        theCanvas = new SlidingPuzzleCanvas(row,col);
        StateBar.setBackground(new Color(166,166,166));
        this.setBackground(new Color(204,200,193));
          Panel thePanel = new Panel(new FlowLayout());
          thePanel.setLayout(new FlowLayout());
          thePanel.add(restart);
          thePanel.add(theLabel);
        this.setLayout(new BorderLayout(1,3));
          Panel PanelTop = new Panel(new FlowLayout());
          PanelTop.add(theCanvas);
        this.add(PanelTop,BorderLayout.NORTH);
        this.add(thePanel, BorderLayout.CENTER);
        this.add(StateBar, BorderLayout.SOUTH);    this.addWindowListener(new WindowAdapter()
        {
          public void windowClosing(WindowEvent w)
          {
            System.exit(0);
          } // method windowClosing
        });
        // the addMouseListener for restart
        restart.addMouseListener(new MouseAdapter()
        {
          public void mouseClicked(MouseEvent e)
          {
            restart_onClick(e);
          }
        });
        // the addMouseListener for theCanvas
        theCanvas.addMouseListener(new MouseAdapter()
        {
          public void mouseClicked(MouseEvent e)
          {
            theCanvas_onClick(e);
          }
        });    int w = Math.max(theCanvas.getWidth()+10,220);
        int h = theCanvas.getHeight()+95;
        this.setSize(w,h);
        this.setLocation(300,200);
        this.setTitle(" Sliding Puzzle");
        this.setResizable(false);
        
        this.setVisible(true);
      }//end SlidingPuzzleAWT  /*
      ** restart_onClick(MouseEvent e)
      ** @param          MouseEvent e
      ** Precondition    none
      ** Postcondition   reset the puzzle
      */
      private void restart_onClick(MouseEvent e)
      {
        theCanvas.reSet();
        theLabel.setText("Movement: 0");
        StateBar.setText(" Click the tile to move it.");
      }// end  restart_actionPerformed
      
      /*
      ** theCanvas_onClick(MouseEvent e)
      ** @param          MouseEvent e
      ** Precondition    none
      ** Postcondition   click the canvas to move the tile.
      */
      private void theCanvas_onClick(MouseEvent e)
      {
        if ( !theCanvas.moveElemant(e.getX(),e.getY()) )
        {
          StateBar.setText(" No, you can't move it.");
        }
        else
        {
          theLabel.setText("Movement: " + theCanvas.getMovement() + "");
          StateBar.setText(" Click the tile to move it.");
          if(theCanvas.completed())
          {
            theCanvas.setEnabled(false);
            StateBar.setText(" You have completed it! :)");
          }
        }
      }// end theCanvas_onClick
      
      /*
      ** main(String[] args) the program start here
      ** @param          String[] args
      ** Precondition    args.length not less 2
      ** Postcondition   click the canvas to move the tile.
      */
      public static void main(String[] args)
      {
        if (args.length >= 2)
        {
          try
          {
            int row = Integer.parseInt( args[0] );
            int col = Integer.parseInt( args[1] );
            if ( row < 2 )
            {
              row = 2;
            }
            if (col < 2)
            {
              col = 2;
            }
            SlidingPuzzleAWT me = new SlidingPuzzleAWT(row,col);
          }
          catch( NumberFormatException e)
          {
            System.out.println("The arguments have to be numbers!");
            System.out.println("Help: java SlidingPuzzleAWT ROW COLUMN");
          }
        }
        else
        {
          System.out.println("Help: java SlidingPuzzleAWT ROW COLUMN");
        }
      }// end main}// end class
    //--------------------------------------------------------------
      

  2.   


    /*--------------------------------------------------------------
    ** SlidingPuzzle.java
    ** @author   Jia Yu
    ** @version  1.0 last update 19-08-2002
    ** PURPOSE:  the class could be used to represent the board for the SLIDING PUZZLE game
    ** Input:    the rol and col of a element
    ** Output:   the board of SLIDING PUZZLE game,state of completement,the number of movement
    */import java.awt.*;public class SlidingPuzzleCanvas extends Canvas
    {
      // the object of SlidingPuzzle
      private SlidingPuzzle sp;
      // the size of a tile
      private final int TILE_SIZE = 32;
      // the x coordinate for the space
      private int spaceX;
      // the y coordinate for the space
      private int spaceY;  /*
      ** SlidingPuzzleCanvas(int row, int col) the constructor
      ** @param                                row and col
      ** Precondition                          row and coll not less than 2
      ** Postcondition                         set the size,color, initialize sp
      */
      public SlidingPuzzleCanvas(int row, int col)
      {
        super();
        sp = new SlidingPuzzle(row,col);
        this.setSize(col * TILE_SIZE,row * TILE_SIZE);
        this.setBackground(new Color(255,255,255));
        //this.setVisible(true);
      }// end SlidingPuzzleCanvas/*
    ** paint(Graphics g)  redraw the screen
    ** @display           the tiles
    ** Precondition       sp not null
    ** Postcondition      reprint the canvas
    */
      public void paint(Graphics g)
      {
        int x = 0,y = 0,e = 0;
        g.setPaintMode();    for (int i=0; i<sp.getMatrix().length;i++)
        {
          for (int j=0;j<sp.getMatrix()[i].length;j++)
          {
            e = sp.getMatrix()[i][j];
            x = j * TILE_SIZE;
            y = i * TILE_SIZE;
            if ( e != 0 )
            {
              g.setColor(new Color(102,102,102));
              g.drawString( e + "",x+TILE_SIZE/2-5,y+10+TILE_SIZE/2-5 );
            }
            else
            {
              spaceX = x;
              spaceY = y;
              g.setColor(new Color(93,144,195));
              g.fillRect(x,y,TILE_SIZE,TILE_SIZE);
            }
            g.setColor(new Color(204,200,193));
            g.drawRect(x,y,TILE_SIZE,TILE_SIZE);
          }
        }
      } // method paint  /*
      ** moveElemant     move the tile by the coordinates
      ** @param          x coordinate, y coordinate
      ** @return         return true if it's moved successful
      ** Precondition    x,y not null
      ** Postcondition   move the tile and reprint the area have to be printed
      */
      public boolean moveElemant(int x,int y)
      {
        int currRow = y / TILE_SIZE;
        int currCol = x / TILE_SIZE;
        if ( sp.moveElement(currRow,currCol) )
        {
          // get the AREA needs to be repainted
          int theX = Math.min( currCol * TILE_SIZE, spaceX );
          int theY = Math.min( currRow * TILE_SIZE, spaceY );
          int w = TILE_SIZE;
          int h = TILE_SIZE;
          if ( currCol * TILE_SIZE == spaceX )
          {
            h += TILE_SIZE;
          }
          if ( currRow * TILE_SIZE == spaceY )
          {
            w += TILE_SIZE;
          }
          //---------------------------------------------
          this.repaint(theX,theY,w,h);
          return true;
        }
        return false;
      }// end setMatrix  /*
      ** reSet()         restart the Puzzle
      ** Precondition    sp not null
      ** Postcondition   reset the puzzle and clear up
      */
      public void reSet()
      {
        sp.resetM();
        this.setEnabled(true);
        this.repaint();
      }  /*
      ** getMovement()   get the movement
      ** @return         a integer value of movement
      ** Precondition    sp not null
      ** Postcondition   noen
      */
      public int getMovement()
      {
        return sp.getNumOfMove();
      }  /*
      ** completed()     check the puzzle is completed or not
      ** @return         return true if it's completed.
      ** Precondition    sp not null
      ** Postcondition   noen
      */
      public boolean completed()
      {
        return sp.completedM();
      }// end completed}// end class
    //----------------------------------------------------------------
      

  3.   

    关键问题是:如何判断所点击的按钮是否与空白按钮相邻?解决方法如下:用一个2维数组来存储每次超做后,每个按钮的位置,如:
    int s[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}} 
    (0表示空白的按钮,1表示按钮1……)
    所对应棋盘的位置就是:
    1   2   3   4
    5   6   7   8
    9   10  11  12
    13  14  15  __得到元素0的在当前状态数组s中的下标i,j 则与它相领为元素为:
      当3>i>0,3>j>0 时 s[i][j-1],s[i][j+1],s[i-1][j],s[i+1][j]
      当i=0,3>j>0 时   s[i][j-1],s[i][j+1],s[i+1][j]
      当i=3,3>j>0 时   s[i][j-1],s[i][j+1],s[i-1][j]  
      当j=0,3>i>0 时   s[i][j+1],s[i-1][j],s[i+1][j]
      当j=3,3>i>0 时   s[i][j-1],s[i-1][j],s[i+1][j] 
      当i=0,j=0 时     s[i][j+1],s[i+1][j]
      当i=0,j=3 时     s[i][j-1],s[i+1][j]
      当i=3,j=0 时     s[i][j+1],s[i-1][j]
      当i=3,j=3 时     s[i][j-1],s[i-1][j] 得到所点击按钮的编号元素在当前状态数组中的下标m,n,判断是否与0元素相邻(判断方法如上)如果相领,就将这2个元素位置互换--》s[m][n]=0,s[i][j]=P (P表示当前点击的按钮所表示的数字)
    最后将0按钮和点击的P按钮上显示的文本互换--》but0.setText(Integer.toString(P));butP.setText(""); 以上提供了基本的算法思路,我想用代码实现起来就很简单了。(不知道,大家还有没有更简单的办法)                            
      

  4.   

    楼上各位不要把简单的事情想复杂了~~~~只要做个监听就OK了~~~ 把你那个空白的按键做个ID  以后只要监听你所点击的键是否与空白键的坐标向邻就可以了