五子棋游戏源代码
知识共享-五子棋java实现源代码(雷惊风)
经典的五子棋java程序(源带码)直接复制粘贴importjava.awt.*;importjava.awt.event.*;importjava.applet.Applet;importjava.awt.Color;publicclassenzitextends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener{intcolor_Qizi=0;//旗子的颜色标识0:白子1:黑子intintGame_Start=0;//游戏开始标志0未开始1游戏中intintGame_Body[][]=newint[16][16]; //设置棋盘棋子状态0 无子1 白子2 黑子Button b1=new Button("游戏开始");Button b2=new Button("重置游戏");Label lblWin=new Label(" ");Checkbox ckbHB[]=new Checkbox[2];CheckboxGroupckgHB=new CheckboxGroup();publicvoidinit(){setLayout(null);addMouseListener(this);add(b1);b1.setBounds(330,50,80,30);b1.addActionListener(this);add(b2);b2.setBounds(330,90,80,30);b2.addActionListener(this);ckbHB[0]=new Checkbox("白子先",ckgHB,false);ckbHB[0].setBounds(320,20,60,30);ckbHB[1]=new Checkbox("黑子先",ckgHB,false);ckbHB[1].setBounds(380,20,60,30);add(ckbHB[0]);add(ckbHB[1]);ckbHB[0].addItemListener(this);ckbHB[1].addItemListener(this);add(lblWin);lblWin.setBounds(330,130,80,30);Game_start_csh();}publicvoiditemStateChanged(ItemEvent e){if (ckbHB[0].getState()) //选择黑子先还是白子先{color_Qizi=0;}else{color_Qizi=1;}}publicvoidactionPerformed(ActionEvent e){Graphics g=getGraphics();if (e.getSource()==b1){Game_start();}else{Game_re();}}publicvoidmousePressed(MouseEvent e){}publicvoidmouseClicked(MouseEvent e){Graphics g=getGraphics();int x1,y1;x1=e.getX();y1=e.getY();if (e.getX()<20 || e.getX()>300 || e.getY()<20 || e.getY()>300) {return;}if (x1%20>10){x1+=20;}if(y1%20>10){y1+=20;}x1=x1/20*20;y1=y1/20*20;set_Qizi(x1,y1);}publicvoidmouseEntered(MouseEvent e){}publicvoidmouseExited(MouseEvent e){}publicvoidmouseReleased(MouseEvent e){}publicvoidmouseDragged(MouseEvent e){}publicvoidmouseMoved(MouseEvent e){}publicvoid paint(Graphics g){draw_qipan(g);}publicvoid set_Qizi(intx,int y) //落子{if (intGame_Start==0) //判断游戏未开始{return;}if (intGame_Body[x/20][y/20]!=0){return;}Graphics g=getGraphics();if (color_Qizi==1)//判断黑子还是白子{g.setColor(Color.black);color_Qizi=0;}else{g.setColor(Color.white);color_Qizi=1;}g.fillOval(x-10,y-10,20,20);intGame_Body[x/20][y/20]=color_Qizi+1;if (Game_win_1(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}if (Game_win_2(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}if (Game_win_3(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}if (Game_win_4(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}}public String Get_qizi_color(int x){if (x==0){return"黑子";}else{return"白子";}}publicvoid draw_qipan(Graphics G) //画棋盘15*15{G.setColor(Color.lightGray);G.fill3DRect(10,10,300,300,true);G.setColor(Color.black);for(inti=1;i<16;i++){G.drawLine(20,20*i,300,20*i);G.drawLine(20*i,20,20*i,300);}}publicvoid Game_start() //游戏开始{intGame_Start=1;Game_btn_enable(false);b2.setEnabled(true);}publicvoid Game_start_csh() //游戏开始初始化{intGame_Start=0;Game_btn_enable(true);b2.setEnabled(false);ckbHB[0].setState(true);for (inti=0;i<16 ;i++ ){for (int j=0;j<16 ;j++ ){intGame_Body[j]=0;}}lblWin.setText("");}publicvoid Game_re() //游戏重新开始{repaint();Game_start_csh();}publicvoid Game_btn_enable(boolean e) //设置组件状态{b1.setEnabled(e);b2.setEnabled(e);ckbHB[0].setEnabled(e);ckbHB[1].setEnabled(e);}publicboolean Game_win_1(intx,int y) //判断输赢横{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1]==intGame_Body[x][y]) {t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1-i][y1]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_2(intx,int y) //判断输赢竖{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1][y1+i]==intGame_Body[x][y]){t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_3(intx,int y) //判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1-i][y1+i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_4(intx,int y) //判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1+i]==intGame_Body[x][y]) {t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1-i][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}}。
Java五子棋游戏源代码(人机对战)
//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。
**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。
五子棋游戏源代码
import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class clientThread extends Thread {chessClient chessclient;clientThread(chessClient chessclient) {this.chessclient = chessclient;}public void acceptMessage(String recMessage) {if (recMessage.startsWith("/userlist ")) {StringTokenizer userToken = new StringTokenizer(recMessage, " ");int userNumber = 0;erList.removeAll();erChoice.removeAll();erChoice.addItem("所有人");while (userToken.hasMoreTokens()) {String user = (String) userToken.nextToken(" ");if (userNumber > 0 && !user.startsWith("[inchess]")) {erList.add(user);erChoice.addItem(user);}userNumber++;}erChoice.select("所有人");} else if (recMessage.startsWith("/yourname ")) {chessclient.chessClientName = recMessage.substring(10);chessclient.setTitle("Java五子棋客户端" + "用户名:"+ chessclient.chessClientName);} else if (recMessage.equals("/reject")) {try {chessclient.chesspad.statusText.setText("不能加入游戏");chessclient.controlpad.cancelGameButton.setEnabled(false);chessclient.controlpad.joinGameButton.setEnabled(true);chessclient.controlpad.creatGameButton.setEnabled(true);} catch (Exception ef) {chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");}chessclient.controlpad.joinGameButton.setEnabled(true);} else if (recMessage.startsWith("/peer ")) {chessclient.chesspad.chessPeerName = recMessage.substring(6);if (chessclient.isServer) {chessclient.chesspad.chessColor = 1;chessclient.chesspad.isMouseEnabled = true;chessclient.chesspad.statusText.setText("请黑棋下子");} else if (chessclient.isClient) {chessclient.chesspad.chessColor = -1;chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");}} else if (recMessage.equals("/youwin")) {chessclient.isOnChess = false;chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");chessclient.chesspad.isMouseEnabled = false;} else if (recMessage.equals("/OK")) {chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");} else if (recMessage.equals("/error")) {chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入\n");} else {chessclient.chatpad.chatLineArea.append(recMessage + "\n");chessclient.chatpad.chatLineArea.setCaretPosition(chessclient.chatpad.chatLineArea.getText().length());}}public void run() {String message = "";try {while (true) {message = chessclient.in.readUTF();acceptMessage(message);}} catch (IOException es) {}}}public class chessClient extends Frame implements ActionListener, KeyListener { userPad userpad = new userPad();chatPad chatpad = new chatPad();controlPad controlpad = new controlPad();chessPad chesspad = new chessPad();inputPad inputpad = new inputPad();Socket chatSocket;DataInputStream in;DataOutputStream out;String chessClientName = null;String host = null;int port = 4331;boolean isOnChat = false; // 在聊天?boolean isOnChess = false; // 在下棋?boolean isGameConnected = false; // 下棋的客户端连接?boolean isServer = false; // 如果是下棋的主机boolean isClient = false; // 如果是下棋的客户端Panel southPanel = new Panel();Panel northPanel = new Panel();Panel centerPanel = new Panel();Panel westPanel = new Panel();Panel eastPanel = new Panel();chessClient() {super("Java五子棋客户端");setLayout(new BorderLayout());host = controlpad.inputIP.getText();westPanel.setLayout(new BorderLayout());westPanel.add(userpad, BorderLayout.NORTH);westPanel.add(chatpad, BorderLayout.CENTER);westPanel.setBackground(Color.pink);inputpad.inputWords.addKeyListener(this);chesspad.host = controlpad.inputIP.getText();centerPanel.add(chesspad, BorderLayout.CENTER);centerPanel.add(inputpad, BorderLayout.SOUTH);centerPanel.setBackground(Color.pink);controlpad.connectButton.addActionListener(this);controlpad.creatGameButton.addActionListener(this);controlpad.joinGameButton.addActionListener(this);controlpad.cancelGameButton.addActionListener(this);controlpad.exitGameButton.addActionListener(this);controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(false);southPanel.add(controlpad, BorderLayout.CENTER);southPanel.setBackground(Color.pink);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {if (isOnChat) {try {chatSocket.close();} catch (Exception ed) {}}if (isOnChess || isGameConnected) {try {chesspad.chessSocket.close();} catch (Exception ee) {}}System.exit(0);}public void windowActivated(WindowEvent ea) {}});add(westPanel, BorderLayout.WEST);add(centerPanel, BorderLayout.CENTER);add(southPanel, BorderLayout.SOUTH);pack();setSize(670, 548);setVisible(true);setResizable(false);validate();}public boolean connectServer(String serverIP, int serverPort)throws Exception {try {chatSocket = new Socket(serverIP, serverPort);in = new DataInputStream(chatSocket.getInputStream());out = new DataOutputStream(chatSocket.getOutputStream());clientThread clientthread = new clientThread(this);clientthread.start();isOnChat = true;return true;} catch (IOException ex) {chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序\n");}return false;}public void actionPerformed(ActionEvent e) {if (e.getSource() == controlpad.connectButton) {host = chesspad.host = controlpad.inputIP.getText();try {if (connectServer(host, port)) {chatpad.chatLineArea.setText("");controlpad.connectButton.setEnabled(false);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");}} catch (Exception ei) {chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序\n");}}if (e.getSource() == controlpad.exitGameButton) {if (isOnChat) {try {chatSocket.close();} catch (Exception ed) {}}if (isOnChess || isGameConnected) {try {chesspad.chessSocket.close();} catch (Exception ee) {}}System.exit(0);}if (e.getSource() == controlpad.joinGameButton) {String selectedUser = erList.getSelectedItem();if (selectedUser == null || selectedUser.startsWith("[inchess]")|| selectedUser.equals(chessClientName)) {chesspad.statusText.setText("必须先选定一个有效用户");} else {try {if (!isGameConnected) {if (chesspad.connectServer(chesspad.host, chesspad.port)) {isGameConnected = true;isOnChess = true;isClient = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+ erList.getSelectedItem() + " "+ chessClientName);}} else {isOnChess = true;isClient = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+ erList.getSelectedItem() + " "+ chessClientName);}} catch (Exception ee) {isGameConnected = false;isOnChess = false;isClient = false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chatpad.chatLineArea.setText("chesspad.connectServer无法连接\n" + ee);}}}if (e.getSource() == controlpad.creatGameButton) {try {if (!isGameConnected) {if (chesspad.connectServer(chesspad.host, chesspad.port)) {isGameConnected = true;isOnChess = true;isServer = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+ "[inchess]" + chessClientName);}} else {isOnChess = true;isServer = true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+ "[inchess]" + chessClientName);}} catch (Exception ec) {isGameConnected = false;isOnChess = false;isServer = false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);ec.printStackTrace();chatpad.chatLineArea.setText("chesspad.connectServer无法连接\n"+ ec);}}if (e.getSource() == controlpad.cancelGameButton) {if (isOnChess) {chesspad.chessthread.sendMessage("/giveup " + chessClientName);chesspad.chessVictory(-1 * chesspad.chessColor);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}if (!isOnChess) {controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}isClient = isServer = false;}}public void keyPressed(KeyEvent e) {TextField inputWords = (TextField) e.getSource();if (e.getKeyCode() == KeyEvent.VK_ENTER) {if (erChoice.getSelectedItem().equals("所有人")) {try {out.writeUTF(inputWords.getText());inputWords.setText("");} catch (Exception ea) {chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n");erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}} else {try {out.writeUTF("/" + erChoice.getSelectedItem()+ " " + inputWords.getText());inputWords.setText("");} catch (Exception ea) {chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接\n");erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}}}}public void keyTyped(KeyEvent e) {}public void keyReleased(KeyEvent e) {}public static void main(String args[]) {chessClient chessClient = new chessClient();}}。
五子棋源代码
/*turboc2.0下编译通过*/#include#include#include#include#define N 15#define B 7#define STOP -10000#define OK 1#define NO 0#define UP 328#define DOWN 336#define LEFT 331#define RIGHT 333/*定义了两个数,n为棋盘的大小。
b为背景颜色的数值*/ int a[N+1][N+1];intzx,zy;int write=1,biaoji=0;structzn{long sum;int y;int x;}w[N+1][N+1],max,max1;void cbar(inti,intx,inty,int r);void map(int a[][]);intgetkey();int key();void zuobiao(intx,inty,inti);inttu(int a[][],int write);intwtu(int a[][],int write);intzhineng(int a[][]);int zh5(inty,intx,int a[][]);long zzh5(int b[][],inti);main(){inti,j;intgdriver=DETECT;intgmode;initgraph(&gdriver,&gmode,);zy=(N+1)/2;for(i=1;i<=N;i++)for(j=1;j<=N;j++)a[i][j]=0;map(a);i=1;while(i){intk,n;k=wtu(a,write);if(k==STOP) goto end;map(a);n=zhineng(a);if(n==STOP) goto end;map(a);}end:;}/* 实现对局的程序,计算全部N*N个格中,最应该填的格子*/ intzhineng(int a[N+1][N+1]){inti,j;int k;max.sum=-1;for(i=0;i<=N;i++)for(j=0;j<+N;j++){w[i][j].sum=0;w[i][j].x=i;w[i][j].y=j;}for(i=1;i<=N-4;i++)for(j=1;j<=N-4;j++){if(k==STOP) return (STOP);}for(i=1;i<=N;i++)for(j=1;j<=N;j++){if(max.sum {max.sum=w[i][j].sum;max.y=i;max.x=j;}else if(max.sum==w[i][j].sum){if(((max.y-zy)*(max.y-zy)+(max.x-zx)*(max.x-zx))>((i-zy)*(i-zy)+(j-zx)*(j-zx))) max.sum=w[i][j].sum;max.y=i;max.x=j;}}if(a[max.y][max.x]==0){a[max.y][max.x]=-1;zy=max.y;zx=max.x;}}/* 转换成5*5的数组,计算出在二十五个格子中,最应该填的格*/ int zh5(inty,intx,int a[N+1][N+1]){inti,j;int b[6][6];long c[13];long d[6][6];long temp;for(i=y;i<=y+4;i++)for(j=x;j<=x+4;j++)b[i+1-y][j+1-x]=a[i][j];c[1]=b[1][1]+b[1][2]+b[1][3]+b[1][4]+b[1][5];c[2]=b[2][1]+b[2][2]+b[2][3]+b[2][4]+b[2][5]; c[3]=b[3][1]+b[3][2]+b[3][3]+b[3][4]+b[3][5]; c[4]=b[4][1]+b[4][2]+b[4][3]+b[4][4]+b[4][5]; c[5]=b[5][1]+b[5][2]+b[5][3]+b[5][4]+b[5][5];c[6]=b[1][1]+b[2][1]+b[3][1]+b[4][1]+b[5][1]; c[7]=b[1][2]+b[2][2]+b[3][2]+b[4][2]+b[5][2]; c[8]=b[1][3]+b[2][3]+b[3][3]+b[4][3]+b[5][3]; c[9]=b[1][4]+b[2][4]+b[3][4]+b[4][4]+b[5][4]; c[10]=b[1][5]+b[2][5]+b[3][5]+b[4][5]+b[5][5];c[11]=b[1][1]+b[2][2]+b[3][3]+b[4][4]+b[5][5]; c[12]=b[1][5]+b[2][4]+b[3][3]+b[4][2]+b[5][1];for(i=1;i<=12;i++){switch(c[i]){case 5:biaoji=1;return(STOP);case -5:biaoji=-1;return(STOP);case -4:c[i]=100000;break;case 4:c[i]=100000;break;case -3:c[i]=150;break;case 3:c[i]=150;break;case -2:c[i]=120;break;case 2:c[i]=100;break;case -1:c[i]=1;break;case 1:c[i]=1;break;default: c[i]=0;}}for(i=1;i<=12;i++){if(c[i]==150)c[i]+=zzh5(b,i);}for(i=1;i<=5;i++)for(j=1;j<=5;j++)d[i][j]=0;for(i=1;i<=5;i++)for(j=1;j<=5;j++){if(i==j) d[i][j]+=c[11];if((i+j)==6) d[i][j]+=c[12];d[i][j]+=c[i]+c[j+5];}for(i=1;i<=5;i++)for(j=1;j<=5;j++){if(b[i][j]!=0)d[i][j]=-2;}max1.sum=-1;max1.y=0;max1.x=0;for(i=1;i<=5;i++)for(j=1;j<=5;j++){if(max1.sum {max1.sum=d[i][j];max1.y=i;max1.x=j;w[i+y-1][j+x-1].sum+=max1.sum;}else if(max1.sum==d[i][j]){if(((i+y-1-zy)*(i+y-1-zy)+(j+x-1-zx)*(j+x-1-zx))>((max1.y+y-1-zy)*(max1.y+y-1-zy)+(max1.x+x-1-zx)* (max1.x+x-1-zx))){max1.sum=d[i][j];max1.y=i;max1.x=j;}}}}long zzh5(int b[6][6],int n){inti,j,k,l,m;switch(n){case 1:i=b[1][1];j=b[1][2];k=b[1][3];l=b[1][4];m=b[1][5];break;case 2:i=b[2][1];j=b[2][2];k=b[2][3];l=b[2][4];m=b[2][5];break;case 3:i=b[3][1];j=b[3][2];k=b[3][3];l=b[3][4];m=b[3][5];break;case 4:i=b[4][1];j=b[4][2];k=b[4][3];l=b[4][4];m=b[4][5];break;case 5:i=b[5][1];j=b[5][2];k=b[5][3];l=b[5][4];m=b[5][5];break;case 6:i=b[1][1];j=b[2][1];k=b[3][1];l=b[4][1];m=b[5][1];break;case 7:i=b[1][2];j=b[2][2];k=b[3][2];l=b[4][2];m=b[5][2];break;case 8:i=b[1][3];j=b[2][3];k=b[3][3];l=b[4][3];m=b[5][3];break;case 9:i=b[1][4];j=b[2][4];k=b[3][4];l=b[4][4];m=b[5][4];break;case 10:i=b[1][5];j=b[2][5];k=b[3][5];l=b[4][5];m=b[5][5];break;case 11:i=b[1][1];j=b[2][2];k=b[3][3];l=b[4][4];m=b[5][5];break;case 12:i=b[1][5];j=b[2][4];k=b[3][3];l=b[4][2];m=b[5][1];break;}if((i==0&&j==1&&k==1&&l==1&&m==0))return (900);if((i==0&&j==-1&&k==-1&&l==-1&&m==0))return(1000);if((i==0&&j==0&&k==1&&l==1&&m==1)||(i==1&&j==1&&k==1&&l==0&&m==0))return(20);if((i==0&&j==0&&k==-1&&l==-1&&m==-1)||(i==-1&&j==-1&&k==-1&&l==0&&m==0))return(20);if((i==-1&&j==1&&k==1&&l==1&&m==1)||(i==1&&j==-1&&k==1&&l==1&&m==1)||(i==1&&j==1 &&k==-1&&l==1&&m==1)||(i==1&&j==1&&k==1&&l==-1&&m==1)||(i==1&&j==1&&k==1&&l== 1&&m==-1))return(-60);if((i==1&&j==-1&&k==-1&&l==-1&&m==-1)||(i==-1&&j==1&&k==-1&&l==-1&&m==-1)||(i==-1& &j==1&&k==-1&&l==-1&&m==-1)||(i==-1&&j==-1&&k==-1&&l==1&&m==-1)||(i==-1&&j==-1&& k==-1&&l==-1&&m==1))return(-60);}/* 循环执行坐标的选择,直到按回车,空格或ESC键*/intwtu(int a[N+1][N+1],int write){inti=1;map(a);zuobiao(zx,zy,1);while(i){int k;k=tu(a,write);if(k==OK) i=0;if(k==STOP) return (STOP);}}/*从键盘获得输入的值*/intgetkey(){intkey,lo,hi;key=bioskey(0);lo=key&0x00ff;hi=(key&0xff00)>>8;return((lo==0) ? hi+256:lo);}/*对获得的值进行判断*//*对应的码值分别如下*//* 上:328 下:336 左:331 右:333 */ /* 回车:13 ESC键:27 */int key(){int k;k=getkey();switch(k){case 27: return (STOP);case 13:case ' ': return (OK);case 328: return (UP);case 336: return (DOWN);case 331: return (LEFT);case 333: return (RIGHT);default: return (NO);}}/*用来显示坐标的位置*/void zuobiao(intx,inty,inti){int r;if(i!=0){setcolor(GREEN);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);}else{if(a[zy][zx]==1){setcolor(8);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);}else if(a[zy][zx]==-1){setcolor(WHITE);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);}else{setcolor(B);for(r=1;r<=5;r++)circle(75+25*x,25+25*y,r);setcolor(RED); line(75+25*zx-5,25+25*zy,75+25*x+5,25+25*zy); line(75+25*zx,25+25*zy-5,75+25*zx,25+25*zy+5);}}}/*从键盘获得的值进行判断,反映在显示的图上*/inttu(int a[N+1][N+1],int write){int k;re:k=key();if(k==OK){if(a[zy][zx]==0){a[zy][zx]=write;}elsegoto re;}if(k==STOP) return(STOP); if(k==NO) goto re;if(k==UP){inti,j;if(zy==1) j=zy;else j=zy-1;zuobiao(zx,zy,0); zuobiao(zx,j,1);zy=j;goto re;}if(k==DOWN){inti,j;if(zy==N) j=zy;else j=zy+1;zuobiao(zx,zy,0); zuobiao(zx,j,1);zy=j;goto re;}if(k==LEFT){inti,j;if(zx==1) i=zx;else i=zx-1;zuobiao(zx,zy,0); zuobiao(i,zy,1);zx=i;goto re;}if(k==RIGHT){inti,j;if(zx==N) i=zx;else i=zx+1;zuobiao(zx,zy,0);zuobiao(i,zy,1);zx=i;goto re;}}/* 根据数组中(存储棋子位置)各位置的数,画实心圆(画出棋子)*/ void cbar(inti,intx,inty,int r){if(i!=0){if(i==1)setcolor(8);else if(i==-1)setcolor(WHITE);for(i=1;i<=r;i++){circle(x,y,i);}}}/*画出棋盘,和各个棋子*/void map(int a[N+1][N+1]){inti,j;cleardevice();setbkcolor(B);setcolor(RED);for(i=0;i {line(100,50+25*i,75+N*25,50+25*i);line(100+25*i,50,100+25*i,25+N*25);}for(i=1;i<=N;i++)for(j=1;j<=N;j++)cbar(a[i][j],75+25*j,25+25*i,10); }。
C语言实现五子棋小游戏源代码
break;
case ESC:
break;
case SPACE:
if(chessx>=1&&chessx<=19&&chessy>=1&&chessy<=19)
{
if(chess[chessx][chessy]==0)
}
if(flag==2)
{
cleardevice();
setfont(36, 0, "宋体", 900, 900, 0, false, false, false);
outtextxy(80,200,"RED win!");
getch();
closegraph();
exit(0);
}
}
if(flag==1)
flag=2;
else
flag=1;
break;
}
void draw_pixel(int x,int y,int color)
{
x=(x+2)*20;
y=(y+2)*20;
{
putpixel(x+8,y,color);
putpixel(x,y-8,color);
putpixel(x+8,y+8,color);
{
chess[chessx][chessy]=flag;
if(result(chessx,chessy)==1)
{
if(flag==1)
{
cleardevice();
n1=0;
n2=0;
C语言五子棋游戏源代码
C语言五子棋游戏源代码标准化管理处编码[BBX968T-XBB8968-NNJ668-MM9N]#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N*N];int y[N*N];}weizhi[N*N];/******************主函数*****************/ void main(){int p=0;welcome();initqipan();for(p=1;p<=N*N;p++){weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();save(p);showqi(p);panduan(p);}if(p==N*N)heqi();over();}/******************建立棋盘*****************/ void initqipan(){int i,j;for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=0;j<N;j++){if(j==0)printf("%d",i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/ void showqi(int p){int i,j,k,m;int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=N*N;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp);a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}for(m=1;m<p;m++){while(weizhi[p].x[p]==a[m]&&weizhi[p].y[p]==b[m]) {printf("error!\n");weizhi[p].x[p]=zouqihang();weizhi[p].y[p]=zouqilie();m=1;}}for(i=0;i<N;i++){printf("%d",i);printf(" ");}printf("\n");for(i=1;i<N;i++){for(j=1;j<N;j++){if(j==1)printf("%d",i);for(k=1;k<=p;k++){if(i==weizhi[k].x[k]&&j==weizhi[k].y[k]) {if(k%2==1){printf("○");break;} else if(k%2==0){printf("●");break;} }}if(k>p)printf("·");else continue;}printf("\n");}}/******************走棋行*****************/ int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d",&x);while(x>N-1||x<1){printf("error!\n");printf("请输入要走棋子所在行数!\n"); printf("x=");scanf("%d",&x);}return x;}/******************走棋列*****************/ int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d",&y);while(y>N-1||y<1){printf("error!\n");printf("请输入要走棋子所在列数!\n"); printf("y=");scanf("%d",&y);}return y;}/******************文件保存*****************/ void save(int i){FILE *fp;fp=fopen("wuzi_list","wb");fwrite(&weizhi[i],sizeof(struct zuobiao),1,fp);}/****************判断输赢*******************/void panduan(int p){int i,j,k[8]={1,1,1,1,1,1,1,1,};int a[N*N],b[N*N];FILE *fp;fp=fopen("wuzi_list","rb");for(i=1;i<=p;i++){fread(&weizhi[i],sizeof(struct zuobiao),1,fp); a[i]=weizhi[i].x[i];b[i]=weizhi[i].y[i];}/*****************判断行******************/for(i=1;i<=p;i++){if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)){k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[0]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[0]++;continue;}else if(k[0]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[0]==5)break;k[0]=1;}else if(k[0]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j])&&(b[i]==b[j]-1)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-2)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-3)) {k[1]++;continue;}else if((a[i]==a[j])&&(b[i]==b[j]-4)) {k[1]++;continue;}else if(k[1]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[1]==5)break;k[1]=1;}}/**********************判断列************************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[2]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[2]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[2]++;continue;}else if(k[2]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[2]==5)break;k[2]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j])){k[3]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j])) {k[3]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j])) {k[3]++;continue;}else if(k[3]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[3]==5)break;k[3]=1;}}/****************判断对角(左上-右下)******************/ for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5)break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[4]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[4]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[4]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[4]++;continue;}else if(k[4]==5){printf("Player 1 wins!!!\n");}elsecontinue;}if(k[4]==5)break;k[4]=1;}else if(k[2]==5)break;else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]-1)&&(b[i]==b[j]-1)){k[5]++;continue;}else if((a[i]==a[j]-2)&&(b[i]==b[j]-2)) {k[5]++;continue;}else if((a[i]==a[j]-3)&&(b[i]==b[j]-3)) {k[5]++;continue;}else if((a[i]==a[j]-4)&&(b[i]==b[j]-4)) {k[5]++;continue;}else if(k[5]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[5]==5)break;k[5]=1;}}/**********判断对角(左下-右上)************/for(i=1;i<=p;i++){if(k[0]==5||k[1]==5||k[2]==5||k[3]==5||k[4]==5||k[5]==5) break;else if(i%2==1){for(j=1;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[6]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[6]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3)) {k[6]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4))k[6]++;continue;}else if(k[6]==5){printf("Player 1 wins!!!\n"); }elsecontinue;}if(k[6]==5)break;k[6]=1;}else if(k[6]==5)else if(i%2==0){for(j=2;j<=p;j=j+2){if((a[i]==a[j]+1)&&(b[i]==b[j]-1)){k[7]++;continue;}else if((a[i]==a[j]+2)&&(b[i]==b[j]-2)) {k[7]++;continue;}else if((a[i]==a[j]+3)&&(b[i]==b[j]-3))k[7]++;continue;}else if((a[i]==a[j]+4)&&(b[i]==b[j]-4)) {k[7]++;continue;}else if(k[7]==5){printf("Player 2 wins!!!\n");}elsecontinue;}if(k[7]==5)break;k[7]=1;}}}/****************和棋*******************/void heqi(){printf("************************************\n"); printf(" Tie!!!\n");printf("************************************\n"); }/****************游戏结束*******************/void over(){printf("************************************\n"); printf(" game over!!!\n");printf("************************************\n"); }/****************游戏开始*******************/void welcome(){printf("************************************\n"); printf(" Welcome!!!\n");printf("************************************\n"); }。
C语言程序源代码_五子棋游戏
if(box[j][k]==flag) n1++; else break ;
} /*垂直向下数*/ for(j=x,k=y;k<=18;k++) {
if(box[j][k]==flag) n2++; else break ; } if(n1+n2-1>=5) { return(1); break ; }
break ; } if(j>18)break ; step_y=j ; judgewho(step_x,step_y); break ; } case UP :
if((step_y-1)<0) break ; else {
for(i=step_x,j=step_y-1;j>=1;j--) if(box[i][j]==0) { draw_circle(step_x,step_y,LIGHTBLUE);
if(box[step_x][step_y]==0) {
box[step_x][step_y]=flag ; if(judgeresult(step_x,step_y)==1) {
sound(1000); delay(1000); nosound(); gotoxy(30,4); if(flag==1) {
{ setbkcolor(BLUE); cleardevice(); setviewport(100,100,540,380,1); /*定义一个图形窗口*/ setfillstyle(1,2); /*绿色以实填充*/ setcolor(YELLOW); rectangle(0,0,439,279); floodfill(50,50,14); setcolor(12); settextstyle(1,0,8); /*三重笔划字体, 水平放大 8 倍*/ outtextxy(20,20,"The Red Win !"); setcolor(15); settextstyle(3,0,5); /*无衬笔划字体, 水平放大 5 倍*/ outtextxy(120,120,"The Red Win !"); setcolor(14); settextstyle(2,0,8); getch(); closegraph(); exit(0);
java五子棋网络版源代码加分析
本人学会的一个五子棋网络版和单机版游戏,有老师指导完成,详细的解释和代码都在下面,希望可以帮助到大家!1.客户端连接新建个gobangClient类package gobang;public class gobangClient {public static void main(String[] args) throws Exception { new ChessBoard("localhost",8866);}}2.服务端连接新建个gobangServer类package gobang;public class gobangServer {public static void main(String[] args) throws Exception { new ChessBoard(8866);}}3.源代码,有详细解释package gobang;import java.awt.BorderLayout;import java.awt.Container;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.image.BufferedImage;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import .ServerSocket;import .Socket;import java.util.ArrayList;import java.awt.Graphics;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;public class ChessBoard extends JFrame{private boolean myPlay=false;//(默认是false)是否轮到我落子private JButton button1 =new JButton("开始");private JButton button2 =new JButton("悔棋");private JPanel p1 = new JPanel();private PicPane pp = null;private int side=1;//1表示黑private int n=0;//记录点击开始的次数public static final int SIZE=15;public static int[][]board=new int[SIZE][SIZE];//用来保存棋盘上棋子状态//1为黑,2为白,0为无public static final int BLACK=1;public static final int WHITE=-1;private NetService service;private static ArrayList<String> list =new ArrayList<String>(); //保存了下棋的步骤private boolean end=true;//true表示游戏已经结束private int currentColor=1;//服务端的构造器public ChessBoard(int port) throws Exception{//调用本类的无参构造树this();//构造器调用规则:1,只能调用本类或父类的构造器2. 调用构造器的代码写在新构造器的第一行3.构造器的调用只能使用this(本类)或者(父类) //将按钮设置能无效的button1.setEnabled(false);button2.setEnabled(false);//3.创建ServerSocket对象ServerSocket ss=new ServerSocket(port);//4.等待连接Socket s=ss.accept();//5.连接成功后创建一个线程来处理请求service=new NetService(s);service.start();//6.将按钮设置成有效的button1.setEnabled(true);button2.setEnabled(true);}//客户端的构造器public ChessBoard(String ip,int port) throws Exception{ //调用本类无参构造器this();//连接服务器Socket s=new Socket(ip,port);//初始化服务类service=new NetService(s);service.start();}public ChessBoard() throws IOException{Container c = this.getContentPane();c.setLayout(new BorderLayout());pp = new PicPane();BorderLayout bl = new BorderLayout();c.setLayout(bl);FlowLayout fl = new FlowLayout();p1.setLayout(fl);p1.add(button1);p1.add(button2);c.add(p1,BorderLayout.NORTH);c.add(pp,BorderLayout.CENTER);setSize(pp.getWidth()+6,pp.getHeight()+65);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setResizable(false);setVisible(true);button1.addActionListener(new SomeListener());button2.addActionListener(new button2Listener());}class SomeListener implements ActionListener{public void actionPerformed(ActionEvent e){// button2.setVisible(true);// if(n==0)// {// JOptionPane.showMessageDialog(// ChessBoard.this, "开始游戏啦!",// "提示",RMATION_MESSAGE);// }// else// {// JOptionPane.showMessageDialog(// ChessBoard.this, "确定要重新开始?",// "提示",RMATION_MESSAGE); // }// board=new int[15][15];// //调用重绘// pp.repaint();// end=false;// n++;start();}}private void start(){netStart();localStart();myPlay=true;//谁先点了开始按钮,谁先开始}private void localStart(){//重新初始化棋盘board=new int[SIZE][SIZE];//重新设置当前颜色currentColor=BLACK;//清空下棋步骤list=new ArrayList<String>();//重绘棋盘pp.repaint();//重新设置使下期没有结束end=false;}private void netStart(){service.send("start");}class button2Listener implements ActionListener{public void actionPerformed(ActionEvent e){back();// if(end==true)// {// JOptionPane.showMessageDialog(// ChessBoard.this, "人家都赢了你不能悔棋啦!", // "提示",RMATION_MESSAGE); // return;// }// int length = list.size();// if(list.size()<0)// {return;}// String str1 = list.remove(list.size() - 1);// String[] str3s = str1.split(",");// String str31 = str3s[0];// String str32 = str3s[1];// int row = Integer.parseInt(str31);// int col = Integer.parseInt(str32);// board[row][col]=0;// pp.repaint();// side = (side==1?2:1);//同下// if(side==1)// side=2;// else// side=1;}}public void back(){netBack();localBack();myPlay=!myPlay;//经典啊boolean的好处啊,悔棋了还是我下棋}private void localBack(){//如果结束不能悔棋if(end){return;}//if(list.isEmpty()){return;}//String str1 = list.remove(list.size() - 1);String[] str3s = str1.split(",");String str31 = str3s[0];String str32 = str3s[1];int row = Integer.parseInt(str31);int col = Integer.parseInt(str32);board[row][col]=0;currentColor=-currentColor;//pp.repaint();//}private void netBack(){if(end){//节省时间return;}service.send("back");}public static void toCenter(JFrame frame){int width = frame.getWidth();int height = frame.getHeight();Toolkit tookie = Toolkit.getDefaultToolkit();Dimension dim = tookie.getScreenSize();int screenWidth = dim.width;int screenHeight = dim.height;frame.setLocation((screenWidth - width)/2,(screenHeight-height)/2);}class PicPane extends JPanel{private int width;private int height;private BufferedImage bImg;//棋盘private BufferedImage chessImg;//黑子private BufferedImage wImg;//白子public PicPane() throws IOException{InputStreamips =PicPane.class.getResourceAsStream("images/chessboard.jpg");bImg = javax.imageio.ImageIO.read(ips);ips =PicPane.class.getResourceAsStream("images/b.gif");chessImg = javax.imageio.ImageIO.read(ips);ips =PicPane.class.getResourceAsStream("images/w.gif");wImg = javax.imageio.ImageIO.read(ips);width = bImg.getWidth();height = bImg.getHeight();addMouseListener(new boardListener());}@Overridepublic void paint(Graphics g){super.paint(g);g.drawImage(bImg,0,0,null);//加上画棋子的代码//依据board数组中的数据for(int i=0;i<board.length;i++){for(int j=0;j<board[i].length;j++){if(board[i][j]==1){g.drawImage(chessImg,j*35+3,i*35+3,null);}else if(board[i][j]==-1){g.drawImage(wImg,j*35+3,i*35+3,null);}}}}public int getHeight(){return height;}public int getWidth(){return width;}class boardListener extends MouseAdapter//只对感兴趣的方法实现,不用借口全部实现{@Overridepublic void mouseClicked(MouseEvent ae){int x=ae.getX();int y=ae.getY();int row=(y-4)/35;int col=(x-4)/35;play(row,col);// //判断游戏的状态,游戏是否结束的逻辑// if(end)// {// return;// }// //获得点击的坐标// int x=e.getX();// int y=e.getY();// int row=y/35;// int col=x/35;// if(row>=15||col>=15)// {// return;// }// if(board[row][col]==0)// switch(side)// {// case 1:// {//e.getComponent().getGraphics().drawImage(chessImg,col*35+3,row *35+3,null);// board[row][col]=1;//记录棋子// side=2;//改为白方// list.add(row+","+col);// break;// }// case 2:// {//e.getComponent().getGraphics().drawImage(wImg,col*35+3,row*35+ 3,null);// board[row][col]=2;// side=1;//改为黑方// list.add(row+","+col);// break;//改为黑方// }// }// //判断输赢// if(isWin(row,col))// {// //如果赢了:// end=true;// //提示用户,谁赢了// JOptionPane.showMessageDialog(ChessBoard.this,// (side==1?"白方胜":"黑方胜"),"提示",RMATION_MESSAGE);// }//}}}private void play(int row,int col){if(!myPlay){//如果不是我落子,直接返回,什么也不做return;}netPlay(row,col);//使另一方的棋盘上落子localPlay(row,col);//在本地的棋盘上落子myPlay=false;}private void netPlay(int row, int col){ if(end){//只打开服务器,会报错的问题return;}service.send(row+","+col);}private void localPlay(int row, int col){if(end){return;}if(row>=SIZE||col>=SIZE||row<0||col<0){return;}if(board[row][col]!=0){return;}//保存棋子board[row][col]=currentColor;//保存下棋步骤list.add(row+","+col);//重绘棋盘pp.repaint();if(isWin(row,col)){end=true;JOptionPane.showMessageDialog(ChessBoard.this,((currentColor==BLACK?"黑方":"白方")+"胜!"),"提示",RMATION_MESSAGE);}currentColor=-currentColor;}private boolean isWin(int currRow,int currCol){ // 需要比较四个方向的棋子(是否同色)int color=board[currRow][currCol];int[][]directions={{1,0},{1,1},{0,1},{-1,1}};//从四个方向比较for(int i=0;i<directions.length;i++){//计数器int num=1;//控制正反的for(int j=-1;j<2;j+=2){//比较次数for(int k=1;k<5;k++){//获得相邻的棋子的坐标int row=currRow+j*k*directions[i][0];int col=currCol+j*k*directions[i][1];//有可能行和列越界if(row<0||row>=15||col<0||row>=15){break;}if(board[row][col]==color){num++;if(num==5){return true;}}elsebreak;}}return false;}class NetService extends Thread{Socket s;BufferedReader in;PrintWriter out;public NetService(Socket s){try {this.s=s;in=new BufferedReader(new InputStreamReader(s.getInputStream()));out=new PrintWriter(s.getOutputStream());} catch (IOException e) {e.printStackTrace();}}public void send(String message){out.println(message);out.flush(); //刷新缓冲区}public void run(){try {while(true){String command=in.readLine();if(command.equals("start")){localStart();myPlay=false;}else if(command.equals("back")){localBack();myPlay=!myPlay;}else{String[]arr=command.split(",");int row=Integer.parseInt(arr[0]);int col=Integer.parseInt(arr[1]);localPlay(row,col);myPlay=true;}}} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) throws IOException {ChessBoard chessboard = new ChessBoard();toCenter(chessboard);}}。
五子棋游戏 C语言 代码 源代码
#include <stdio.h>#include <stdlib.h>#define m 30int main (void){int count;//计数器算横纵行的结果int w,h;int u;int l;int i,size;//i声明步数。
size声明int r[m][m] = {0};//数组声明(棋子位置)int x, y;//声明落子坐标int n;//声明棋盘大小nchar a[20],b[20];printf ("请输入棋盘大小n\n");//编辑棋盘直到棋盘长度宽度大于4小于30 scanf ("%d", &n);if (n<=4 || n>m){do{printf ("输入的棋盘大小:4<n<%d\n", m);scanf ("%d", &n);}while (n<=4 || n>m);}getchar ();//声明玩家printf ("请输入玩家1姓名:\n");gets(a);printf ("请输入玩家2姓名:\n");gets(b);for ( i = 1, size = n*n;i <= size; i++)//编辑棋盘{if (i%2 == 1)//如果i能被2整除,为玩家a相关信息{do//玩家a棋子信息{printf ("%s该你下棋了,第%d个棋子\n", a, i);scanf ("%d%d", &x, &y);if (x > n || x < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>m || x<0);}if (y > n || y < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 1;for (u = 0;u < n; u++)//不同情况下判断玩家a获胜方式{for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 1 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;//直接跳转,其余代码不在运行count = 0;for (w = u, h = l; r[w][h] == 1 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w = u,h = l; r[w][h] == 1 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 1 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}}}}system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++)//画棋盘,声明两玩家棋子图片{if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●"); }printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k);}else if (i%2 == 0)//如果i不能被2整除,为玩家b相关信息{do{printf ("\n%s该你下棋了,第%d个棋子\n", b, i);scanf ("%d%d", &x, &y);if (x > n || x < 0){do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>n || x<0);}if (y >n|| y < 0){do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 2;system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");count = 0;for (u = 0;u < n; u++){for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 2 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u, h = l; r[w][h] == 2 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u,h = l; r[w][h] == 2 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 2 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}}}}}e: for (int j = n;j>=0;j--)//游戏结束界面棋盘固定重新显示{printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");printf ("\a游戏愉快,Powered by Techmessager\n");//结束语句return 0;}。
五子棋代码
final JDialog dialog = new JDialog(this, "叫匡", true);
Font font=new Font("new_font", Font.BOLD, 20);
Grid grids[][] = new Grid[length][length];
direction=oblique_2;
break;
case oblique_2: displace_x=displace_y=1;
direction=horizontal;
int[][] dir = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
boolean[] dir2 = new boolean[8];
boolean turn;
String message;
break;
}
x=locX+displace_x;
y=locY+displace_y;
while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check)
{
count=count+1;
final static int End =3;
final static int nil=-1; /* 礚よ */
final static int oblique_1 =0; /* オ */
final static int oblique_2 =1; /* オ */
5子棋源代码
package org;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.JFrame;import javax.swing.JOptionPane;public class FiveChess extends JFrame implements MouseListener, Runnable { // 背景图片BufferedImage bgImage = null;// 保存棋子坐標int x = 0;int y = 0;// 用數組來表示所有下過的棋子// 其內容數據:0--表示沒有棋子、1--表示黑子、2--表示白子int[][] allChess = new int[19][19];// 标识下一步棋子的颜色boolean isBlack = true;// 标识游戏是否结束boolean canPlay = false;// 创建游戏信息标识String gameMessage = "黑方先行";// 创建黑白双方的游戏时间信息String blackTimeMessage = "无限制";String whiteTimeMessage = "无限制";// 保存游戲最大時間(秒)int maxTime = 0;// 保存黑白雙方游戲時間int blackTime = 0;int whiteTime = 0;// 保存黑白雙方游戲時間信息String blackMessage = "無限制";String whiteMessage = "無限制";// 創建線程,用來建立倒計時Thread t = new Thread(this);public FiveChess() {this.setTitle("五子棋");this.setSize(500, 500);this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - 500) / 2,(Toolkit.getDefaultToolkit().getScreenSize().height - 500) / 2);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);// 实例化背景图片try {bgImage = ImageIO.read(new File("F:" + File.separator + "image"+ File.separator + "background.jpg"));} catch (IOException e) {e.printStackTrace();}// 加入鼠标监听this.addMouseListener(this);t.start();// 啟動線程t.suspend();//掛起線程this.repaint();// 刷新屏幕}public void paint(Graphics g) {// 利用双缓冲技术,防止点击时屏幕闪烁。
Java五子棋游戏源代码(人机对战)
//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。
**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。
Python五子棋游戏代码
Python五子棋游戏代码五子棋游戏涉及到的内容较多,这里给出一个简化版的五子棋游戏实现。
首先需要安装pygame库,可以使用以下命令安装:bashpip install pygame接下来是五子棋游戏的代码:import pygameimport sys# 初始化pygamepygame.init()# 设置屏幕大小screen_size = (600, 600)screen = pygame.display.set_mode(screen_size)# 设置颜色white = (255, 255, 255)black = (0, 0, 0)# 加载棋盘图片board_image = pygame.image.load("board.png")# 设置棋盘大小board_size = board_image.get_rect().size# 设置棋盘坐标def get_position(x, y):return x * board_size[0], y * board_size[1]# 绘制棋盘def draw_board():for x in range(15):for y in range(15):rect = get_position(x, y)screen.blit(board_image, rect)pygame.draw.line(screen, black, get_position(x, y), get_position((x + 1) % 15, y), 2)pygame.draw.line(screen, black, get_position(x, y), get_position((x - 1) % 15, y), 2)# 主循环player = 1while True:for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.MOUSEBUTTONDOWN:x, y = event.posx, y = x // board_size[0], y // board_size[1]if board_image.get_at((x, y)) == (0, 0, 0):if player == 1:player = 2else:player = 1screen.fill(white)draw_board()pygame.display.flip()注意:这个示例需要你提供一张名为"board.png"的棋盘图片。
五子棋源代码(C++)-完美版
#include <iostream>#include <conio.h>using namespace std;#define WIDE_AND_LONG 20 //棋盘的长和宽#define NAME_LEN 20 //输入姓名的长度typedef class Gobang{public:int InitPlayerName(char *, char *);int CheckInput(char,int);int CheckIndexInput(char, char, char);int GetPlayerName();int InitBoard();int WriteBoard(char, char, bool);int BeginOrNot();int CheckRow();int CheckColumn();int CheckTopLeft();int CheckTopRight();int CheckDownLeft();int CheckDownRight();int CheckDraw();int CheckFinish();int Chess();int ShowBoard();private:char acBoard[WIDE_AND_LONG][WIDE_AND_LONG];char acPlayerOneName[NAME_LEN];char acPlayerTwoName[NAME_LEN];}GOBANG;//初始化姓名的缺省值int GOBANG::InitPlayerName(char *pPlayerOne,char *pPlayerTwo) {strcpy(acPlayerOneName,pPlayerOne);strcpy(acPlayerTwoName,pPlayerTwo);return 0;}//检查输入姓名时是否含非法字符空格和Tab键int GOBANG::CheckInput(char ch, int iNameLen){if(' ' == ch || '\t' == ch){cout<<"含有非法字符!"<<endl;return -1;}{cout<<"输入超出限定长度!"<<endl;return -1;}return 0;}//将棋子放到棋盘中int GOBANG::WriteBoard(char cRow, char cColumn, bool bJudge){int iRow = 0;int iColumn = 0;if(cRow >= '0' && cRow <= '9'){iRow = static_cast<int>(cRow - '0');}else if(cRow >= 'A' && cRow <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)){iRow = static_cast<int>((cRow - 'A') + 10);}else{iRow = static_cast<int>((cRow - 'a') + 10);}if(cColumn >= '0' && cColumn <= '9'){iColumn = static_cast<int>(cColumn - '0');}else if(cColumn >= 'A' && cColumn <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) {iColumn = static_cast<int>((cColumn - 'A') + 10);}else{iColumn = static_cast<int>((cColumn - 'a') + 10);}if('+' != acBoard[iRow][iColumn]){cout<<"此处已有棋子!"<<endl;return -1;}if(!bJudge){acBoard[iRow][iColumn] = static_cast<char>(1);}elseacBoard[iRow][iColumn] = static_cast<char>(2);}return 0;}//检查坐标输入是否合法int GOBANG::CheckIndexInput(char cRow,char cSeparator,char cColumn){if(!cRow || !cSeparator || !cColumn){return -1;}if(!((cRow >= '0' && cRow <= '9') || \(cRow >= 'A' && cRow <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) || \ (cRow >= 'a' && cRow <= static_cast<char>('a' + WIDE_AND_LONG - 10 - 1)))){return -1;}if(' ' != cSeparator && '\t' != cSeparator && ',' != cSeparator){return -1;}if(!((cColumn >= '0' && cColumn <= '9') || \(cColumn >= 'A' && cColumn <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) || \ (cColumn >= 'a' && cColumn <= static_cast<char>('a' + WIDE_AND_LONG - 10 - 1)))){return -1;}return 0;}//获取玩家的昵称int GOBANG::GetPlayerName(){fflush(stdin);char cTemp = 0;int iNameLen = 0;cout<<"是否自己定义昵称?是(Y),否(任意键):";cTemp = getch();cout<<endl;if(('y' != cTemp) && ('Y' != cTemp)){return 0;}fflush(stdin);memset(acPlayerTwoName,0,sizeof(acPlayerTwoName));cout<<"请玩家一输入昵称:";while('\n' != (cTemp = getchar())){if(-1 == CheckInput(cTemp,iNameLen)){fflush(stdin);cout<<"请玩家一输入昵称:";continue;}acPlayerOneName[iNameLen] = cTemp;iNameLen++;}if(0 == iNameLen){strcpy(acPlayerOneName,"玩家一");}iNameLen = 0;fflush(stdin);cout<<"请玩家二输入昵称:";while('\n' != (cTemp = getchar())){if(-1 == CheckInput(cTemp,iNameLen)){fflush(stdin);cout<<"请玩家二输入昵称:";continue;}acPlayerTwoName[iNameLen] = cTemp;iNameLen++;}if(0 == iNameLen){strcpy(acPlayerTwoName,"玩家一");}return 0;}//初始化棋盘int GOBANG::InitBoard(){int iRow = 0;int iColumn = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++)acBoard[iRow][iColumn] = '+';}}return 0;}//检查棋盘横向是否存在五子连珠int GOBANG::CheckRow(){int iRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow ++) {while(iColumn < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;}else if(static_cast<char>(2) == acBoard[iRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iColumn ++;}if(iPlayerOneLen >= 5){return 1;}if(iPlayerTwoLen >= 5){return 2;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}}//检查棋盘竖向是否存在五子连珠int GOBANG::CheckColumn(){int iRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn ++) {while(iRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;}else if(static_cast<char>(2) == acBoard[iRow][iColumn]){iPlayerTwoLen ++;iPlayerOneLen = 0;}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iRow ++;}if(iPlayerOneLen >= 5){return 1;}if(iPlayerTwoLen >= 5){return 2;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iRow = 0;}return 0;}//检查棋盘左上方(包括对角线)是否存在五子连珠int GOBANG::CheckTopLeft()int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 4; iRow < WIDE_AND_LONG; iRow ++){iTempRow = iRow;while(iTempRow >= 0){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow --;iColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘右上方(包括对角线)是否存在五子连珠int GOBANG::CheckTopRight()int iTempColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iColumn = 0; iColumn < WIDE_AND_LONG - 4; iColumn ++) {iTempColumn = iColumn;while(iTempColumn < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iTempColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iRow][iTempColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iRow ++;iTempColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iRow = 0;}return 0;}//检查棋盘左下方(不包括对角线)是否存在五子连珠{int iRow = 0;int iTempRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 1; iRow < WIDE_AND_LONG - 4; iRow ++){iTempRow = iRow;while(iTempRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow ++;iColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}int GOBANG::CheckDownRight(){int iRow = 0;int iTempRow = 0;int iColumn = WIDE_AND_LONG - 1;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 1; iRow < WIDE_AND_LONG - 4; iRow ++){iTempRow = iRow;while(iTempRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow ++;iColumn --;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = WIDE_AND_LONG - 1;}return 0;//检查是否平局int GOBANG::CheckDraw(){int iRow = 0;int iColumn = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++){if('+' == acBoard[iRow][iColumn]){return 1;}}}return 0;}//检查是否达到结束的条件(五子连珠或平局)int GOBANG::CheckFinish(){int iJudgeRow = 0;int iJudgeColumn = 0;int iJudgeTopLeft = 0;int iJudgeTopRight = 0;int iJudgeDownLeft = 0;int iJudgeDownRight = 0;int iJudgeDraw = 0;iJudgeRow = CheckRow();iJudgeColumn = CheckColumn();iJudgeTopLeft = CheckTopLeft();iJudgeTopRight = CheckTopRight();iJudgeDownLeft = CheckDownLeft();iJudgeDownRight = CheckDownRight();iJudgeDraw = CheckDraw();if(1 == iJudgeRow || 1 == iJudgeColumn || 1 == iJudgeTopLeft || \1 == iJudgeTopRight || 1 == iJudgeDownLeft || 1 == iJudgeDownRight) {cout<<"恭喜玩家<"<<acPlayerOneName<<">获胜!"<<endl;return 1;}if(2 == iJudgeRow || 2 == iJudgeColumn || 2 == iJudgeTopLeft || \2 == iJudgeTopRight || 2 == iJudgeDownLeft || 2 == iJudgeDownRight) {cout<<"恭喜玩家<"<<acPlayerTwoName<<">获胜!"<<endl;return 1;}if(0 == iJudgeDraw){cout<<"平局!"<<endl;return 1;}return 0;}//显示棋盘到控制台int GOBANG::ShowBoard(){int iRow = 0;int iColumn = 0;system("cls");cout<<" ";for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){if(9 < iRow){cout<<static_cast<char>('A' + iRow - 10)<<" ";}else{cout<<iRow<<" ";}}cout<<endl;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){if(9 < iRow){cout<<static_cast<char>('A' + iRow - 10)<<" ";}else{cout<<iRow<<" ";}for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++) {cout<<acBoard[iRow][iColumn]<<' ';}cout<<endl;}return 0;}//开始下棋int GOBANG::Chess(){bool bJudge = false;while(1){char cRow = 0;char cSeparator = 0;char cColumn = 0;char cTemp = 0;int iLen =1;fflush(stdin);if(!bJudge){cout<<"请<"<<acPlayerOneName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }else{cout<<"请<"<<acPlayerTwoName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }while('\n' != (cTemp = getchar())){if(iLen > 3){cout<<"输入有误!"<<endl;fflush(stdin);if(!bJudge){cout<<"请<"<<acPlayerOneName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):";}else{cout<<"请<"<<acPlayerTwoName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):";}iLen = 1;continue;}if(1 == iLen){cRow = cTemp;}else if(2 == iLen){cSeparator = cTemp;}else{cColumn = cTemp;}iLen++;}if(-1 == CheckIndexInput(cRow,cSeparator,cColumn)) {cout<<"输入有误!"<<endl;continue;}if(-1 == WriteBoard(cRow,cColumn,bJudge)){continue;}ShowBoard();if(1 == CheckFinish()){BeginOrNot();}bJudge = !bJudge;}return 0;}//判断游戏结束后玩家是否选择继续还是退出int GOBANG::BeginOrNot(){char cTemp = 0;cout<<"是否继续?是(Y),退出(任意键):";fflush(stdin);cTemp = getch();if('y' == cTemp || 'Y' == cTemp){InitBoard();ShowBoard();Chess();}else{exit(0); //程序的出口}return 0;}int main(){GOBANG gobang;memset(&gobang,0,sizeof(GOBANG));gobang.InitPlayerName("玩家一","玩家二"); gobang.GetPlayerName();gobang.InitBoard(); gobang.ShowBoard(); gobang.Chess(); return 0;}。
最新 java五子棋源代码(完整版)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import .*;
import java.util.*;
class clientthread extends thread
{
chessclient chessclient;
{
chessclient.isonchess=false;
chessclient.chesspad.chessvictory(chessclient.chesspad.chesscolor);
chessclient.chesspad.statustext.settext("对方退出,请点放弃游戏退出连接");
controlpad.joingamebutton.setenabled(false);
controlpad.cancelgamebutton.setenabled(false);
southpanel.add(controlpad,borderlayout.center);
southpanel.setbackground(color.pink);
panel southpanel=new panel();
panel northpanel=new panel();
panel centerpanel=new panel();
panel westpanel=new panel();
panel eastpanel=new panel();
try
{
while(true)
{
message=chessclient.in.readutf();
五子棋源代码
import java.awt.*;import java.awt.event.MouseListener;import java.awt.event.MouseEvent;import java.util.Vector;import javax.swing.*;public class wuziqi extends JFrame implements MouseListener{ public static void main(String args[]){wuziqi d=new wuziqi();}Vector v=new Vector();Vector white=new Vector();Vector black=new Vector();JButton btnstart =new JButton("开始");JButton btnstop =new JButton("停止");JToolBar tool=new JToolBar();boolean b; //用来判断白棋还是黑棋int blackcount,whitecount; //计算悔棋public wuziqi(){super("五子棋游戏");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按钮Container con=this.getContentPane();this.addMouseListener(this);//添加监听tool.add(btnstart);//添加按钮tool.add(btnstop);this.setSize(550,500);//设置窗体大小this.setVisible(true);}int w=20; //间距大小是双数int px=100,py=100; //棋盘的坐标int pxw=(px+w), pyw=(py+w);int w=w*16,h=w*16;int vline=(w+px); //垂直线的长度int hline=(h+py); //水平线的长度/*** 画棋盘*/public void paint(Graphics g){g.clearRect(0, 0, this.getw(), this.geth()); //清除面板g.setColor(Color.BLACK); //设置网格颜色g.drawRect(px, py, w, h); //网格大小g.drawString("简易五子棋-可以悔棋", 110, 70);for(int i=0;i<15;i++){g.drawLine(pxw+i*w,py,pxw+i*w,hline);//每条横线和竖线g.drawLine(px,pyw+i*w,vline,pyw+i*w);}g.setColor(Color.WHITE);}else{for(int x=0;x<v.size();x++){String str=(String)v.get(x);String tmp[]=str.split("-");int a=Integer.parseInt(tmp[0]);int b=Integer.parseInt(tmp[1]);a=a*w+px;b=b*w+py;if(x%2==0){g.setColor(Color.BLACK);}g.fillArc(a-w/2, b-w/2, w, w,0,360);}}public void updeta(Graphics g){ this.paint(g);}public void victory(int x,int y,Vector contain){ //判断胜利的方法int cv=0; //计算垂直的变量int ch=0; //计算水平的变量int ci1=0; //计算斜面的变量1int ci2=0; //计算斜面的变量2for(int i=1;i<5;i++){if(contain.contains((x+i)+"-"+y))ch++;else break;}System.out.println("前面已执行"+ch+"次");for(int i=1;i<5;i++){if(contain.contains((x-i)+"-"+y))ch++;else break;}System.out.println("后面已执行"+ch+"次");for(int i=1;i<5;i++){if(contain.contains(x+"-"+(y+i)))cv++;else break;}for(int i=1;i<5;i++){if(contain.contains(x+"-"+(y-i)))cv++;else break;}for(int i=1;i<5;i++){if(contain.contains((x+i)+"-"+(y+i)))ci1++;else break;}for(int i=1;i<5;i++){if(contain.contains((x-i)+"-"+(y-i)))ci1++;elsebreak;}for(int i=1;i<5;i++){if(contain.contains((x-i)+"-"+(y+i)))ci2++;else break;}for(int i=1;i<5;i++){if(contain.contains((x+i)+"-"+(y-i)))ci2++;else break;}if(ch>=4||cv>=4||ci1>=4||ci2>=4){System.out.println(v.size()+"步棋");if(v.size()%2==0){ //判断偶数是黑棋胜利,奇数白棋胜利JOptionPane.showMessageDialog(null,"恭喜你黑棋赢了");}else{JOptionPane.showMessageDialog(null,"恭喜你白棋赢了");}this.v.clear();this.black.clear();this.white.clear();this.repaint();}System.out.println(ch+" "+cv+" "+ci1+" "+ci2);}public void mouseClicked(MouseEvent e) {if(e.getButton()==e.BUTTON1){int x=e.getX();int y=e.getY();x=(x-x%w)+(x%w>w/2?w:0);y=(y-y%w)+(y%w>w/2?w:0);x=(x-px)/w;y=(y-py)/w;if(x>=0&&y>=0&&x<=16&&y<=16){if(v.contains(x+"-"+y)){System.out.println("已有棋了");}else{v.add(x+"-"+y);this.repaint();if(v.size()%2==0){black.add(x+"-"+y);this.victory(x, y,black);System.out.println("黑棋");}else{white.add(x+"-"+y);this.victory(x, y,white);System.out.println("白棋");}System.out.println(e.getX()+"-"+e.getY());}}else{System.out.println(e.getX()+"-"+e.getY()+"|"+ x+"-"+y+"\t 超出边界");}}if(e.getButton()==e.BUTTON3){ //悔棋方法全在这里System.out.println("鼠标右键-悔棋");if(v.isEmpty()){JOptionPane.showMessageDialog(this,"没有棋可以悔");}else{if(v.size()%2==0){ //判断是白方悔棋还是黑方悔棋blackcount++;if(blackcount>3){JOptionPane.showMessageDialog(this, "黑棋已经悔了三步");}else{v.remove(stElement());this.repaint();}}else{whitecount++;if(whitecount>3){JOptionPane.showMessageDialog(this, "白棋已经悔了三步");}else{v.remove(stElement());this.repaint();}}}}}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}}。
五子棋 C++ 源代码
int main()
{
int isSuccess = -1;
char isContinue = 'Y';
int mark = 0;
int mark_tmp;
Print();
cout<<"白方落子:"<<endl;
while(isSuccess == -1)
num=num>>1;
}
}
for(c1=0;c1<8;c1++)
{
for(c2=0;c2<4;c2++)
{
cout<<res[++i];
}
cout<<" ";
}
cout<<endl;
}
bool Compare(unsigned int num1, unsigned int num2)
&&Compare(position1[ser+2],qipan[i+2]&position0[ser+2])
&&Compare(position1[ser+3],qipan[i+3]&position0[ser+3])
&&Compare(position1[ser+4],qipan[i+4]&position0[ser+4]))
cout<<endl;
}
int TestSuccess()
五子棋源代码
package resource;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.geom.Ellipse2D;import java.awt.geom.Line2D;import javax.swing.JPanel;publicclass DrawPanel extends JPanel{privateint[][] a;privateint n,m;public DrawPanel(int k[][],int n1,int m1){a=k;n=n1;m=m1;}publicvoid paintComponent(Graphics g){super.paintComponent(g);Graphics2D g2=(Graphics2D)g;Graphics2D g3=(Graphics2D)g;double X=20;double Y=20;double width=480;double height=480;double jiange=30;// 画棋盘网格for(int i=0;i<=width/jiange;i++){g2.draw(new Line2D.Double(X+i*jiange,Y,X+i*jiange,height+Y));g2.draw(new Line2D.Double(X,Y+i*jiange,width+X,Y+i*jiange));}//画中间点的标记g3.setPaint(Color.RED);g3.draw(new Line2D.Double(254,245,254,254));g3.draw(new Line2D.Double(245,254,254,254));g3.draw(new Line2D.Double(267,245,267,254));g3.draw(new Line2D.Double(267,254,275,254));g3.draw(new Line2D.Double(245,266,254,266));g3.draw(new Line2D.Double(254,266,254,275));g3.draw(new Line2D.Double(266,275,266,266));g3.draw(new Line2D.Double(266,266,275,266));//画旗子for(int i=1;i<a.length-1;i++){for(int j=1;j<a[i].length-1;j++){Ellipse2D circle=new Ellipse2D.Double();circle.setFrame(j*30-25, i*30-25, 28, 28);if(a[i][j]==1){g2.setPaint(Color.BLACK);g2.fill(circle);}elseif(a[i][j]==2){g2.setPaint(Color.WHITE);g2.fill(circle);}}}//画旗子上的标记if(n>0&&m>0){g2.setPaint(Color.RED);g2.setStroke(new BasicStroke(1.5f));g2.draw(new Line2D.Double(30*m-16,30*n-16,30*m-4,30*n-4));g2.draw(new Line2D.Double(30*m-16,30*n-4,30*m-4,30*n-16));}}}package resource;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.Toolkit;import java.awt.Dimension;import javax.swing.JColorChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;publicclass PlayerVsPC {private JFrame frame; //整个窗口private JMenuBar bar; //菜单栏private JMenuItem[][] jit;//菜单项数组private JMenuItem[] mode;//模式项数组private JMenu[] jm; //菜单publicboolean isBlack; //是否为黑方下子状态privateint[][] qipan; //棋盘数组privateint row; //当前行privateint col; //当前列privateint prow;privateint pcol;private DrawPanel panel; //棋盘面板private JLabel label; //棋盘上方的标签private JPanel panel0; //棋盘上方条形面板privateboolean isEnd;privateint[][] qixingPC;privateint[][] qixingPlayer;privateboolean isPC = true; //记录当前下棋模式privateboolean cMode = true; //记录选择的对弈模式public PlayerVsPC(){frame=new JFrame("五子棋游戏");bar=new JMenuBar();jm=new JMenu[2];jit=new JMenuItem[2][];qipan=newint[19][19];qixingPC = newint[17][17];qixingPlayer = newint[17][17];for(int i=0;i<19;i++){for(int j=0;j<19;j++){qipan[i][j]=0;}}for(int i=0;i<17;i++){for(int j=0;j<17;j++){qixingPC[i][j]=0;qixingPlayer[i][j]=0;}}label = new JLabel("人"+(isPC?"机":"人")+"对弈模式,请按开局开始游戏!");panel0=new JPanel();addItems();addEventAction();printqipan(0,0);}publicvoid addItems(){jm[0]=new JMenu("游戏");jm[1]=new JMenu("选项");jit[0]=new JMenuItem[3];jit[0][0]=new JMenuItem("开局");jit[0][1]=new JMenuItem("重新开始");jit[0][2]=new JMenuItem("结束游戏");jit[1]=new JMenuItem[2];jit[1][0]=new JMenu("对弈模式");mode=new JMenuItem[2];mode[0] = new JMenuItem("人人对弈");mode[1] = new JMenuItem("人机对弈");jit[1][0].add(mode[0]);jit[1][0].add(mode[1]);jit[1][1]=new JMenuItem("悔棋");for(int i=0;i<jm.length;i++){for(int j=0;j<jit[i].length;j++){jm[i].add(jit[i][j]);}}panel0.add(label);bar.add(jm[0]);bar.add(jm[1]);frame.setJMenuBar(bar);frame.add(panel0,"North");}//给菜单项设定事件publicvoid addEventAction(){jit[0][0].addActionListener(new ActionListener(){ //开局publicvoid actionPerformed(ActionEvent e) {row=prow=0;col=pcol=0;isPC=cMode;isBlack = true;isEnd = false;for(int i=0;i<19;i++){for(int j=0;j<19;j++){if(i==0||j==0||i==(qipan.length-1)||j==(qipan.length-1)){qipan[i][j] = -1;}else{qipan[i][j]=0;}}}if(isPC){ //人机对弈模式label.setText("游戏开始,请玩家先下棋!");}else{ //人人对弈模式label.setText("游戏开始,请"+(isBlack?"黑":"白")+"方先下棋!");}printqipan(row,col);addEventHandler();}});jit[0][1].addActionListener(new ActionListener(){ //重新开始publicvoid actionPerformed(ActionEvent e) {row=prow=0;col=pcol=0;isBlack = true;isEnd = false;for(int i=0;i<19;i++){for(int j=0;j<19;j++){if(i==0||j==0||i==(qipan.length-1)||j==(qipan.length-1)){qipan[i][j] = -1;}else{qipan[i][j]=0;}}}if(isPC){ //人机对弈模式label.setText("游戏开始,请玩家先下棋!");}else{ //人人对弈模式label.setText("游戏开始,请"+(isBlack?"黑":"白")+"方先下棋!");}printqipan(row,col);addEventHandler();}});//给模式选项添加事件监听mode[0].addActionListener(new ActionListener(){publicvoid actionPerformed(ActionEvent e) {cMode = false;label.setText("已选择人"+(cMode?"机":"人")+"对弈模式,重新开局将生效!");}});mode[1].addActionListener(new ActionListener(){publicvoid actionPerformed(ActionEvent e) {cMode = true;label.setText("已选择人"+(cMode?"机":"人")+"对弈模式,重新开局将生效!");}});jit[0][2].addActionListener(new ActionListener(){ //结束游戏publicvoid actionPerformed(ActionEvent e) {label.setText("游戏结束,请按开局开始游戏!");isEnd=true;}});jit[1][1].addActionListener(new ActionListener(){ //悔棋publicvoid actionPerformed(ActionEvent e) {if(!isPC){huiqi();}else{pchuiqi();}}});}// 监听鼠标事件,下棋以及判断本盘是否结束,电脑是白方,玩家是黑方publicvoid addEventHandler(){panel.addMouseListener(new MouseAdapter(){publicvoid mousePressed(MouseEvent e) {if(!isEnd){int x=(e.getX()-5)/30;int y=(e.getY()-5)/30;if(qipan[y+1][x+1]==0){load(x+1,y+1);}else{label.setText("此处已经有棋子,请重新下子!");}}}});}//电脑下棋publicvoid pcLoad(){qixing();int count = 0;int hang = 0;int lie = 0;for(int i=0;i<17;i++){for(int j=0;j<17;j++){if(qixingPC[i][j]>count){count = qixingPC[i][j];hang = i+1;lie = j+1;}if(qixingPlayer[i][j]>count){count = qixingPlayer[i][j];hang = i+1;lie = j+1;}}}if(qipan[hang][lie]==0){load(lie,hang);return;}}//下棋子publicvoid load(int x,int y){col=x;row=y;if(isBlack){prow=row;pcol=col;qipan[row][col]=1;isBlack = false;}else{qipan[row][col]=2;isBlack = true;}printqipan(row,col);if(panduan(row-1,col-1)){if(isPC){label.setText("本局结束,恭喜"+(isBlack?"电脑":"玩家")+"获胜!");isEnd = true;}else{label.setText("本局结束,恭喜"+(isBlack?"黑":"白")+"方获胜!");isEnd = true;}}else{if(isPC){label.setText((isBlack?"电脑":"玩家")+"在("+row+":"+col+")处下子,"+"现在"+(isBlack?"玩家":"电脑")+"下子!");}else{label.setText((isBlack?"白":"黑")+"方在("+row+":"+col+")处下子,"+"现在"+(isBlack?"黑":"白")+"下子!");}if(!isBlack){if(isPC){pcLoad();}}}}//刷新棋盘publicvoid printqipan(int n,int m){panel=new DrawPanel(qipan,n,m);//panel.setBackground(c);frame.add(panel,"Center");}//人人对弈悔棋publicvoid huiqi(){if(isEnd){label.setText("游戏已经结束不能悔棋,请重新开局!");return;}isBlack=!isBlack;qipan[row][col]=0;printqipan(row,col);label.setText((isBlack?"黑":"白")+"方悔棋,请重新下棋!");}//人机对弈悔棋publicvoid pchuiqi(){if(isEnd){label.setText("游戏已经结束不能悔棋,请重新开局!");return;}qipan[row][col]=0;qipan[prow][pcol]=0;printqipan(row,col);label.setText((isBlack?"玩家":"电脑")+"悔棋,请重新下棋!");}//算出双方的棋形数组publicvoid qixing(){for(int i=0;i<17;i++){for(int j=0;j<17;j++){if(qipan[i+1][j+1]==0){//说明此处没有棋子qixingPC[i][j] =heiheng(i,j,2)+heishu(i,j,2)+heizuoxie(i,j,2)+heiyouxie(i,j,2);qixingPlayer[i][j] =heiheng(i,j,1)+heishu(i,j,1)+heizuoxie(i,j,1)+heiyouxie(i,j,1);}else{qixingPC[i][j] = 0;qixingPlayer[i][j] = 0;}}}}// 算出黑子横方向的棋型数值publicint heiheng(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean left = false;//判断左边是否有黑子boolean liveLeft = false;//判断左边是活还是死boolean liveRight = false;//判断右边是活还是死while((qipan[n][m-1]!=-1)&&(qipan[n][m-1]==num||qipan[n][m-1]==0)){ if(qipan[n][m-1]==0&&k<1){//第一个空白if(qipan[n][m-2]!=num){liveLeft = true;break;}k++;m--;}elseif(qipan[n][m-1]==num){//黑子left = true;m--;}else{//第二个空白liveLeft = true;break;}}if(!left){k = 0;m = lie+1;}while((qipan[n][m+1]!=-1)&&(qipan[n][m+1]==num||qipan[n][m+1]==0)){ int t = qipan[n][m+1];if(m==lie){count++;m++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n][m+2]!=num){liveRight = true;break;}k++;m++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子m++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}// 算出黑子竖方向的棋型数值publicint heishu(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean top = false;//判断上边是否有黑子boolean liveLeft = false;boolean liveRight = false;while((qipan[n-1][m]!=-1)&&(qipan[n-1][m]==num||qipan[n-1][m]==0)){ if(qipan[n-1][m]==0&&k<1){//第一个空白if(qipan[n-2][m]!=num){liveLeft = true;break;}k++;n--;}elseif(qipan[n-1][m]==num){//黑子top = true;n--;}else{//第二个空白liveLeft = true;break;}}if(!top){k = 0;n = hang+1;}while((qipan[n+1][m]!=-1)&&(qipan[n+1][m]==num||qipan[n+1][m]==0)){ int t = qipan[n+1][m];if(n==hang){count++;n++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n+2][m]!=num){liveRight = true;break;}k++;n++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子n++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}// 算出黑子左斜方向的棋型数值publicint heizuoxie(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean top = false;//判断上边是否有黑子boolean liveLeft = false;boolean liveRight = false;while((qipan[n+1][m-1]!=-1)&&(qipan[n+1][m-1]==num||qipan[n+1][m-1]==0)){ if(qipan[n+1][m-1]==0&&k<1){//第一个空白if(qipan[n+2][m-2]!=num){liveLeft = true;break;}k++;n++;m--;}elseif(qipan[n+1][m-1]==num){//黑子top = true;n++;m--;}else{//第二个空白liveLeft = true;break;}}if(!top){k = 0;n = hang+1;m = lie+1;}while((qipan[n-1][m+1]!=-1)&&(qipan[n-1][m+1]==num||qipan[n-1][m+1]==0)){ int t = qipan[n-1][m+1];if(n==(hang+2)&&m==lie){count++;n--;m++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n-2][m+2]!=num){liveRight = true;break;}k++;n--;m++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子n--;m++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}// 算出黑子右斜方向的棋型数值publicint heiyouxie(int hang,int lie,int num){int k = 0;//记录空白处的个数int count = 1;//记录可以形成几连int n = hang+1;//对应棋盘的行int m = lie+1;//对应棋盘的列boolean top = false;//判断上边是否有黑子boolean liveLeft = false;boolean liveRight = false;while((qipan[n-1][m-1]!=-1)&&(qipan[n-1][m-1]==num||qipan[n-1][m-1]==0)){ if(qipan[n-1][m-1]==0&&k<1){//第一个空白if(qipan[n-2][m-2]!=num){liveLeft = true;break;}k++;n--;m--;}elseif(qipan[n-1][m-1]==num){//黑子top = true;n--;m--;}else{//第二个空白liveLeft = true;break;}}if(!top){k = 0;n = hang+1;m = lie+1;}while((qipan[n+1][m+1]!=-1)&&(qipan[n+1][m+1]==num||qipan[n+1][m+1]==0)){ int t = qipan[n+1][m+1];if(n==hang&&m==lie){count++;n++;m++;continue;}if(t==0&&k<1){//第一个空白if(qipan[n+2][m+2]!=num){liveRight = true;break;}k++;n++;m++;}elseif(t==0&&k>0){//第二个空白liveRight = true;break;}else{//黑子n++;m++;count++;}}return jieguo(liveLeft,liveRight,count,k,num);}publicint jieguo(boolean left,boolean right,int count,int k,int num){ if(count==1){return 0;}elseif(count==2){if(left&&right){if(k==0){if(num==2){return 60;}else{return 50;}}else{if(num==2){return 40;}else{return 35;}}}elseif(!left&&!right){return 0;}else{return 10;}}elseif(count==3){if(left&&right){if(k==0){if(num==2){return 950;}else{return 700;}}else{if(num==2){return 900;}else{return 650;}}}elseif(!left&&!right){return 0;}else{return 100;}}elseif(count==4){if(left&&right){if(k==0){if(num==2){return 6000;}else{return 3500;}}else{if(num==2){return 5000;}else{return 3000;}}}elseif(!left&&!right){return 0;}else{if(k==0){if(num==2){return 4000;}else{return 800;}}else{if(num==2){return 3600;}else{return 750;}}}}else{if(k==0){if(num==2){return 20000;}else{return 15000;}}else{if(num==2){return 10000;}else{return 3300;}}}}publicvoid showMe(){frame.setSize(530,600);Toolkit kit = Toolkit.getDefaultToolkit();Dimension screenSize = kit.getScreenSize();int width = screenSize.width;int height = screenSize.height;int x = (int)(width-600)/2;int y = (int)(height-530)/2-50;frame.setLocation(x,y);frame.setVisible(true);frame.setResizable(false);frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); }publicstaticvoid main(String[] args) {new PlayerVsPC().showMe();}publicboolean panduan(int n,int m){if(heng(n,m)||shu(n,m)||zuoxie(n,m)||youxie(n,m)){ returntrue;}returnfalse;}publicboolean heng(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i][j-1]==qipan[n+1][m+1]){ j--;}while(qipan[i][j+1]==qipan[n+1][m+1]){ count++;j++;}if(count>4){returntrue;}returnfalse;}publicboolean shu(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i-1][j]==qipan[n+1][m+1]){ i--;}while(qipan[i+1][j]==qipan[n+1][m+1]){ count++;i++;}if(count>4){returntrue;}returnfalse;}publicboolean youxie(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i-1][j-1]==qipan[n+1][m+1]){ i--;j--;}while(qipan[i+1][j+1]==qipan[n+1][m+1]){ count++;i++;j++;}if(count>4){returntrue;}returnfalse;}publicboolean zuoxie(int n,int m){int i=n+1,j=m+1;int count=1;while(qipan[i+1][j-1]==qipan[n+1][m+1]){i++;j--;}while(qipan[i-1][j+1]==qipan[n+1][m+1]){count++;i--;j++;}if(count>4){returntrue;}returnfalse;}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
private String[] strmode={"人机对弈","人人对弈"};
public static boolean iscomputer=true;
public static boolean checkcomputer=true;
mp=new MainPanel(cm);
Container con=this.getContentPane();
con.add(mp,"Center");
this.setResizable(false);
this.addWindowListener(new ChessWindowEvent());
r.addActionListener((ActionListener)target);
return r;
}
public void MapSize(int w,int h){
setSize(w * 20+50 , h * 20+100 );
if(!ChessFrame.checkcomputer) {
else if(item instanceof JMenuItem)
r = (JMenuItem)item;
else
return null;
if(target instanceof ActionListener)
r.addActionListener((ActionListener)target);
MapSize(20,15);
JMenuBar mbar = new JMenuBar();
this.setJMenuBar(mbar);
JMenu gameMenu = new JMenu("游戏");
mbar.add(makeMenu(gameMenu, new Object[] {
"开局", "棋盘","模式", null, "退出"
private int width,height;
private ChessModel cm;
private MainPanel mp;
//构造五子棋游戏的主窗体
public ChessFrame() {
this.setTitle("五子棋游戏");
cm=new ChessModel(1);
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
else if(arg.equals("Motif"))
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");
*并启动屏幕显示显示该实例对象。
**/
public class FiveChessAppletDemo {
public static void main(String args[]){
ChessFrame cf = new ChessFrame();
cf.setVisible(true);
this.width=30;
this.height=20;
cm=new ChessModel(2);
MapSize(this.width,this.height);
SwingUtilities.updateComponentTreeUI(this);
}
if(arg.equals("40x30")){
this.width=20;
this.height=15;
cm=new ChessModel(1);
MapSize(this.width,this.height);
SwingUtilities.updateComponentTreeUI(this);
}
if(arg.equals("30x20")){
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
}
public void restart(){
int modeChess = cm.getModeChess();
if(modeChess <= 3 && modeChess >= 1){
cm = new ChessModel(modeChess);
MapSize(cm.getWidth(),cm.getHeight());
rmenu=makeRadioButtonMenuItem(strmode[h],target);
if(h==0)
rmenu.setSelected(true);
jm.add(rmenu);
group.add(rmenu);
}
m.add(jm);
}else
m.add(makeMenuItem(items[i], target));
五子棋游戏源代码.txt33学会宽容,意味着成长,秀木出木可吸纳更多的日月风华,舒展茁壮而更具成熟的力量。耐力,是一种不显山石露水的执着;是一种不惧风不畏雨的坚忍;是一种不图名不图利的忠诚。 JAVA期末课题实践考察--五子棋游戏设计
import java.awt.Color;
for (int j=0;j<strsize.length;j++){
rmenu=makeRadioButtonMenuItem(strsize[j],target);
if (j==0)
rmenu.setSelected(true);
jm.add(rmenu);
group.add(rmenu);
r = new JRadioButtonMenuItem((String)item);
else if(item instanceof JRadioButtonMenuItem)
r = (JRadioButtonMenuItem)item;
else
return null;
if(target instanceof ActionListe.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
else
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel" );
SwingUtilities.updateComponentTreeUI(this);
}catch(Exception ee){}
if(arg.equals("20x15")){
mbar.add(makeMenu(helpMenu, new Object[] {
"关于"
}, this));
}
//构造五子棋游戏的主菜单
public JMenu makeMenu(Object parent, Object items[], Object target){
JMenu m = null;
}else{
System.out.println("\u81EA\u5B9A\u4E49");
}
}
public void actionPerformed(ActionEvent e){
String arg=e.getActionCommand();
try{
if (arg.equals("Windows"))
}
}
/*
*类ChessFrame主要功能是创建五子棋游戏主窗体和菜单
**/
class ChessFrame extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 2183726320279905885L;
this.width=40;
this.height=30;
cm=new ChessModel(3);
}, this));
JMenu lookMenu =new JMenu("视图");
mbar.add(makeMenu(lookMenu,new Object[] {
"Metal","Motif","Windows"
},this));