Java做的五子棋

转自:http://www.cnblogs.com/pains/archive/2007/10/07/915966.html

两年前做的,程序在玩家胜利后会有一点问题,有些棋子还在原来的位置上,那时候没找出来是什么原因,现在也不想管它了,拿上来也许对有些朋友有用。不过要 事先说明的是:要在j2sdk1.4.0下才能编译通过,在更高的版本上就要修改下程序才行,这可不是我的错,是java的版本兼容有问题;最好用个工具 编译执行它,如:EditPlus(它虽然是个文本编辑工具,但可以编译执行源程序的,要在工具菜单参数选择里设置下,当然要有java的sdk了),如 果直接在dos下执行可能图片加载不上来。
与本博客中的用flash实现的五子棋的实现原理不同,这个要简单很多,这个10×10的,标准应该是15×15。
贴个图(比较丑,不过我想你关心的是程序实现原理。):

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;

public class wuziqi
{
   public static void main(String[] args)
   {
      SimpleFrame frame=new SimpleFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.show();
   }
}

class AboutFrame extends JFrame
{
    public AboutFrame()
    {
       setSize(400,300);
       setResizable(false);
       setTitle("关于");
       Toolkit tk=Toolkit.getDefaultToolkit();
       Image ff=tk.getImage("false.gif");
       setIconImage(ff);
       Dimension screenSize=tk.getScreenSize();
       setLocation((screenSize.width-400)/2,(screenSize.height-300)/2);
       FontPanel fpanel=new FontPanel();
       Container con=getContentPane();
       con.add(fpanel);
    }
}
class FontPanel extends JPanel
{
   public void paintComponent(Graphics g)
   {
      super.paintComponent(g);
      Font f=new Font("宋体",Font.BOLD,22);
      g.setFont(f);
      g.drawString("五子棋)",10,30);
      f=new Font("楷体_GB2312",Font.PLAIN,18);
      g.setFont(f);
      g.drawString("设计者:Rick carter",10,120);
      g.drawString("本程序仅供大家参考及学习,",10,225);
      g.drawString("未经本人允许请勿用于任何商业活动!",10,250);
   }
}

class SimpleFrame extends JFrame
{
   public SimpleFrame()
   {
     setSize(WIDTH,HEIGHT);
     setResizable(false);
     setTitle("五子棋(10*10)");
     Toolkit tk=Toolkit.getDefaultToolkit();
     Image img=tk.getImage("map.gif");
     setIconImage(img);
     Dimension screenSize=tk.getScreenSize();
     setLocation((screenSize.width-WIDTH)/2,(screenSize.height-HEIGHT)/2);

     final AboutFrame aboutFrame=new AboutFrame();

     ImagePanel panel=new ImagePanel();
     Container contentPane=getContentPane();
     contentPane.add(panel);

     JMenuBar menuBar=new JMenuBar();
     setJMenuBar(menuBar);

     JMenu gameMenu=new JMenu("游戏(G)");   //创建游戏菜单
     gameMenu.setMnemonic('G');

     //创建游戏子菜单及监听器
     JMenuItem replayItem=new JMenuItem("重玩",'R');
     replayItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,InputEvent.CTRL_MASK));
     replayItem.addActionListener(new AbstractAction("重玩")
                    {
                        public void actionPerformed(ActionEvent event)
                        {
                           ImagePanel.restart();
                        }
                    } );
     JMenuItem optionItem=new JMenuItem("选项",'O');
     optionItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
     optionItem.addActionListener(new AbstractAction("选项")
                    {
                        public void actionPerformed(ActionEvent event)
                        {
                           
                        }
                    } );


     JMenuItem exitItem=new JMenuItem("退出",'E');
     exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,InputEvent.CTRL_MASK));
     exitItem.addActionListener(new AbstractAction("退出")
                    {
                        public void actionPerformed(ActionEvent event)
                        {
                           System.exit(0);
                        }
                    } );
     gameMenu.add(replayItem);
     gameMenu.add(optionItem);
     gameMenu.addSeparator(); 
     gameMenu.add(exitItem);
     menuBar.add(gameMenu);

     JMenu helpMenu=new JMenu("帮助(H)");    //创建帮助菜单
     helpMenu.setMnemonic('H');
     //创建帮助子菜单及监听器     
     JMenuItem aboutItem=new JMenuItem("关于",'A');
     aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
     aboutItem.addActionListener(new AbstractAction("关于")
                     {
                         public void actionPerformed(ActionEvent event)
                         {
                             aboutFrame.show();
                         }
                     });
     helpMenu.add(aboutItem);
     menuBar.add(helpMenu);

   }
   public static final int WIDTH=560;
   public static final int HEIGHT=450;
}

final class ImagePanel extends JPanel
{
    public ImagePanel()
    {
       image=Toolkit.getDefaultToolkit().getImage("map.gif");
       green=Toolkit.getDefaultToolkit().getImage("green.gif");
       red=Toolkit.getDefaultToolkit().getImage("red.gif");
       position=Toolkit.getDefaultToolkit().getImage("position.gif");
       ired=Toolkit.getDefaultToolkit().getImage("ired.gif");
       MediaTracker tracker=new MediaTracker(this);
       tracker.addImage(image,1);         //棋盘
       tracker.addImage(green,2);         //绿棋子
       tracker.addImage(red,3);           //红棋子
       tracker.addImage(position,4);      //鼠标位置
       tracker.addImage(ired,5); 
       try
       {
           tracker.waitForID(1);
           tracker.waitForID(2);
           tracker.waitForID(3);
           tracker.waitForID(4);
           tracker.waitForID(5);
       }
       catch(InterruptedException exception) 
       {}

       //注册监听器
       addMouseListener(new MouseHandler());
       addMouseMotionListener(new MouseMotionHandler());

    for(i=0;i<10;i++)          //初始化棋盘状态
        for(j=0;j<10;j++)
            ball[i][j] = 0;
    for(i=0;i<10;i++)          //设定水平方向的获胜位置
        for(j=0;j<6;j++)
        {
            for(k=0;k<5;k++)
            {
                ptable[j+k][i][count] = true;
                ctable[j+k][i][count] = true;
            }
            count++;
        }
    for(i=0;i<10;i++)          //设定垂直方向的获胜位置
        for(j=0;j<6;j++)
        {
            for(k=0;k<5;k++)
            {
                ptable[i][j+k][count] = true;
                ctable[i][j+k][count] = true;
            }
            count++;
        }
    for(i=0;i<6;i++)           //设定正对角线方向的获胜位置
        for(j=0;j<6;j++)
        {
            for(k=0;k<5;k++)
            {
                ptable[j+k][i+k][count] = true;
                ctable[j+k][i+k][count] = true;
            }
            count++;
        }
    for(i=0;i<6;i++)           //设定反对角线方向的获胜位置
        for(j=9;j>=4;j--)
        {
            for(k=0;k<5;k++)
            {
                ptable[j-k][i+k][count] = true;
                ctable[j-k][i+k][count] = true;
            }
            count++;
        }
    computer = false;
    player = true;
    }

    //绘制窗体面板
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        int FrameWidth=getWidth();
        int FrameHeight=getHeight();
        int x=(FrameWidth-400)/2;
        int y=FrameHeight-400;
        int px=mousex-(mousex-x)%40;
        int py=mousey-(mousey-y)%40;
        if(px<x)
           px=x;
        if(py<y)
           py=y;
        if(px>(x+360))
           px=x+360;
        if(py>(y+360))
          py=y+360;
        g.drawImage(image,x,y,null);
        g.drawImage(position,px,py,null);
        Font f=new Font("楷体_GB2312",Font.BOLD,20);
        g.setFont(f);
        g.setColor(new Color(204,66,204));
        g.drawString("计算机",5,60);
        g.setColor(new Color(00,99,00));
        g.drawString("玩家",495,60);
        g.drawImage(red,20,75,null);
        g.drawImage(green,500,75,null);
        g.setColor(Color.black);
        switch(str)
        {
          case 0:
               g.drawString("你先下!",480,140);
               break;
          case 1:
               g.drawString("等待!",480,140);
               break;
          case 2:
               g.drawString("该你了.",480,140);
               break;
          case 3:
               g.drawString("你嬴了!",480,140);
               break;
          case 4:
               g.drawString("你输了!",480,140);
               break;
          case 5:
               g.drawString("平 局!",480,140);
               break;
        }
        for(i=0;i<10;i++)
           for(j=0;j<10;j++)
           {
              if(ball[i][j]==1)
              { 
                   px=i*40+3+x;
                   py=j*40+3+y;
                   g.drawImage(green,px,py,null);
              }
              if(ball[i][j]==2)
              {
                   px=i*40+3+x;
                   py=j*40+3+y;
                   g.drawImage(red,px,py,null);
              }
           }
        g.drawImage(ired,a*40+x+3,b*40+y+3,null);
     }

     //变量
     private Image image;
     private Image position;
     private Image green;
     private Image red;
     private Image ired;
     private int mousex,mousey;
     private JButton replayButton;

     private static int ball[][]=new int [10][10];
     private static boolean ptable[][][]=new boolean [10][10][192],ctable[][][]=new boolean [10][10][192];
     private static int pgrades[][]=new int [10][10],cgrades[][]=new int [10][10],cgrade,pgrade;
     private static int win[][]=new int [2][192];
     private static int pcount,ccount;   //记录计算机与玩家各下了多少棋子
     private static boolean player,computer,start=true,over=false,pwin,cwin,tie;
     private static int i,j,k,n,m,count,a=50,b=50;
     private static int mat,nat,mde,nde;
     private static int str=0;

     private class replayAction implements ActionListener
     {
        public void actionPerformed(ActionEvent event)
        {
            restart();
        }
     }

     //鼠标移动事件
     private class MouseMotionHandler implements MouseMotionListener
     {
        public void mouseMoved(MouseEvent event)
        {
           mousex=event.getX();
           mousey=event.getY();
           repaint();
        }
        public void mouseDragged(MouseEvent event) {}
     }

     //鼠标点击事件
     private class MouseHandler extends MouseAdapter
     {
         public void mousePressed(MouseEvent event)
         {
             mousex=event.getX();
             mousey=event.getY();

             if(!over)
                 if(player)
                 {
                     int FrameWidth=getWidth();
                     int FrameHeight=getHeight();
                     int x=(FrameWidth-400)/2;
                     int y=FrameHeight-400-5;
                     if(mousex>x&&mousex<(x+400)&&mousey>y&&mousey<(y+400))
                     {   m=(int)((mousex-x)/40);
                         n=(int)((mousey-y)/40);
                         while(ball[m][n]==0)  //如果该棋子为空
                         {  ball[m][n]=1;   //设为玩家的棋子
                            pcount++;
                            str=1;
                            if((ccount==50)&&(pcount==50))
                            {   tie=true;
                                over=true;
                                str=5;
                            }
                            for(i=0;i<192;i++)
                            {
                               if(ptable[m][n][i]&&win[0][i]!=7)
                                   win[0][i]++;
                               if(ctable[m][n][i])
                               {
                                  ctable[m][n][i]=false;
                                  win[1][i]=7;   //计算机在第i种获胜可能中不可能再获胜,就置为7
                               }
                            }
                        if(!over)
                        {
                       for(i=0;i<=1;i++)
                      for(j=0;j<192;j++)
                      {
                     if(win[i][j] == 5)
                    if(i==0)           //玩家获胜
                    {
                       pwin=true;
                                           cwin=false;
                       over=true;
                                           str=3;
                       break;
                    }
                    else               //计算机获胜
                    {
                       cwin=true;
                                           pwin=false;
                       over=true;
                                           str=4;
                           break;
                    }
                     if(over)
                    break;
                      }
                        }

                            player=false;
                            computer=true;
                            repaint();
                            if(over)
                            {
                              if(tie)
                                    JOptionPane.showConfirmDialog(
                                         ImagePanel.this,
                                         "平局!","确认信息",
                                         JOptionPane.DEFAULT_OPTION,
                                         JOptionPane.INFORMATION_MESSAGE);
                              else
                                 if(pwin)
                                    JOptionPane.showConfirmDialog(
                                         ImagePanel.this,
                                         "恭喜你!你嬴了。","确认信息",
                                         JOptionPane.DEFAULT_OPTION,
                                         JOptionPane.INFORMATION_MESSAGE);
                                 else
                                    if(cwin)
                                      JOptionPane.showConfirmDialog(
                                         ImagePanel.this,
                                         "你输了!","确认信息",
                                         JOptionPane.DEFAULT_OPTION,
                                         JOptionPane.INFORMATION_MESSAGE);
                              restart();
                            
                            }
                         }
                     }
                 }
             //电脑下
             computerdo();
        }
    }

    public void computerdo()
    {
      if(!over)
         if(computer)
         {
           for(i=0;i<=9;i++)        //计算玩家在空格子上的获胜分数
          for(j=0;j<=9;j++)
          {
        pgrades[i][j]=0;
        if(ball[i][j]==0)
          for(k=0;k<192;k++)
             if(ptable[i][j][k])
             {
            switch(win[0][k])
            {
            case 1:
                    pgrades[i][j]+=5;
                break;
            case 2:
                pgrades[i][j]+=50;
                break;
            case 3:
                pgrades[i][j]+=100;
                break;
            case 4:
                pgrades[i][j]+=400;
                break;
            }
            }
         }
           for(i=0;i<=9;i++)        //计算计算机在空格子上的获胜分数
         for(j=0;j<=9;j++)
         {
        cgrades[i][j]=0;
        if(ball[i][j]==0)
            for(k=0;k<192;k++)
            if(ctable[i][j][k])
            {
               switch(win[1][k])
               {
                 case 1:
                cgrades[i][j]+=5;
                break;
                 case 2:
                cgrades[i][j]+=50;
                break;
                 case 3:
                cgrades[i][j]+=100;
                break;
                 case 4:
                cgrades[i][j]+=400;
                break;
               }
            }
          }
     if(start)              //游戏开始
     {
        if(ball[4][4]==0)
        {
            m = 4;
            n = 4;
        }
        else
        {
            m = 5;
            n = 5;
        }
        start = false;
     }
     else
     {
        for(i=0;i<10;i++)
           for(j=0;j<10;j++)
          if(ball[i][j]==0)
          {
             if(cgrades[i][j]>=cgrade)
             {
            cgrade = cgrades[i][j];   
            mat = i;
            nat = j;
             }
             if(pgrades[i][j]>=pgrade)
             {
            pgrade = pgrades[i][j];   
            mde = i;
            nde = j;
             }
          }
        if(pgrade>=cgrade&&pgrade>100)     //防守
        {
        m = mde;
        n = nde;
        }
        else                   //攻击
        {
        m = mat;
        n = nat;
        }
     }
     cgrade = 0;        
     pgrade = 0;
     ball[m][n] = 2;      //设定为计算机的棋子
         a=m;
         b=n;
     ccount++;
         str=2;
     if((ccount==50)&&(pcount==50))
     {
         tie = true;
         over = true;
     }
     for(i=0;i<192;i++)
     {
         if(ctable[m][n][i] && win[1][i] != 7)
        win[1][i]++;
         if(ptable[m][n][i])
         {
         ptable[m][n][i] = false;
           win[0][i]=7;
         }
     }
         if(!over)
         {
            for(i=0;i<=1;i++)
        for(j=0;j<192;j++)
        {
            if(win[i][j]==5)
            if(i==0)           //玩家获胜
            {
               pwin=true;
                           cwin=false;
               over=true;
                           str=3;
               break;
            }
            else               //计算机获胜
            {
               cwin=true;
                           pwin=false;
               over=true;
                           str=4;
               break;
            }
            if(over)
            break;
        }
     }
     player=true;        //换玩家下
     computer=false;
         repaint();
         if(over)
         {
            if(tie)
              JOptionPane.showConfirmDialog(
                     ImagePanel.this,
                     "平局!","确认信息",
                     JOptionPane.DEFAULT_OPTION,
                     JOptionPane.INFORMATION_MESSAGE);
            else
                if(pwin)
                  JOptionPane.showConfirmDialog(
                       ImagePanel.this,
                       "恭喜你!你嬴了。","确认信息",
                       JOptionPane.DEFAULT_OPTION,
                       JOptionPane.INFORMATION_MESSAGE);
                else
                    if(cwin)
                       JOptionPane.showConfirmDialog(
                            ImagePanel.this,
                            "你输了!","确认信息",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.INFORMATION_MESSAGE);
           restart();
                            
        }
     }
   }

   public static void restart()
   {
    for(i=0;i<10;i++)
        for(j=0;j<10;j++)
        {
        pgrades[i][j]=0;
        cgrades[i][j]=0;
        ball[i][j]=0;
        }
        count=0;
    for(i=0;i<10;i++)          //设定水平方向的获胜位置
        for(j=0;j<6;j++)
        {
            for(k=0;k<5;k++)
            {
                ptable[j+k][i][count] = true;
                ctable[j+k][i][count] = true;
            }
            count++;
        }
    for(i=0;i<10;i++)          //设定垂直方向的获胜位置
        for(j=0;j<6;j++)
        {
            for(k=0;k<5;k++)
            {
                ptable[i][j+k][count] = true;
                ctable[i][j+k][count] = true;
            }
            count++;
        }
    for(i=0;i<6;i++)           //设定正对角线方向的获胜位置
        for(j=0;j<6;j++)
        {
            for(k=0;k<5;k++)
            {
                ptable[j+k][i+k][count] = true;
                ctable[j+k][i+k][count] = true;
            }
            count++;
        }
    for(i=0;i<6;i++)           //设定反对角线方向的获胜位置
        for(j=9;j>=4;j--)
        {
            for(k=0;k<5;k++)
            {
                ptable[j-k][i+k][count] = true;
                ctable[j-k][i+k][count] = true;
            }
            count++;
        }
    for(i=0;i<=1;i++)
        for(j=0;j<192;j++)
        win[i][j]=0;
    computer=false;
    player=true;
        str=0;
    count=0;
    ccount=0;
    pcount=0;
    start=true;
    over=false;
    pwin=false;
    cwin=false;
    tie=false;
        a=b=50;
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值