⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hanoitower.java

📁 创建一个Applet小程序实现有名的汉诺塔小游戏
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
         else status = "You did it!  Now try again, making only " + minMoves + " moves." ;
      }
      return status ;
   }
   // manual move
   boolean moveDisc(int d,int p1,int p2) //$移动盘子规则
   {
      if ((p1>=0)&&(p2>=0)) //$必须两个柱上都有盘子
      {
         // to different peg which is empty or has larger disc
         if ( (p1!=p2)&&((pegTop[p2]<0)||(peg[pegTop[p2]][p2]>d))) //$不是同一个柱子并且目的
         {                                                         //$柱上无盘子或目的柱上的盘子
            setDisc(d,p2) ;                                        //$上小下大
            moveCount++ ;
            return true ;
         }
      }
      setDisc(d,p1) ;
      return false ;
   }
   // AutoSolve move
   void moveDisc(int p1,int p2)  //$自动时使用
   {
      setDisc(getTopDisc(p1),p2) ;
      moveCount++ ;
   }
}


final class BoardCanvas extends Canvas //$自定义类描述盘子外观
{
   static final int PEG_SPACE=75, DISC_HEIGHT=15 ; //$柱距75、盘高15
   static final Color COLOR_3=new Color(204,153,51);

   private Image bufferImage ;
   private Graphics buffer ; //$缓冲
   private HanoiTower main ;
   // constructor
   BoardCanvas(HanoiTower main)
   {
      this.main = main ;
   }
   void drawBoard(Board b,Image boardImage,int dragDisc,int dragX,int dragY)
   {                                 //$画盘子
      int width=0, disc=0 ;

      if (buffer==null)  //$利用缓冲技术
      {
         bufferImage = createImage(main.CANVAS_WIDTH,main.CANVAS_HEIGHT) ;
         buffer = bufferImage.getGraphics() ;
      }
      // draw board
      buffer.drawImage(boardImage,0,0,this) ;
      // draw discs
      for (int p=main.PEG1; p<=main.PEG3; p++) //$遍历存储结构画盘子
      {
         for (int d=0; d<=b.getPegTop(p); d++)
         {
            disc = b.getDisc(d,p) ;
            if (disc!=0) {
               width = b.getDiscWidth(disc) ;
               drawDisc( (((2*p)+1)*PEG_SPACE)-((int)(width/2)),
                  main.TABLE_TOP-((d+1)*DISC_HEIGHT),width ) ;
            }
         }
      }
      // draw dragged disc
      if (dragDisc!=0)
      {
         width = b.getDiscWidth(dragDisc) ;
         drawDisc(dragX-(int)(width/2),
                  dragY-(int)(DISC_HEIGHT*.75),width) ;
      }
      repaint() ;
   }
   // draw single disc 15 pixel height with primitives
   void drawDisc(int x,int y,int width)
   {
   	  buffer.setColor(COLOR_3) ;
   	  buffer.drawRect(x,y,width,14) ;
   }
   public void paint(Graphics g) { update(g) ; }
   public void update(Graphics g) { g.drawImage(bufferImage,0,0,this) ; }

   // mouse event handlers
   public boolean mouseDown(Event e,int x,int y) { main.selectDisc(x,y) ; return true ; }
   public boolean mouseDrag(Event e,int x,int y) { main.dragDisc(x,y) ; return true ; }
   public boolean mouseUp(Event e,int x,int y) { main.dropDisc(x,y) ; return true ; }
}

final class ControlPanelOne extends JPanel //$自定义类描述控制面板1
{
   static final int MAX_DELAY=1000 ;  //$最大时间一秒
   private JPanel discsPanel ;
   private JButton bDiscsMinus, bDiscsPlus, bReset, bSolve ;

   private JTextField tfDiscs ;       //$显示盘子数
   private Scrollbar sbSpeed ;
   private HanoiTower main ;
   private int discs=main.MIN_DISCS, delay=200 ;

// constructor
   ControlPanelOne(HanoiTower main)       //$JPanel初始化
   {
      this.main = main ;
      setLayout(new GridLayout(6,1,0,3)) ;//$布局6行3列
      setFont(main.textFont) ;
      // DISCS
      discsPanel = new JPanel() ;
      discsPanel.setLayout(new BorderLayout(2,0)) ;
      tfDiscs = new JTextField(3) ;           //$显示盘子数
      tfDiscs.setFont(main.monoFont) ;
      tfDiscs.setForeground(Color.black) ;
      tfDiscs.setBackground(Color.lightGray) ;
      tfDiscs.setEditable(false) ;
      setDiscs(discs) ;
      bDiscsMinus=new JButton("-");           //$"-"按钮
      bDiscsMinus.addActionListener(new ControlActionListener());
      discsPanel.add("West",bDiscsMinus) ;
      bDiscsMinus.setFont(main.monoFont) ;
      discsPanel.add("Center",tfDiscs) ;
      bDiscsPlus=new JButton("+");            //$"+"按钮
      bDiscsPlus.addActionListener(new ControlActionListener());
      discsPanel.add("East",bDiscsPlus) ;
      bDiscsPlus.setFont(main.monoFont) ;
      bReset=new JButton("RESET");            //$"RESET"按钮
      bReset.addActionListener(new ControlActionListener());
      bSolve=new JButton("AUTOSOLVE");        //$"AUTOSOLVE"按钮
      bSolve.addActionListener(new ControlActionListener());
      discsPanel.validate() ;                 //$布局生效
      // SPEED
      sbSpeed = new Scrollbar(Scrollbar.HORIZONTAL,
                             (MAX_DELAY-delay),0,0,(MAX_DELAY-9)) ;
      sbSpeed.setBackground(Color.lightGray) ;
      sbSpeed.setPageIncrement((int)(MAX_DELAY/10)) ;  //$箭头自增量
      sbSpeed.setLineIncrement((int)(MAX_DELAY/100)) ; //$滑块自增量

      // construct panel
      add(new JLabel("DISCS",JLabel.CENTER)) ;  //$加到控制面板1
      add(discsPanel) ;
      add(bReset) ;
      add(bSolve) ;
      add(new JLabel("SPEED",JLabel.CENTER)) ;
      add(sbSpeed) ;
      validate() ;      //$布局生效


   }
                                      //$设置按钮状态
   void setAutoSolveEnable(boolean b) { bSolve.enable(b) ; }
   void setDiscs(int i)               //$设置显示盘子数
   {
      String s = Integer.toString(i) ;
      if (s.length()==1) s = "  " + s ;
      else if (s.length()==2) s = " " + s ;
      tfDiscs.setText(s) ;
   }

   int getDiscs() { return discs ; }
   int getDelay() { return delay ; } //$得到延时时间

   // handle button clicks
   private class ControlActionListener implements ActionListener //$响应按钮事件
	{
		public void actionPerformed(ActionEvent e)
		{


			if (e.getActionCommand()=="AUTOSOLVE")
			{
               setAutoSolveEnable(false) ;
               main.startSolveThread() ;
            }
            else
            {
              if (e.getActionCommand()=="+"&&discs<main.MAX_DISCS)
                 setDiscs(++discs) ;
              else if (e.getActionCommand()=="-"&&discs>main.MIN_DISCS)
                 setDiscs(--discs) ;

              main.restartGame() ;
            }
		}
	}

   // handle scrollbar
   public boolean handleEvent(Event e) //$响应滑块事件
   {
      if (e.target instanceof Scrollbar)
      {
         delay = MAX_DELAY - sbSpeed.getValue() ;
         return true ;
      }
      else return super.handleEvent(e) ;
   }
}

final class ControlPanelTwo extends JPanel //$自定义类描述控制面板2
{

   private int temp;
   private JButton Stop,Pause,Continue,Step;
   private JCheckBox cbTimer ;
   private JTextField tfTimer ;
   private JRadioButton t1,t2;
   private ButtonGroup group;
   private JPanel rbPanel;
   private HanoiTower main ;
   public boolean isTimerOn=true;

   // constructor
   ControlPanelTwo(HanoiTower main) //$//$JPanel初始化
   {
   	  temp=-1;
      this.main = main ;
      setLayout(new GridLayout(7,1)) ; //$布局7行1列
      setFont(main.textFont) ;
      Stop=new JButton("stop");        //$"stop"按钮
      Stop.addActionListener(new ControlActionListener());
      Pause=new JButton("pause");      //$"pause"按钮
      Pause.addActionListener(new ControlActionListener());
      Continue=new JButton("cotinue"); //$"cotinue"按钮
      Continue.addActionListener(new ControlActionListener());
      Step=new JButton("step by step");//$"step by step"按钮
      Step.addActionListener(new ControlActionListener());
      t1=new JRadioButton("peg2");     //$单选按钮"peg2"
      t1.addActionListener(new ControlActionListener());

      t2=new JRadioButton("peg3");     //$单选按钮"peg3"
      t2.addActionListener(new ControlActionListener());

      group=new ButtonGroup();          //$单选按钮"peg2"、"peg3"组
      group.add(t1);
      group.add(t2);

      rbPanel=new JPanel();
      rbPanel.add(t1);
      rbPanel.add(t2);

      cbTimer = new JCheckBox("TIMER") ;//$"TIMER"复选框
      cbTimer.addActionListener(new ControlActionListener());
      cbTimer.setBackground(Color.gray) ;
      tfTimer = new JTextField(10) ;
      tfTimer.setFont(main.monoFont) ;
      tfTimer.setForeground(Color.white) ;
      tfTimer.setBackground(Color.darkGray) ;
      tfTimer.setEditable(false) ;

      add(Stop);     //$加到控制面板2
      add(Pause);
      add(Continue);
      add(Step);
      add(rbPanel);
      add(cbTimer) ;
      add(tfTimer) ;
      validate() ;  //$布局生效

      cbTimer.setSelected(true) ;//$选中状态
      t2.setSelected(true) ;     //$选中状态
    }
    private class ControlActionListener implements ActionListener //$响应按钮事件
	{
		public void actionPerformed(ActionEvent e)
		{
			if (e.getActionCommand()=="TIMER")
			   isTimerOn=!isTimerOn;
			else if (e.getActionCommand()=="stop")
			   main.stop();
			else if (e.getActionCommand()=="pause")
			   main.mysuspend();
			else if (e.getActionCommand()=="cotinue")
               main.myresume();
            else if (e.getActionCommand()=="step by step")
               main.step();
            else if (e.getActionCommand()=="peg2")
              {
		         temp=main.PEG2;
		         main.PEG2=main.PEG3;
		         main.PEG3=temp;
		      }
            else if (e.getActionCommand()=="peg3")
              {
		         temp=main.PEG2;
		         main.PEG2=main.PEG3;
		         main.PEG3=temp;
		      }
        }
	}

	public void setTimer(String s) { tfTimer.setText(s) ; }
	void setTimerEnable(boolean b) { cbTimer.enable(b) ; }

}

final class StatusPanel extends JPanel //$自定义类描述状态面板
{
   private JTextField tfStatus, tfMoveCount ;
   private HanoiTower main ;

   // constructor
   StatusPanel(HanoiTower main)  //$构造函数
   {
      this.main = main ;
      setFont(main.textFont) ;

      tfStatus = new JTextField("",50) ; //$信息文本域
      tfStatus.setForeground(Color.white) ;
      tfStatus.setBackground(Color.darkGray) ;
      tfStatus.setEditable(false) ;

      tfMoveCount = new JTextField(6) ;  //$次数文本域
      tfMoveCount.setFont(main.monoFont) ;
      tfMoveCount.setForeground(Color.white) ;
      tfMoveCount.setBackground(Color.darkGray) ;
      tfMoveCount.setEditable(false) ;

      add(tfStatus) ;                    //$加到状态面板
      add(tfMoveCount) ;
      add(new JLabel("MOVES")) ;
      validate() ;                       //$布局生效
   }
   void setMoveCount(int i)              //$设置显示移动次数
   {
      String s=Integer.toString(i) ;

      switch (s.length())                //$字符串中心对齐
      {
         case 1: s = "    " + s ; break ;
         case 2: s = "   " + s ; break ;
         case 3: s = "  " + s ; break ;
         case 4: s = " " + s ; break ;
      }
      tfMoveCount.setText(s) ;
   }
   void setStatus(String s) { tfStatus.setText(s) ; }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -