以五子棋实例来提高程序模型思维的建设

来源:互联网 发布:杭州网络安防招聘 编辑:程序博客网 时间:2024/05/21 19:08

五子棋实例

 

五子棋实例的实现分为以下几个步骤:

1.    主类的创建,并new一个窗体的对象,然后调用其中showUI的方法。这样的做法可以优化主类的结构,主类代码如下:

publicclassFiveChessextends JFrame{

    publicstaticvoid main(String[]args)

   

    {

    MainFrame mf=new MainFrame();

    mf.showUI();

    }

}

2.  接下来自然是接着创建一个MainFrame类继承JFrame类用来构成五子棋的窗口界面。然后再其中添加以下面板组件以实现五子棋的界面。

界面的添加主要写于showUI的方法中,然后根据showUI的方法来在Mainrame中添加相应的方法。

showUI:

publicvoid showUI() {

 

       //对整个界面做初始化,大小,位置,默认关闭,标题等

    init();

    // 增加绘制界面

addLeftPanel();

addRightPanel();

       //添加背景音乐

// 设置可见

    setVisible(true);

}

 

showUI中调用的方法:

privatevoid addRightPanel() {

       //Graphics g=new Graphics();

       RightPanel rp= new RightPanel(this);

       add(rp, BorderLayout.EAST);

    }

 

    privatevoid addLeftPanel() {

       LeftPanel lp= new LeftPanel(this);

       add(lp, BorderLayout.CENTER);

    }

 

    privatevoid init() {

       setTitle("五子棋");

       setSize(630, 500);

       ImageIcon ii=new ImageIcon(getClass().getResource("/tu/1.png"));

        setIconImage(ii.getImage());

       setLocationRelativeTo(null);

       setDefaultCloseOperation(EXIT_ON_CLOSE);

       setResizable(false); 

}

3.  根据Mainframe中创建的对象来依次添加LeftPanel类和RightPanel类,然后分别实现每个类的方法

五子棋的棋盘自然画在LeftPanel面板中

LeftPanel类中分为以下几个方法:

(1)构造方法:用来设置边框以及添加mouseListener方法

public LeftPanel(MainFramemf)

    {

       this.mf=mf;

    setBorder(BorderFactory.createBevelBorder(1,Color.gray, Color.GRAY));

       mouseListener();

    }

2paint方法用来添加背景图片和调用画棋盘的QipanPaint方法和画棋子的QiziPaint方法

publicvoid paint(Graphicsg)

    { 

      

       super.paint(g);

       ImageIcon ii1=new ImageIcon(getClass().getResource("/tu/5.jpg"));

       g.drawImage(ii1.getImage(), 0, 0,500,500,null);

      

       QipanPaint(g);

       QiziPaint(g); 

}  

 

(3)鼠标监听的方法,用来获取鼠标点击的坐标,从而判断画出棋子的坐标

publicvoid mouseListener() {

       MouseAdapter adapter =new MouseAdapter(){

          

           publicvoid mouseMoved(MouseEvente)

           {

              intx=e.getX();

              inty=e.getY();

              System.out.println(x+","+y);

           }

           publicvoid mouseClicked(MouseEvente) {

          

              if(start)

              {

              intx=e.getX()-20;

              inty=e.getY()-20;

              //判断位置

              intxIndex =x%20>10?x/20+1:x/20;

              intyIndex =y%20>10?y/20+1:y/20;

              if(xIndex>21 ||yIndex>21)

              {

                  return;

              }

              if(allChess[xIndex][yIndex]==0)

              {

                 

                  papa();

              if(chessFlag)

              {

                  allChess[xIndex][yIndex]=1; 

              }

              else

              {

                  allChess[xIndex][yIndex] = 2;

              }

              Point point = new Point(xIndex,yIndex);

              allcs.add(point);

              chessFlag=!chessFlag;

             

              mf.repaint();

              if(CheckWin(xIndex,yIndex)==true)

              {

                  JOptionPane.showMessageDialog(mf,"赢了");

                  allChess =newint[21][21];

                  allcs.clear();

                  mf.repaint();

                  start =false;

              }

             

             

           }}}

       }; 

       this.addMouseListener(adapter);

       this.addMouseMotionListener(adapter);

}

 

4)画棋盘方法,就是画直线

privatevoid QipanPaint(Graphicsg) {

       //setBackground(Color.PINK);

       for(inti=1;i<23;i++)

       {

           g.drawLine(20*i, 20, 20*i, 440);

           g.drawLine( 20,20*i, 440, 20*i);

       }

}

(5)画棋子方法,根据鼠标监听的坐标来画填充颜色的园即为其中,此处我用的是两黑白棋子的图片,效果一样

privatevoid QiziPaint(Graphicsg) {

       for(inti=0;i<allChess.length;i++)

       {

           for(intj=0;j<allChess.length;j++)

           {

             

              intvalue=allChess[i][j];

              if(value==1)

              {

                  ImageIconii1=new ImageIcon(getClass().getResource("/tu/black.png"));

                  g.drawImage(ii1.getImage(),i*20+20-8,j*20+20-8,16,16,null);

              }

              if(value==2)

              {

                  ImageIconii4=new ImageIcon(getClass().getResource("/tu/white.png"));

                  g.drawImage(ii4.getImage(),i*20+20-8,j*20+20-8, 16,16,null);

 

              }

           }

       }  

    }

6)判断棋子输赢的方法,此方法的调用添加在mouseListener的方法中,当横向,纵向,正斜或者反斜出项大于等于5子的情况即为赢。算法如下:

protectedboolean CheckWin(intxIndex,intyIndex) {

       intxt=xIndex,yt=yIndex;

       intcount=1;

       int [][][]Check={

              {{-1,0},{1,0}},

              {{0,-1},{0,1}},

              {{1,1},{-1,-1}},

              {{1,-1},{-1,1}}  

       };

       for(inti=0;i<Check.length;i++)

       {

           count=1;

           int [][]Change=Check[i];

           for(intj=0;j<Change.length;j++)

           {

             

              while(true)

              {

                  xt=xt+Change[j][0];

                  yt=yt+Change[j][1];

                  if(xt>20||yt>20||xt<0||yt<0)

                  {

                     break;

                  }

                  if(allChess[xt][yt]==allChess[xIndex][yIndex])

                  {

                     count++;

                  }

                  else

                  {

                     break;

                  }

              }

              xt=xIndex;yt=yIndex;

             

           }

           if(count>=5)

           {

              returntrue;

             

           }  

       }

      

       returnfalse;

 

}

 

接下来是RightPanel类的实现:

RightPanel类中主要是添加几个功能按钮,并实现相应的监听,从而实现功能调用。

主要方法如下:

1)构造方法,实现边框结构,并调用anniuPaint添加按钮方法,和添加音乐的方法

public RightPanel(MainFramemf)

{

    setBackground(Color.PINK);

    this.mf=mf;

    setBorder(BorderFactory.createBevelBorder(0,Color.ORANGE, Color.GRAY));

    setPreferredSize(new Dimension(150,0));

    FlowLayout f1=new FlowLayout(FlowLayout.CENTER,50,50);

    setLayout(f1);

    anniuPaint();

    addmusic();   

}

(2)绘制背景图片,由于右边面板有按钮等组件所以用paintComponent来绘制背景,这样背景图片不会把按钮覆盖。

publicvoid paintComponent(Graphicsg)

    super.paintComponent(g);

    ImageIcon ii3=new ImageIcon(getClass().getResource("/tu/3.jpg"));

    g.drawImage(ii3.getImage(),0, 0,150,500,null);

}

(3)添加按钮的方法的实现,以及实现按钮的监听功能

privatevoid anniuPaint() {

    JButton jbt1=new JButton("开始");

    JButton jbt2=new JButton("退出");

    JButton jbt3=new JButton("悔棋");

    JButton jbt4=new JButton("音乐");

     jbt1.setForeground(Color.green);

     jbt2.setForeground(Color.green);

     jbt3.setForeground(Color.green);

     jbt4.setForeground(Color.green);

     jbt1.setBackground(Color.gray);

     jbt2.setBackground(Color.gray);

     jbt3.setBackground(Color.gray);

     jbt4.setBackground(Color.gray);

    add(jbt1);

    add(jbt2);add(jbt3);add(jbt4);

    jbt1.addActionListener(new ActionListener() {

      

       @Override

       publicvoid actionPerformed(ActionEvente) {

           //TODO Auto-generated method stub

           LeftPanel.start=true;

       }

    });

   

    jbt4.addActionListener(new ActionListener() {

       publicvoid actionPerformed(ActionEvente) {

           //TODO Auto-generated method stub

           if(music)

              {

                 AudioPlayer.player.stop(as);

                 music=false;

                 jbt4.setText("打开音乐");

              }

              else

              {

                 AudioPlayer.player.start(as);

                 music=true;

                 jbt4.setText("关闭音乐");

              }

             

             

       }

    });

   

    jbt2.addActionListener(new ActionListener() {

      

       @Override

       publicvoid actionPerformed(ActionEvente) {

           //TODO Auto-generated method stub

          

               System.exit(0);  

             

       }

    });

   

    jbt3.addActionListener(new ActionListener() {

      

       @Override

       publicvoid actionPerformed(ActionEvente) {

                Pointpoint =LeftPanel.allcs.get(LeftPanel.allcs.size()-1);

                LeftPanel.allChess[(int)point.getX()][(int)point.getY()]=0;

               LeftPanel.allcs.remove(LeftPanel.allcs.size()-1);

               mf.repaint();

               LeftPanel.chessFlag = !LeftPanel.chessFlag;

       }

    });

 

}

4)添加音乐的方法AudioStream类有时不能够调用,需要改变jre的调用路径,选用JDK下的jre文件。

此方法的调用在按钮监听中。

privatevoid addmusic() {

    //TODO Auto-generated method stub

    try {

       FileInputStreamfis=new FileInputStream("sound/back.wav");

        as=new AudioStream(fis);

        AudioPlayer.player.start(as);

      

      

    } catch (Exceptione) {

       //TODO Auto-generated catch block

       e.printStackTrace();

    }

}

 


最终的界面如下:

0 0
原创粉丝点击