五子棋游戏代码(Java语言)
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(){}}。
双人五子棋的Java源代码

第一个文件:import javax.swing.*;import java.awt.event.*;import java.awt.*;/*五子棋-主框架类, 程序启动类*/public class StartChessJFrame extends JFrame {private ChessBoard chessBoard;//对战面板private JPanel toolbar;//工具条面板private JButton startButton, backButton, exitButton;//重新开始按钮,悔棋按钮,和退出按钮private JMenuBar menuBar;//菜单栏private JMenu sysMenu;//系统菜单private JMenuItem startMenuItem, exitMenuItem, backMenuItem;//重新开始,退出,和悔棋菜单项public StartChessJFrame() {setTitle("单机版五子棋");//设置标题chessBoard = new ChessBoard();//初始化面板对象// 创建和添加菜单menuBar = new JMenuBar();//初始化菜单栏sysMenu = new JMenu("系统");//初始化菜单startMenuItem = new JMenuItem("重新开始");exitMenuItem = new JMenuItem("退出");backMenuItem = new JMenuItem("悔棋");//初始化菜单项sysMenu.add(startMenuItem);//将三个菜单项添加到菜单上sysMenu.add(backMenuItem);sysMenu.add(exitMenuItem);MyItemListener lis = new MyItemListener();//初始化按钮事件监听器内部类this.startMenuItem.addActionListener(lis);//将三个菜单项注册到事件监听器上backMenuItem.addActionListener(lis);exitMenuItem.addActionListener(lis);menuBar.add(sysMenu);//将系统菜单添加到菜单栏上setJMenuBar(menuBar);// 将menuBar设置为菜单栏toolbar = new JPanel();//工具面板栏实例化startButton = new JButton("重新开始");//三个按钮初始化backButton = new JButton("悔棋");exitButton = new JButton("退出");toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));//将工具面板按钮用FlowLayout布局toolbar.add(startButton);//将三个按钮添加到工具面板上toolbar.add(backButton);toolbar.add(exitButton);startButton.addActionListener(lis);//将三个按钮注册监听事件backButton.addActionListener(lis);exitButton.addActionListener(lis);add(toolbar, BorderLayout.SOUTH);//将工具面板布局到界面"南"方也就是下面add(chessBoard);//将面板对象添加到窗体上setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置界面关闭事件//setSize(800,800);pack(); // 自适应大小}private class MyItemListener implements ActionListener {//事件监听器内部类public void actionPerformed(ActionEvent e) {Object obj = e.getSource(); // 取得事件源if (obj == StartChessJFrame.this.startMenuItem || obj == startButton) {// 重新开始// JFiveFrame.this内部类引用外部类System.out.println("重新开始...");chessBoard.restartGame();} else if (obj == exitMenuItem || obj == exitButton) {System.exit(0); // 结束应用程序} else if (obj == backMenuItem || obj == backButton) { // 悔棋System.out.println("悔棋...");chessBoard.goback();}}}public static void main(String[] args) {StartChessJFrame f = new StartChessJFrame(); // 创建主框架f.setVisible(true); // 显示主框架}}第二个文件:import java.awt.Color;/*五子棋的棋子设计。
五子棋JAVA源代码

五子棋Java实现代码import java.awt.*;import java.awt.event.*;import java.applet.Applet;import java.awt.Color;public class WUZIQI extends Applet implements ActionListener, MouseListener, MouseMotionListener, ItemListener {int color = 0;// 棋子的颜色标识0:白子1:黑子boolean isStart = false;// 游戏开始标志int bodyArray[][] = new int[16][16]; // 设置棋盘棋子状态0 无子1 白子2 黑子Button b1 = new Button("游戏开始");Button b2 = new Button("重新开始");Label lblWin = new Label(" ");Checkbox ckbHB[] = new Checkbox[2];CheckboxGroup ckgHB = new CheckboxGroup();public void init() {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);gameInit();this.resize(new Dimension(450,350));}public void itemStateChanged(ItemEvent e) {if (ckbHB[0].getState()) // 选择黑子先还是白子先{color = 0;}else {color= 1;}}public void actionPerformed(ActionEvent e) {if (e.getSource() == b1) {gameStart();}else {reStart();}}public void mousePressed(MouseEvent e) {}public void mouseClicked(MouseEvent e) {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;setDown(x1, y1);}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseDragged(MouseEvent e) {}public void mouseMoved(MouseEvent e) {}public void paint(Graphics g) {g.setColor(Color.pink);g.fill3DRect(10, 10, 300, 300, true);g.setColor(Color.black);for (int i = 1; i < 16; i++) {g.drawLine(20, 20 * i, 300, 20 * i);g.drawLine(20 * i, 20, 20 * i, 300);}}public void setDown(int x, int y) // 落子{if (!isStart) // 判断游戏未开始{return;}if (bodyArray[x / 20][y / 20] != 0) {return;}Graphics g = getGraphics();if (color == 1)// 判断黑子还是白子{g.setColor(Color.black);color = 0;}else {g.setColor(Color.white);color = 1;}g.fillOval(x - 10, y - 10, 20, 20);bodyArray[x / 20][y / 20] = color + 1;if (gameWin1(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}if (gameWin2(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}if (gameWin3(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}if (gameWin4(x / 20, y / 20)) // 判断输赢{lblWin.setText(startColor(color) + "赢了!");isStart = false;}}public String startColor(int x) {if (x == 0) {return "黑子";}else {return "白子";}}public void gameStart() // 游戏开始{isStart = true;enableGame(false);b2.setEnabled(true);}public void gameInit() // 游戏开始初始化{isStart = false;enableGame(true);b2.setEnabled(false);ckbHB[0].setState(true);for (int i = 0; i < 16; i++) {for (int j = 0; j < 16; j++) {bodyArray[i][j] = 0;}}lblWin.setText("");}public void reStart() // 游戏重新开始{repaint();gameInit();}public void enableGame(boolean e) // 设置组件状态{b1.setEnabled(e);b2.setEnabled(e);ckbHB[0].setEnabled(e);ckbHB[1].setEnabled(e);}public boolean gameWin1(int x, int y) // 判断输赢横{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1 + i][y1] == bodyArray[x][y]) {t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;}if (bodyArray[x1 - i][y1] == bodyArray[x][y]) {t += 1;}else {break;}}if (t > 4) {return true;}else {return false;}}public boolean gameWin2(int x, int y) // 判断输赢竖{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1][y1 + i] == bodyArray[x][y]) {t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;if (bodyArray[x1][y1 - i] == bodyArray[x][y]) {t += 1;}else {break;}}if (t > 4) {return true;}else {return false;}}public boolean gameWin3(int x, int y) // 判断输赢左斜{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1 + i][y1 - i] == bodyArray[x][y]) { t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;}if (bodyArray[x1 - i][y1 + i] == bodyArray[x][y]) { t += 1;}else {break;}}if (t > 4) {return true;else {return false;}}public boolean gameWin4(int x, int y) // 判断输赢左斜{int x1, y1, t = 1;x1 = x;y1 = y;for (int i = 1; i < 5; i++) {if (x1 > 15) {break;}if (bodyArray[x1 + i][y1 + i] == bodyArray[x][y]) {t += 1;}else {break;}}for (int i = 1; i < 5; i++) {if (x1 < 1) {break;}if (bodyArray[x1 - i][y1 - i] == bodyArray[x][y]) {t+=1;}else {break;}}if (t > 4) {return true;}else {return false;}}}。
从eclipse控制台输入的五子棋Java代码

package com.五子棋.code;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Code2 {String[][] s=new String[15][15];boolean flag=true;public void f4(){for(int i=0;i<s.length;i++){for(int j=0;j<s[i].length;j++){s[i][j]="╋";System.out.print(s[i][j]);}System.out.println();}}public boolean f1(int x,int y){if((x>=0&&x<15)&&(y>=0&&y<15)){if(s[x][y]=="☻"||s[x][y]=="○"){return false;}return true;}return false;}public void f2(int x,int y){boolean b=f1(x,y);if(b==true){f3(x,y);}else{System.out.println("输入格式不正确或重复,请重新输入");}}public void f3(int x,int y){for(int i=0;i<s.length;i++){for(int j=0;j<s[i].length;j++){if(i==x&&j==y){if(flag==true){s[x][y]="☻";flag=false;}else{s[x][y]="○";flag=true;}}System.out.print(s[i][j]);}System.out.println();}if(f5(x,y,"☻")==1){System.out.println("__________");System.out.println("黑子胜利");return;}else if(f5(x,y,"○")==1){System.out.println("白子胜利");return;}}public int f5(int x,int y,String f){int jact1=0,jact2=0;for(int i=0;i<s.length;i++){for(int j=0;j<s[i].length;j++){//判断横向五子while(s[x][y-jact1]==f&&y-jact1>=0||s[x][y+jact1]==f&&j-jact1<15) {jact1++;if(jact1==5){System.out.println("11111111111");return 1;}}//判断横向左右两边五子jact1=0;jact2=0;while((s[x][y-jact1]==f)&&(y-jact1>=0)){jact1++;while(s[x][y+jact2]==f&&(y+jact2<15)){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("2222222222222222");return 1;}}jact1=0;jact2=0;//判断竖向五子while(s[x-jact1][y]==f&&x-jact1>=0||s[x+jact1][y]==f&&j+jact1<15){jact1++;if(jact1==5){System.out.println("3333333333333");return 1;}}//判断竖向上下五子jact1=0;jact2=0;while((s[x-jact1][y]==f)&&(x-jact1>=0)){jact1++;while(s[x+jact2][y]==f&&(x+jact2<15)){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("4444444444444444444");return 1;}}//判断左上方五子jact1=0;jact2=0;while(s[x-jact1][y-jact1]==f&&(y-jact1>=0)&&(x-jact1>=0)){jact1++;if(jact1==5){System.out.println("55555555555555555555");return 1;}}//判断左边斜向上下五子jact1=0;jact2=0;while(s[x-jact1][y-jact1]==f&&y-jact1>=0&&y-jact1>=0){jact1++;while(s[x+jact2][y+jact2]==f&&y+jact2<15&&x-jact2<15){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("666666666666666");return 1;}}//判断右上方五子jact1=0;jact2=0;while(s[x+jact1][y+jact1]==f&&(y-jact1<15)&&(x-jact1<15)){jact1++;if(jact1==5){System.out.println("77777777777777");return 1;}}//判断右边斜向上下五子jact1=0;jact2=0;while(s[x+jact1][y-jact1]==f&&y-jact1>=0&&x+jact1<15){jact1++;while(s[x-jact2][y+jact2]==f&&y+jact2<15&&x-jact2>=0){jact2++;if(jact2==5){break;}}if(jact1+jact2==6){System.out.println("888888888888888888888");return 1;}}}}return 0;}public static void main(String [] args){Code2 co=new Code2();co.f4();System.out.println("是否开始游戏【yes】开始");BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String str=null;try {while((str=br.readLine())!=null){if("yes".equals(str)){System.out.println("黑子先手-请输入坐标(0~15的数字,不含15)");String t1,t2;while((t1=br.readLine())!=null){System.out.println("+++++++++++++++");t2=br.readLine();int a1=Integer.parseInt(t1);int a2=Integer.parseInt(t2);co.f2(a1,a2);System.out.println("----------");}}else{System.out.println("****************");}}} catch (IOException e) {e.printStackTrace();}}}。
简单的五子棋java游戏代码

package day17.gobang;import java.util.Arrays;public class GoBangGame {public static final char BLANK='*';public static final char BLACK='@';public static final char WHITE='O';public static final int MAX = 16;private static final int COUNT = 5;//棋盘private char[][] board;public GoBangGame() {}//开始游戏public void start() {board = new char[MAX][MAX];//把二维数组都填充‘*’for(char[] ary: board){Arrays.fill(ary, BLANK);}}public char[][] getChessBoard(){return board;}public void addBlack(int x, int y) throws ChessExistException{ //@//char blank = '*';//System.out.println( x +"," + y + ":" + board[y][x] + "," + BLANK); if(board[y][x] == BLANK){// x, y 位置上必须是空的才可以添棋子board[y][x] = BLACK;return;}throw new ChessExistException("已经有棋子了!");}public void addWhite(int x, int y)throws ChessExistException{if(board[y][x] == BLANK){// x, y 位置上必须是空的才可以添棋子board[y][x] = WHITE;return;}throw new ChessExistException("已经有棋子了!");}//chess 棋子:'@'/'O'public boolean winOnY(char chess, int x, int y){//先找到y方向第一个不是blank的棋子int top = y;while(true){if(y==0 || board[y-1][x]!=chess){//如果y已经是棋盘的边缘,或者的前一个不是chess//就不再继续查找了break;}y--;top = y;}//向回统计所有chess的个数,如果是COUNT个就赢了int count = 0;y = top;while(true){if(y==MAX || board[y][x]!=chess){//如果找到头或者下一个子不是chess 就不再继续统计了break;}count++;y++;}return count==COUNT;}//chess 棋子:'@'/'O'public boolean winOnX(char chess, int x, int y){//先找到x方向第一个不是blank的棋子int top = x;while(true){if(x==0 || board[y][x-1]!=chess){//如果x已经是棋盘的边缘,或者的前一个不是chess//就不再继续查找了break;}x--;top = x;}//向回统计所有chess的个数,如果是COUNT个就赢了int count = 0;x = top;while(true){if(x==MAX || board[y][x]!=chess){//如果找到头或者下一个子不是chess 就不再继续统计了break;}count++;x++;}return count==COUNT;}//chess 棋子:'@'/'O'public boolean winOnXY(char chess, int x, int y){//先找MAX向第一个不是blank的棋子int top = y;int left = x;while(true){if(x==0 || y==0 || board[y-1][x-1]!=chess){//如果x已经是棋盘的边缘,或者的前一个不是chess//就不再继续查找了break;}x--;y--;top = y;left=x;}//向回统计所有chess的个数,如果是COUNT个就赢了int count = 0;x = left;y = top;while(true){if(x==MAX || y==MAX || board[y][x]!=chess){//如果找到头或者下一个子不是chess 就不再继续统计了break;}count++;x++;y++;}return count==COUNT;}//chess 棋子:'@'/'O'public boolean winOnYX(char chess, int x, int y){//先找到x方向第一个不是blank的棋子int top = y;int left = x;while(true){if(x==MAX-1 || y==0 || board[y-1][x+1]!=chess){//如果x已经是棋盘的边缘,或者的前一个不是chess//就不再继续查找了break;}x++;y--;top = y;left=x;}//向回统计所有chess的个数,如果是COUNT个就赢了int count = 0;x = left;y = top;while(true){if(x==0 || y==MAX || board[y][x]!=chess){//如果找到头或者下一个子不是chess 就不再继续统计了break;}count++;x--;y++;}return count==COUNT;}public boolean whiteIsWin(int x, int y) {//在任何一个方向上赢了,都算赢return winOnY(WHITE, x, y) ||winOnX(WHITE, x, y) ||winOnXY(WHITE, x, y) ||winOnYX(WHITE, x, y);}public boolean blackIsWin(int x, int y) {return winOnY(BLACK, x, y) ||winOnX(BLACK, x, y) ||winOnXY(BLACK, x, y) ||winOnYX(BLACK, x, y);}}。
五子棋源代码-Java_Applet小程序

五子棋源代码-Java_Applet小程序importjava.applet.Applet; importjava.awt.*;importjava.util.Random;public class wzq extends Applet implements Runnable{public void stop(){LoopThread = null;}privateintCalcZi(inti, int j, byte byte0){CXY cxy = new CXY(); int k = 0;int l = 0;do{int i1 = 0;int j1 = 0;do{cxy.x = i;cxy.y = j;if(MoveAGrid(cxy, l + 4 * j1) &&QiPan[cxy.x][cxy.y] == byte0) do{ if(QiPan[cxy.x][cxy.y] == 0 || QiPan[cxy.x][cxy.y] != byte0) break;i1++;} while(MoveAGrid(cxy, l + 4 * j1));}while(++j1 < 2);if(i1 > k)k = i1;}while(++l < 4);return ++k;}privatebooleanCanDo(){return steps < ((GRIDSUM * GRIDSUM) / 100) * 80;}//电脑下棋privateintCPUDo(CXY cxy, byte byte0){intai[] = new int[2];int ai1[] = new int[2];int ai2[] = new int[2];boolean flag = false;EnterTimes++;ai2[0] = 0;for(inti = recLU.x; i<= recRD.x; i++){for(int k = recLU.y; k <= recRD.y; k++){int l = 0;if(QiPan[i][k] == 0){DoAStep(i, k, byte0);l = CalcCPU(i, k, byte0);}if(l > 0){int i1 = 0;byte byte1;if(byte0 == 1)byte1 = 2; elsebyte1 = 1; if(EnterTimes<= level && steps < ((GRIDSUM * GRIDSUM) / 100) * 80)i1 = CPUDo(cxy, byte1);l += i1;if(l + Math.abs(rd.nextInt()) % 5 > ai2[0] || !flag){ai[0] = i;ai1[0] = k;ai2[0] = l;flag = true;}QiPan[i][k] = 0;}}}if(EnterTimes<= 1){cxy.x = ai[0];cxy.y = ai1[0];int j = 0;do{try{Thread.sleep(300L);}catch(InterruptedException _ex) { } QiPan[cxy.x][cxy.y] = byte0;repaint();try{Thread.sleep(300L);}catch(InterruptedException _ex) { } QiPan[cxy.x][cxy.y] = 0; repaint(); }while(++j < 2);}EnterTimes--;return ai2[0];}public void ClearPan(){for(inti = 0; i< GRIDSUM; i++){for(int j = 0; j < GRIDSUM; j++) QiPan[i][j] = 0;}scHong = 0;scHei = 0;steps = 0;recLU.x = 8;recRD.x = 9;recLU.y = 8;recRD.y = 9;}privatebooleanMoveAGrid(CXY cxy, inti){boolean flag = false;i %= 8;int j = cxy.x + oAdd[i][0]; int k = cxy.y + oAdd[i][1]; if(j >= 0 && j < GRIDSUM && k >= 0 && k < GRIDSUM){cxy.x = j;cxy.y = k;flag = true;}return flag;}public void paint(Graphics g){super.paint(g);for(inti = 0; i< GRIDSUM + 1; i++){g.drawLine(0, i * GRIDWIDTH, GRIDSUM * GRIDWIDTH, i * GRIDWIDTH);g.drawLine(i * GRIDWIDTH, 0, i * GRIDWIDTH, GRIDSUM * GRIDWIDTH);}for(int j = 0; j < GRIDSUM; j++){for(int k = 0; k < GRIDSUM; k++) drawQi(g, j, k, QiPan[j][k]);}}private void CPUInit(){PosAdd[0][0] = 8;PosAdd[0][1] = -2;PosAdd[1][0] = -2;PosAdd[0][2] = 3;PosAdd[2][0] = 3;PosAdd[0][3] = 2;PosAdd[3][0] = 2; PosAdd[1][1] = -7; PosAdd[1][2] = -1; PosAdd[2][1] = -1; PosAdd[1][3] = -1; PosAdd[3][1] = -1;PosAdd[2][2] = 4; PosAdd[3][3] = 4; PosAdd[2][3] = 4; PosAdd[3][2] = 4;}public void mouseDOWNThis(Event event){if(playerdo)xiazi.put(event.x, event.y);}privateintDoAStep(inti, int j, byte byte0){if(QiPan[i][j] != 0 || byte0 == 0 || byte0 > 2){return 0;}else{QiPan[i][j] = byte0; return 1;}}private void FreshRec(inti, int j){if(i - recLU.x< 2){recLU.x = i - 2;if(recLU.x< 0)recLU.x = 0;}if(recRD.x - i< 2){recRD.x = i + 2;if(recRD.x>= GRIDSUM) recRD.x = GRIDSUM - 1; }if(j - recLU.y< 2){recLU.y = j - 2;if(recLU.y< 0)recLU.y = 0;}if(recRD.y - j < 2){recRD.y = j + 2;if(recRD.y>= GRIDSUM) recRD.y = GRIDSUM - 1;}}publicwzq(){GRIDWIDTH = 18;GRIDSUM = 18; QiPan = new byte[GRIDSUM][GRIDSUM];oAdd = new int[8][2]; playing = false;playerdo = true;xy = new CXY();xiazi = new CXiaZi(); rd = new Random(); recLU = new CXY(); recRD = new CXY(); PosAdd = new int[4][4];}public void update(Graphics g){paint(g);}//画棋public void drawQi(Graphics g, inti, int j, int k){switch(k){case 0: // '\0'g.clearRect(i * GRIDWIDTH + 1, j * GRIDWIDTH + 1, GRIDWIDTH -2,GRIDWIDTH - 2);return;case 1: // '\001'g.setColor(Color.red);g.fillArc(i * GRIDWIDTH + 2, j * GRIDWIDTH + 2, GRIDWIDTH -4,GRIDWIDTH - 4, 0, 360);return;case 2: // '\002'g.setColor(Color.black);break;}g.fillArc(i * GRIDWIDTH + 2, j * GRIDWIDTH + 2, GRIDWIDTH -4,GRIDWIDTH - 4, 0, 360);}public void start(){if(LoopThread == null)LoopThread = new Thread(this, "wbqloop"); LoopThread.setPriority(1);LoopThread.start();}public void run(){for(; Thread.currentThread() == LoopThread; xiazi.get(xy)) {ClearPan();repaint();playing = true;//谁先下随机who = (byte)(Math.abs(rd.nextInt()) % 2 + 1); for(passes = 0; playing && passes < 2;){if(who == 1){lblStatus.setText("\u7EA2\u65B9\u4E0B");lblStatus.setForeground(Color.red);}else{lblStatus.setText("\u9ED1\u65B9\u4E0B");lblStatus.setForeground(Color.black);}if(steps < ((GRIDSUM * GRIDSUM) / 100) * 80){passes = 0;if(who == 1) //人下棋{xiazi.get(xy);for(; DoAStep(xy.x, xy.y, who) == 0; xiazi.get(xy)); scHong = CalcZi(xy.x, xy.y, who); FreshRec(xy.x, xy.y); steps++;}else //机器下棋{if(scHong == 0 &&scHei == 0){ xy.x = 9;xy.y = 9;} else{ CPUDo(xy, who);} for(; DoAStep(xy.x, xy.y, who) == 0; CPUDo(xy, who)); scHei = CalcZi(xy.x, xy.y, who); FreshRec(xy.x, xy.y); steps++;}}else{passes = 2;}if(scHong>= 5 || scHei>= 5) playing = false; repaint();//交换下棋方who = (byte)((1 - (who - 1)) + 1); Thread.yield(); }if(scHong>= 5) //红方胜{Status = "\u7EA2\u65B9\u80DC!";lblStatus.setForeground(Color.red); LoseTimes++; }else if(scHei>= 5)//黑方胜{Status = "\u9ED1\u65B9\u80DC!";lblStatus.setForeground(Color.black);if(LoseTimes> 0)LoseTimes--;}else //平局{Status = "\u4E0D\u5206\u80DC\u8D1F!";}lblStatus.setText(Status); repaint();}}//入口,开始下棋,初始化public void init() {super.init(); LoopThread = null; oAdd[0][0] = 0; oAdd[0][1] = -1; oAdd[1][0] = 1; oAdd[1][1] = -1; oAdd[2][0] = 1; oAdd[2][1] = 0; oAdd[3][0] = 1; oAdd[3][1] = 1; oAdd[4][0] = 0; oAdd[4][1] = 1; oAdd[5][0] = -1; oAdd[5][1] = 1; oAdd[6][0] = -1; oAdd[6][1] = 0; oAdd[7][0] = -1; oAdd[7][1] = -1; CPUInit();setLayout(null);resize(325, 352);lblStatus = new Label("Welcome"); lblStatus.setFont(new Font("Dialog", 1, 14));add(lblStatus);lblStatus.reshape(14, 332, 175, 15);lblLevel = new Label("JAVA\u4E94\u5B50\u68CB");lblLevel.setFont(new Font("Dialog", 1, 14));add(lblLevel);lblLevel.reshape(196, 332, 119, 15);}publicbooleanhandleEvent(Event event){if(event.id != 501 || event.target != this){returnsuper.handleEvent(event);}else{mouseDOWNThis(event);return true;}}privateintCalcCPU(inti, int j, byte byte0){CXY cxy = new CXY();String s = "";String s2 = "";String s4 = ""; byte byte1 = 0;CalcTimes++;if(byte0 == 1)byte1 = 2; elseif(byte0 == 2)byte1 = 1; int k = 0;int l = 0;do{int i1 = 0;String s1 = "";String s3 = "";String s5 = ""; int j1 = 0;do{int k1 = 0;cxy.x = i;for(cxy.y = j; MoveAGrid(cxy, l + 4 * j1) && k1 < 6 &&QiPan[cxy.x][cxy.y] != byte1; k1++) if(QiPan[cxy.x][cxy.y] == byte0) {if(j1 == 0)s3 += "1"; elses5 = "1" + s5; i1++;}elseif(j1 == 0)s3 += "0"; elses5 = "0" + s5;if(j1 == 0)s3 += "2";elses5 = "2" + s5;}while(++j1 < 2);i1++;s1 = s5 + "1" + s3;if(s1.indexOf("11111") != -1)i1 += 1000;elseif(s1.indexOf("011110") != -1)i1 += 500;elseif(s1.indexOf("211110") != -1 || s1.indexOf("011112") != -1 || s1.indexOf("01110") != -1 || s1.indexOf("01110") != -1 ||s1.indexOf("011010")!= -1 || s1.indexOf("010110") != -1 || s1.indexOf("11101") != -1 || s1.indexOf("10111") != -1 ||s1.indexOf("11011") != -1)i1 += 100;elseif(s1.indexOf("21110") != -1 || s1.indexOf("01112") != -1 ||s1.indexOf("0110") != -1 || s1.indexOf("211010") != -1 ||s1.indexOf("210110")!= -1)i1 += 20;if(l == 1 || l == 3)i1 += (i1 * 20) / 100;k += i1;}while(++l < 4); if(CalcTimes<= 1)k += CalcCPU(i, j, byte1);elseif(k > 10)k -= 10; CalcTimes--;return k;}int GRIDWIDTH; //网格宽度int GRIDSUM; //网格总数byte QiPan[][]; //棋盘intoAdd[][];Thread LoopThread;intscHong; //红方intscHei; //黑方byte who; //byte winner; //赢方boolean playing; booleanplayerdo; CXY xy;CXiaZixiazi; //下子String Status; //状态Random rd; //随机数 int passes;int steps;intLoseTimes;CXY recLU;CXY recRD; intPosAdd[][]; int level; intEnterTimes; intCalcTimes;Label lblStatus;Label lblLevel; }classCXiaZi{public synchronized void get(CXY cxy) {ready = false;notify();while(!ready)try{wait();}catch(InterruptedException _ex) { }ready = false;notify();cxy.x = xy.x;cxy.y = xy.y;}public synchronized void put(inti, int j){if(i< GRIDWIDTH * GRIDSUM && j < GRIDWIDTH * GRIDSUM) {xy.x = i / GRIDWIDTH; xy.y = j / GRIDWIDTH; ready = true; notify();}}publicCXiaZi(){GRIDWIDTH = 18;GRIDSUM = 18; xy = new CXY();ready = false;}private CXY xy;privateboolean ready; privateint GRIDWIDTH; privateint GRIDSUM; } class CXY{public CXY(){x = 0;y = 0;}publicint x; publicint y; }内部资料,请勿外传~。
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);}}。
简单JAVA五子棋代码1详解

简单JA V A五子棋代码只需要建两个类就可以了1.MainFrame类继承JFrame类2.MainPanel类继承JPanel类实现接口MouseListener两个类详细代码如下MainFrame类,如下:package game.gobang;import java.awt.BorderLayout;import java.awt.Color;import javax.swing.JFrame;/*** 五子棋*/public class MainFrame extends JFrame{public static void main(String[] args) {M ainPanel panel = new MainPanel();MainFrame frame = new MainFrame("五子棋");frame.setSize(680,680);panel.setBackground(Color.GRAY);frame.add(panel,BorderLayout.CENTER);panel.addMouseListener(panel);frame.setVisible(true);}public MainFrame(){s uper();}public MainFrame(String str){s uper(str);}}MainPanel类如下:package game.gobang;import java.awt.Color;import java.awt.Graphics;import java.awt.Panel;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JOptionPane;/*** 五子棋的面板设计*/public class MainPanel extends Panel implements MouseListener{ private static final int COLUMN = 16;//列数private static final int ROW = 16;//行数private static final int GAP = 40;//间距private static boolean isBlack = true;// 判断是否是黑棋private static int click_X;private static int click_Y;private char[][] allChess= new char[ROW][COLUMN];// 存下了旗子的位置public MainPanel(){super();for(int i=0;i<allChess.length;i++){for(int j=0;j<allChess[i].length;j++){allChess[i][j]='*';// 初始化数组allChess,*表示没有棋子存在}}}public void paint(Graphics g){f or(int i=0;i<ROW;i++){//划横线g.setColor(Color.BLACK);g.drawLine(20, 20+i*GAP, 640-20, 20+i*GAP);// 棋盘间隔分布}f or(int i=0;i<COLUMN;i++){//划纵线g.setColor(Color.BLACK);g.drawLine(20+i*GAP, 20, 20+i*GAP, 640-20);}f or(int i=0;i<allChess.length;i++){for(int j=0;j<allChess[i].length;j++){if(allChess[i][j]=='~'){g.setColor(Color.WHITE);g.fillOval(5+i*40, 5+j*40, 30, 30);g.drawOval(5+i*40, 5+j*40, 30, 30);}if(allChess[i][j]=='!'){g.setColor(Color.BLACK);g.fillOval(5+i*40, 5+j*40, 30, 30);g.drawOval(5+i*40, 5+j*40, 30, 30);}}}}public boolean isWin(int x,int y,boolean isColor){//判断是否为5个相同的棋子,是返回true,否返回falsec har ch=allChess[x][y];/* 横向判断 */i nt RLastX = x;w hile(RLastX>=0 && allChess[RLastX][y]==ch){//横向判断是否到达5个相同的棋子RLastX --;}int RNum = 0;//统计横向相同的棋子数RLastX ++;w hile(RLastX<allChess.length && allChess[RLastX][y]==ch){//横向判断是否到达5个相同的棋子RNum ++;RLastX ++;}/* 纵向判断 */i nt LLastY = y;w hile(LLastY>=0 && allChess[x][LLastY]==ch){//纵向判断是否到达5个相同的棋子LLastY --;}i nt LNum = 0;//统计纵向相同的棋子数L LastY ++;w hile(LLastY<allChess[x].length && allChess[x][LLastY]==ch){//纵向判断是否到达5个相同的棋子LLastY ++;LNum ++;}/* 左下右上判断 */i nt LDLastX = x;i nt RULastY = y;w hile(LDLastX>=0 && RULastY<allChess.length &&allChess[LDLastX][RULastY]==ch){// 横向判断有多少个连在一起了LDLastX --;RULastY ++;}i nt LDNum = 0;L DLastX ++;R ULastY --;w hile(LDLastX<allChess.length && RULastY>=0 &&allChess[LDLastX][RULastY]==ch){LDNum ++;LDLastX ++;RULastY --;}/* 左上右下判断 */i nt RULastX = x;i nt LDLastY = y;w hile(RULastX>=0 && LDLastY>=0 && allChess[RULastX][LDLastY]==ch){ RULastX --;LDLastY --;}i nt RUNum = 0;R ULastX ++;L DLastY ++;w hile(RULastX>=0 && LDLastY<allChess.length &&allChess[RULastX][LDLastY]==ch){RULastX ++;LDLastY ++;RUNum ++;}i f(RNum>=5||LNum>=5||RUNum>=5||LDNum>=5){return true;}r eturn false;}public void mouseClicked(MouseEvent e) {/ / 鼠标按下时候画出棋子}public void mousePressed(MouseEvent e) {//鼠标点击事件处理过程//获取点击坐标位置int click_x = e.getX();int click_y = e.getY();int chess_x = Math.round((float)(click_x-20)/GAP);int chess_y = Math.round((float)(click_y-20)/GAP);//获取点击后的坐标位置click_X = chess_x;click_Y = chess_y;if(isBlack==true&&allChess[chess_x][chess_y]=='*'){allChess[chess_x][chess_y] = '!';isBlack = false;}if(isBlack==false&&allChess[chess_x][chess_y]=='*'){allChess[chess_x][chess_y] = '~';isBlack = true;}System.out.println(e.getX());System.out.println(e.getY());repaint();for(int j=0;j<16;j++){f or(int i=0;i<16;i++){System.out.print(allChess[i][j]+" ");}S ystem.out.println();}System.out.println();if(isWin(chess_x,chess_y,isBlack)){S ystem.out.println("你赢了");}if(isWin(chess_x,chess_y,isBlack)){i f(isBlack){JOptionPane.showMessageDialog(null,"白子赢了");}else{JOptionPane.showMessageDialog(null,"黑子赢了");}System.exit(0);}}public void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}public void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}public void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}public void setAllChess(char[][] allChess) {this.allChess = allChess;}public char[][] getAllChess() {return allChess;}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
五子棋游戏代码(Java语言)import java.awt.*;import java.awt.event.*;import javax.swing.*;class mypanel extends Panel implements MouseListener {int chess[][] = new int[11][11];boolean Is_Black_True;mypanel(){Is_Black_True=true;for(int i=0;i<11;i++){for(int j=0;j<11;j++){chess[i][j] = 0;}}addMouseListener(this);setBackground(Color.RED);setBounds(0, 0, 360, 360);setVisible(true);}public void mousePressed(MouseEvent e){int x = e.getX();int y = e.getY();if(x < 25 || x > 330 + 25 ||y < 25 || y > 330+25){return;}if(chess[x/30-1][y/30-1] != 0){return;}if(Is_Black_True==true){chess[x/30-1][y/30-1] = 1;Is_Black_True=false;repaint();Justisewiner();return;}if(Is_Black_True==false){chess[x/30-1][y/30-1]=2;Is_Black_True=true;repaint();Justisewiner();return;}}void Drawline(Graphics g){for(int i=30;i<=330;i+=30){for(int j = 30;j <= 330; j+= 30){g.setColor(Color.GREEN);g.drawLine(i, j, i, 330);}}for(int j = 30;j <= 330;j+=30){g.setColor(Color.GREEN);g.drawLine(30, j, 330, j);}}void Drawchess(Graphics g){for(int i=0;i < 11;i++){for(int j = 0;j < 11;j++){if(chess[i][j] == 1){g.setColor(Color.BLACK);g.fillOval((i+1)*30-8, (j+1)*30-8, 16, 16);}if(chess[i][j]==2){g.setColor(Color.WHITE);g.fillOval((i+1)*30-8, (j + 1) * 30-8, 16, 16);}}}void Justisewiner(){int black_count = 0;int white_count = 0;int i = 0;for(i=0;i<11;i++) //竖向判断{for(int j=0;j<11;j++){if(chess[i][j]==1){black_count++;if(black_count==5){JOptionPane.showMessageDialog(this, "黑棋胜利");Clear_Chess();return;}}else{black_count=0;}if(chess[i][j]==2){white_count++;if(white_count==5){JOptionPane.showMessageDialog(this, "白棋胜利");Clear_Chess();return;}}else{white_count = 0;}}for(i=0;i<11;i++) //横向判断{for(int j=0;j<11;j++){if(chess[j][i] == 1){black_count++;if(black_count==5){JOptionPane.showMessageDialog(this, "黑棋胜利");Clear_Chess();return;}}else{black_count=0;}if(chess[j][i]==2){white_count++;if(white_count==5){JOptionPane.showMessageDialog(this, "白棋胜利");Clear_Chess();return;}}else{white_count = 0;}}}for(i=0;i<7;i++) //左向右斜判断{for(int j=0;j < 7;j++){for(int k=0;k < 5;k++){if(chess[i+k][j+k]==1){black_count++;if(black_count==5){JOptionPane.showMessageDialog(this, "黑棋胜利");Clear_Chess();return;}}else{black_count=0;}if(chess[i+k][j+k]==2){white_count++;if(white_count==5){JOptionPane.showMessageDialog(this, "白棋胜利");Clear_Chess();return;}}else{white_count=0;}}}}for(i = 4;i < 11;i++) //右向左斜判断{for(int j = 6;j >= 0;j--){for(int k = 0;k < 5;k++){if(chess[i - k][j + k] == 1){black_count++;if(black_count == 5){JOptionPane.showMessageDialog(this, "黑棋胜利");Clear_Chess();return;}}else{black_count = 0;}if(chess[i - k][j + k] == 2){white_count++;if(white_count==5){JOptionPane.showMessageDialog(this, "白棋胜利");Clear_Chess();return;}}else{white_count=0;}}}}}void Clear_Chess(){for(int i=0;i<11;i++){for(int j=0;j<10;j++){chess[i][j]=0;}}repaint();}public void paint(Graphics g){Drawline(g);Drawchess(g);}public void mouseExited(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseReleased(MouseEvent e){}public void mouseClicked(MouseEvent e){}}class myframe extends Frame implements WindowListener {mypanel panel;myframe(){setLayout(null);panel=new mypanel();add(panel);panel.setBounds(0,23, 360, 360);setTitle("单人版五子棋");setBounds(200, 200, 360, 383);setVisible(true);addWindowListener(this);}public void windowClosing(WindowEvent e){System.exit(0);}public void windowDeactivated(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowOpened(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}}public class WuZiQi{public static void main(String argc[]){myframe f=new myframe();}}。