Java五子棋游戏源代码(人机对战)

合集下载

五子棋游戏代码(Java语言)

五子棋游戏代码(Java语言)

五子棋游戏代码(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();}}。

五子棋源代码-Java_Applet小程序

五子棋源代码-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五子棋源代码

java五子棋源代码

package chess;import java.awt.Button;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.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;public class Chess extends JFrame implements MouseListener, Runnable { private static final long serialVersionUID = 1L;int width= Toolkit.getDefaultToolkit().getScreenSize().width;int hight =Toolkit.getDefaultToolkit().getScreenSize().height;// 背景图片BufferedImage bjImage = null;// 保存棋子坐标int x = 0;int y = 0;// 保存之前下过的棋子坐标// 其中数据:0:表示这个点没有棋子 1:表示黑子 2:表示白子int[][] allChess = new int[19][19];// 标识当前是黑棋还是白旗下下一步boolean isBlack = true;// 标识当前游戏是否可以继续boolean canPlay = true;// 保存显示的提示信息String message = "黑方先行";// 保存最多拥有多少时间(秒)int maxTime = 0;// 做倒计时的线程类Thread t = new Thread(this);// 保存黑方与白方的剩余时间int blackTime = 0;int whiteTime = 0;// 保存双方剩余时间的显示信息String blackMessage = "无限制";String whiteMessage = "无限制";@SuppressWarnings("deprecation")public Chess() {this.setTitle("五子棋");this.setSize(500, 500);this.setLocation((width - 500) / 2, (hight - 500) / 2);this.addMouseListener(this);// this.setResizable(false);this.setVisible(true);this.setLayout(null);t.start();t.suspend();// 线程挂起// 刚打开的时候刷新屏幕,防止开始游戏时无法显示的问题this.repaint();this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);try {bjImage = ImageIO.read(newFile("C:\\Users\\cwb\\Desktop\\timg.jpg"));} catch (IOException e) {e.printStackTrace();}}@Overridepublic void paint(Graphics g) {// 双缓存技术防止屏幕闪烁但不知道为什么,使用双缓存技术以后,效果特不好,所以没用,如果使用的话,下面的 g 改为 g2 就可以了//BufferedImage bi=new//BufferedImage(500,500,BufferedImage.TYPE_INT_ARGB);//Graphics g=bi.createGraphics();g.drawImage(bjImage, 0, 20, this);g.setFont(new Font("黑体", Font.BOLD, 20));g.drawString("游戏信息:" + message, 120, 60);g.setFont(new Font("宋体", 0, 14));g.drawString("黑方时间:" + blackMessage, 30, 470);g.drawString("白方时间:" + whiteMessage, 260, 470);g.drawString("开始游戏", 400,100);g.drawString("游戏设置", 400,150);g.drawString("游戏说明", 400,200);g.drawString("认输", 400,300);g.drawString("关于", 400,350);g.drawString("退出", 400,400);// 绘制棋盘for (int i = 0; i < 19; i++) {g.drawLine(10, 70 + 20 * i, 370, 70 + 20 * i);g.drawLine(10 + 20 * i, 70, 10 + 20 * i, 430); }// 标注小圆点位g.fillOval(68, 128, 4, 4);g.fillOval(308, 128, 4, 4);g.fillOval(308, 368, 4, 4);g.fillOval(68, 368, 4, 4);g.fillOval(188, 128, 4, 4);g.fillOval(68, 248, 4, 4);g.fillOval(188, 368, 4, 4);g.fillOval(188, 248, 4, 4);g.fillOval(308, 248, 4, 4);// //绘制棋子// x=(x-10)/20*20+10; //是为了取得交叉点的坐标// y=(y-70)/20*20+70;// //黑子// g.fillOval(x-7, y-7, 14, 14);// //白子// g.setColor(Color.BLACK);// g.fillOval(x-7, y-7, 14, 14);// g.setColor(Color.BLACK);// g.drawOval(x-7, y-7, 14, 14);// 输出数组中所有数值// 绘制全部棋子for (int i = 0; i < 19; i++) {for (int j = 0; j < 19; j++) {if (allChess[i][j] == 1) {// 黑子int tempX = i * 20 + 10;int tempY = j * 20 + 70;g.fillOval(tempX-7, tempY-7 ,14, 14);}if (allChess[i][j] == 2) {// 白子int tempX = i * 20 + 10;int tempY = j * 20 + 70;g.setColor(Color.WHITE);g.fillOval(tempX- 7, tempY- 7, 14, 14);g.setColor(Color.BLACK);g.drawOval(tempX- 7, tempY- 7, 14, 14);}}}}@Overridepublic void mouseClicked(MouseEvent e) {}private boolean checkWin() {boolean flag = false;// 保存共有多少相同颜色棋子相连int count = 1;// 判断横向特点:allChess[x][y]中y值相同int color = allChess[x][y];// 判断横向count = this.checkCount(1, 0, color);if (count >= 5) {flag = true;} else {// 判断纵向count = this.checkCount(0, 1, color);if (count >= 5) {flag = true;} else {// 判断右上左下count = this.checkCount(1, -1, color);if (count >= 5) {flag = true;} else {// 判断左下右上count = this.checkCount(1, 1, color);if (count >= 5) {flag = true;}}}}return flag;}// 判断棋子连接数量private int checkCount(int xChange, int yChange, int color) { int count = 1;int tempX = xChange;int tempY = yChange;while (x + xChange >= 0 && x + xChange <= 18 && y + yChange >= 0&& y + yChange <= 18&& color == allChess[x + xChange][y + yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}xChange = tempX;yChange = tempY;while (x - xChange >= 0 && x - xChange <= 18 && y - yChange >= 0&& y - yChange <= 18&& color == allChess[x - xChange][y - yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}return count;}@Overridepublic void mouseEntered(MouseEvent arg0) {}@Overridepublic void mouseExited(MouseEvent arg0) {}@SuppressWarnings("deprecation")@Overridepublic void mousePressed(MouseEvent e) {if (canPlay == true) {x = e.getX();y = e.getY();if (x >= 10 && x <= 370 && y >= 70 && y <= 430) {// System.out.println("在棋盘范围内:"+x+"--"+y);x = (x - 10) / 20; // 是为了取得交叉点的坐标y = (y - 70) / 20;if (allChess[x][y] == 0) {// 判断当前要下的是什么棋子if (isBlack == true) {allChess[x][y] = 1;isBlack = false;message = "轮到白方"; } else {allChess[x][y] = 2;isBlack = true;message = "轮到黑方"; }// 判断这个棋子是否和其他棋子连成5个boolean winFlag =this.checkWin();if (winFlag == true) { JOptionPane.showMessageDialog(this, "游戏结束,"+ (allChess[x][y] == 1 ? "黑方" : "白方") + "获胜!");canPlay = false;}} else {JOptionPane.showMessageDialog(this, "当前位子已经有棋子,请重新落子!!!");}this.repaint();}}// 点击开始游戏按钮if(e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 70 && e.getY() <= 100) {int result =JOptionPane.showConfirmDialog(this, "是否重新开始游戏?");if (result == 0) {// 现在重新开始游戏// 重新开始所要做的操作:1)把棋盘清空,allChess数组中全部数据归0;// 2)游戏相关信息显示初始化// 3)将下一步下棋改为黑方for (int i = 0; i < 19; i++) {for (int j = 0; j < 19; j++) {allChess[i][j] = 0; }}// 另一种方式 allChess=newint[19][19]message = "黑方先行";isBlack = true;blackTime = maxTime;whiteTime = maxTime;if (maxTime > 0) {blackMessage= maxTime/ 3600 +":"+ (maxTime / 60 - maxTime / 3600 * 60) + ":"+ (maxTime - maxTime / 60 * 60);whiteMessage= maxTime/ 3600 + ":"+ (maxTime / 60 - maxTime / 3600 * 60) + ":"+ (maxTime - maxTime / 60 * 60);t.resume();} else {blackMessage = "无限制";whiteMessage = "无限制";}this.repaint();// 如果不重新调用,则界面不会刷新}}// 点击游戏设置按钮if(e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 120 && e.getY() <= 150) {String input = JOptionPane.showInputDialog("请输入游戏的最多时间(单位:分钟),如果输入0 ,表示没有时间限制");try {maxTime= Integer.parseInt(input) * 60;if (maxTime < 0) {JOptionPane.showMessageDialog(this, "请正确提示信息,不允许输入负数"); }if (maxTime == 0) {int result =JOptionPane.showConfirmDialog(this,"设置完成,是否重新开始游戏?");if (result == 0) {// 现在重新开始游戏// 重新开始所要做的操作:1)把棋盘清空,allChess数组中全部数据归0;// 2)游戏相关信息显示初始化// 3)将下一步下棋改为黑方for(int i= 0; i< 19; i++) {for(int j= 0; j < 19; j++) {allChess[i][j] = 0;}}// 另一种方式allChess=new int[19][19]message = "黑方先行";isBlack = true;blackTime = maxTime;whiteTime = maxTime;blackMessage= "无限制";whiteMessage= "无限制";this.repaint();// 如果不重新调用,则界面不会刷新}}if (maxTime > 0) {int result =JOptionPane.showConfirmDialog(this,"设置完成,是否重新开始游戏?");if (result == 0) {// 现在重新开始游戏// 重新开始所要做的操作:1)把棋盘清空,allChess数组中全部数据归0;// 2)游戏相关信息显示初始化// 3)将下一步下棋改为黑方for(int i= 0; i< 19; i++) {for(int j= 0; j < 19; j++) {allChess[i][j] = 0;}}// 另一种方式allChess=new int[19][19]message = "黑方先行";isBlack = true;blackTime = maxTime;whiteTime = maxTime;blackMessage= maxTime / 3600 + ":"+ (maxTime / 60 - maxTime / 3600 * 60) + ":"+ (maxTime - maxTime / 60 * 60);whiteMessage= maxTime / 3600 + ":"+ (maxTime / 60 - maxTime / 3600 * 60) + ":"+ (maxTime - maxTime / 60 * 60);t.resume();this.repaint();// 如果不重新调用,则界面不会刷新}}} catch (NumberFormatException e1) {JOptionPane.showMessageDialog(this, "请正确提示信息");}}// 点击游戏说明按钮if(e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 170 && e.getY() <= 200) {JOptionPane.showMessageDialog(this,"这是一个五子棋游戏程序,黑白双方轮流下棋,当某一方连到五子时,游戏结束。

java开发实现五子棋游戏

java开发实现五子棋游戏

java开发实现五⼦棋游戏本⽂实例为⼤家分享了java实现五⼦棋游戏的具体代码,供⼤家参考,具体内容如下此游戏具有双⼈对战功能和⼈机对战功能⼀、游戏界⾯的实现⼀个游戏⾸先从设计界⾯开始1、⾸先创建⼀个类,作⽤是通过对窗体组件的⼀些设置来实现简单游戏界⾯public void gameUI(){//窗体组件MyFrame jf = new MyFrame();jf.setSize(900, 800);jf.setTitle("冷丁-五⼦棋");//居中显⽰jf.setLocationRelativeTo(null);//设置退出进程jf.setDefaultCloseOperation(3);//流式布局管理器FlowLayout flow=new FlowLayout();jf.setLayout(flow);//边框布局BorderLayout border=new BorderLayout();jf.setLayout(border);//⾯板: JPanel 默认流式布局JPanel eastPanel=new JPanel();Dimension dm=new Dimension(100,0);//除了JFrame,其他组件设置⼤⼩都是该⽅法eastPanel.setPreferredSize(dm);jf.add(eastPanel,BorderLayout.EAST);}2、加⼊功能按钮JButton jbu=new JButton("开始");eastPanel.add(jbu,BorderLayout.EAST);JButton jbu2=new JButton("悔棋");eastPanel.add(jbu2,BorderLayout.EAST);JButton jbu3=new JButton("认输");eastPanel.add(jbu3,BorderLayout.EAST);JButton jbu4=new JButton("⼈机对战");eastPanel.add(jbu4,BorderLayout.EAST);//设置窗体可见jf.setVisible(true);每个按钮添加ActionListner监听jbu.addActionListener(mouse);jbu2.addActionListener(mouse);jbu3.addActionListener(mouse);jbu4.addActionListener(mouse);在GameMouse类中对过对actionPerformed⽅法的重新来判断当前是哪个按钮按下,并实现对应的功能public void actionPerformed(ActionEvent e) {//获取按钮上的内容String name=e.getActionCommand();System.out.println("点击按钮:"+name);if(name.equals("开始")){jf.removeMouseListener(this);jf.addMouseListener(this);startflag=false;flag=false;gameOver=false;for(int i=0;i<15;i++){for(int j=0;j<15;j++){}jf.paint(gr);}else if(name.equals("悔棋")){arrChess[nowx][nowy]=0;jf.paint(gr);this.flag=!this.flag;}else if(name.equals("认输")){if(this.flag){gr.setColor(Color.red);gr.setFont(new Font("TimesRoman", Font.BOLD, 50));gr.drawString("⿊⽅获胜!",300,300);}else{gr.setColor(Color.red);gr.setFont(new Font("TimesRoman", Font.BOLD, 50));gr.drawString("⽩⽅获胜!",300,300);}}else if(name.equals("⼈机对战")){jf.removeMouseListener(this);jf.addMouseListener(this);startflag=false;flag=false;gameOver=false;for(int i=0;i<15;i++){for(int j=0;j<15;j++){arrChess[i][j]=0;}}this.aiflag=true;jf.paint(gr);}}3、游戏效果是通过画笔画在组件上实现的,获取画笔:图形显⽰在哪个组件上,画笔就从该组件上获取。

五子棋代码(人机对战)

五子棋代码(人机对战)

import java.applet.*;import java.awt.*;import java.awt.event.*;import java.applet.Applet;import java.awt.Color;public class wuziqi extends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListe ner{int color_Qizi=0;//旗子的颜色标识0:白子1:黑子int intGame_Start=0;//游戏开始标志0未开始1游戏中int intGame_Body[][]=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);Game_start_csh();}public void itemStateChanged(ItemEvent e){if (ckbHB[0].getState()) //选择黑子先还是白子先{color_Qizi=0;}else{color_Qizi=1;}}public void actionPerformed(ActionEvent e){Graphics g=getGraphics();if (e.getSource()==b1){Game_start();}else{Game_re();}}public void mousePressed(MouseEvent e){}public void mouseClicked(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);}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){draw_qipan(g);}。

java五子棋网络版源代码加分析

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代码(可打印修改)

五子棋人机对战java代码(可打印修改)
3
int tempy=j*24+58; g.drawImage(whiteImage1, tempx, tempy, 15, 15, this); } } } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { if(canplay) { x=e.getX(); y=e.getY(); if(x>=18&&x<=379&&y>=58&&y<=580) { x=(x-18)/24; y=(y-58)/24; //判断该坐标是否有棋子,没有则放棋子,有则显示已经有棋子对话框 if(allqz[x][y]==0) { //玩家鼠标点击的坐标设置为放黑子标志 allqz[x][y]=1; message="白方走棋"; this.repaint(); boolean Winflag=this.Win(); if(Winflag) { JOptionPane .showMessageDialog(this, "游戏结束:"+(allqz[x] [y]==1?"黑方胜":"白方胜")); canplay=false; } if(canplay) { //电脑通过最优算法获得最能够阻止玩家的黑棋成为5连得坐标x,y 并把这个坐标设置为放白子标记 //allqz[x][y]=2;
//把棋盘清空---将allqz[][]全部数据清零 allqz=new int[15][15]; //将游戏信息提示变回出示位置 message="黑方先行"; this.repaint(); } } if(e.getX()>=401&&e.getX()<=469&&e.getY()>=151&&e.getY()<=179) { JOptionPane.showMessageDialog(this, "这是一个简易五子棋游戏,玩家 持黑棋,电脑持白棋,"); JOptionPane.showMessageDialog(this, "任一方先在棋盘上形成横向、竖 向、斜向的连续的相同颜色的五个(含五个以上)棋子的一方为胜!"); } if(e.getX()>=401&&e.getX()<=469&&e.getY()>=252&&e.getY()<=280) {

五子棋人机对战源代码

五子棋人机对战源代码

#include "stdafx.h"#include "FiveStone.h"#include "FiveKernel.h"#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif//////////////////////////////////////////////////////////////////////// Construction/Destruction////////////////////////////////////////////////////////////////////// FiveKernel::FiveKernel(){const char * readstring[9]={"长连","五","活四","冲四","活三","冲三","活二","可能为五","不可能为五"};int ItemNum;FILE * f;//read opentable filef=fopen("openlib.txt","r");fscanf(f,"%3x\n", &ItemNum);int j;for (int i=0;i<ItemNum;i++){fscanf(f, "%3x: %8x\n", &j, &OpenT able[i]);};fclose(f);//read valuetable filef=fopen("valuelib.txt","r");char str1[5], str2[10], str[2][11];for (i=0;i<3281;i++){ValueT able[i][0]=0;ValueT able[i][1]=0;}for (i=0;i<6561;i++){fscanf(f, "%s %s %s %s\n\n", str1, str2, str[0], str[1]);for (j=0;j<2;j++){for (int k=0;k<9;k++){if (strcmp(str[j],readstring[k])==0){if (i<=3280){ValueT able[i][j]+=(k+1)*16; //k+1 because value can not be 0 }if (i>=3280){ValueT able[6560-i][j]+=(k+1);break;}}}}fclose(f);Result=rsNotPlayed;}FiveKernel::~FiveKernel(){}bool FiveKernel::NewGame(HARDLEVEL hardlevel, RULE rule){if (Result==rsNotOut){if (IDYES!=MessageBox(GetActiveWindow(), "Are you sure to cancel the curre nt game?","New game",MB_YESNO)){return false;}}HardLevel=hardlevel;Rule=rule;HandLimit=(rule!=rlNormal);Result=rsNotOut;int i,j;//initialize Boardfor (i=0;i<16;i++){for (j=0;j<16;j++){Board[i][j]=vlCanBeFive*16+vlCanBeFive;}}StepNum=0;Turn=tnBlackTurn;return true;}bool FiveKernel::InputChess(POS pos){if((_ValidPos(pos))&&((Board[pos.x][pos.y]>>4)>=1)&&(Result==rsNotOut)){ BYTE value=(Turn==tnBlackTurn)?((Board[pos.x][pos.y]>>4)):((Board[pos.x][pos.y]&0x0f));if (value==vlHandLimit){MessageBox(GetActiveWindow(), "Invalid chess!","Hand limit",MB_OK); return false;_GoAStep(pos);return true;}else return false;}bool FiveKernel::OutputChess(POS * pos) {if (Result!=rsNotOut){return false;}if (StepNum==0){pos->x=7;pos->y=7;_GoAStep(*pos);return true;}if (_SearchInLib(pos)){_GoAStep(*pos);return true;}if (_ThinkOut(pos)){_GoAStep(*pos);return true;}return false;}bool FiveKernel::Retract(POS * pos){if ((Result==rsNotOut)&&(StepNum>0)){int i, j;StepNum--;//initialize Board and TurnTurn=tnBlackTurn;for (i=0;i<16;i++){for (j=0;j<16;j++){Board[i][j]=vlCanBeFive*16+vlCanBeFive; }}//place each chess stored in StepTablefor (i=0;i<StepNum;i++){_PlaceChess(&Board, StepTable[i], Turn); Turn=_GetOtherTurn(Turn);}}return true;}bool FiveKernel::GetResult(RESULT * result) {*result=Result;return (Result==rsNotPlayed)?false:true;}bool FiveKernel::GetBoard(BOARD * board) {if (Result==rsNotPlayed) return false;for (int i=0;i<16;i++){for (int j=0;j<16;j++){(*board)[i][j]=Board[i][j];}}return true;}bool FiveKernel::GetTurn(TURN * turn){if (Result==rsNotOut){*turn=Turn;return true;}else return false;}bool FiveKernel::GetLastPos(POS * pos) {if (StepNum>1){*pos=StepT able[StepNum-1];return true;}else return false;}//convert x and y to POSPOS FiveKernel::_Pos(BYTE x, BYTE y){POS pos;pos.x=x;pos.y=y;return pos;}//NOTICE: This routine has no error check void FiveKernel::_GoAStep(POS pos){StepT able[StepNum]=pos;StepNum++;BYTE value=(Turn==tnBlackTurn)?((Board[pos.x][pos.y]>>4)):((Board[pos.x][pos.y]&0x0f));if (value==vlFive){Result=(Turn==tnBlackTurn)?rsBlackWin:rsWhiteWin;}else if (StepNum==225){Result=rsDraw;}else{Board[pos.x][pos.y]=_Chess(Turn);bool CanBeDraw=true;for (int i=0;i<15;i++){for (int j=0;j<15;j++){BYTE value1=Board[i][j]>>4, value2=Board[i][j]&0x0f;if ((value1>0)&&(((value1!=vlHandLimit)&&(value1!=vlNoUse))||(value2!=vlNoUse))) CanBeDraw=false; }}if (CanBeDraw) Result=rsDraw;}_PlaceChess(&Board, pos, Turn);Turn=_GetOtherTurn(Turn);}TURN FiveKernel::_GetOtherTurn(TURN turn){return !turn;}//NOTICE: This routine has no error checkvoid FiveKernel::_PlaceChess(BOARD * board, POS pos, TURN turn) {(*board)[pos.x][pos.y]=_Chess(turn);BYTE i1=(pos.x>=4)?pos.x-4:0;BYTE i2=(pos.x<=10)?pos.x+4:14;BYTE j1=(pos.y>=4)?pos.y-4:0;BYTE j2=(pos.y<=10)?pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if (((*board)[i][j]>>4)==0) continue;(*board)[i][j]=_PosValue(board, _Pos(i, j));}}}PLACE FiveKernel::_Chess(TURN turn){return (turn==tnBlackTurn?plBlackChess:plWhiteChess);}bool FiveKernel::_ValidPos(POS pos){return (pos.x>=0)&&(pos.x<15)&&(pos.y>=0)&&(pos.y<15);}bool FiveKernel::_SearchInLib(POS * pos){POS FoundPosT able[255];BYTE FoundPosNum=0;unsigned long x, y, z;int j=0;for (int i=0;i<StepNum;i++){x=StepT able[i].x;y=StepT able[i].y;z=x<<4|y;while ((OpenTable[j]&0xff000000)!=(z*0x1000000)){if ((OpenT able[j]&0xfff)==0xfff){return false;}else j=OpenT able[j]&0xfff;}if ((OpenTable[j]&0xfff000)==0xfff000) return false;j=(OpenT able[j]&0xfff000)/0x1000;if (i==StepNum-1){do{z=(OpenT able[j]&0xff000000)/0x1000000;x=z>>4;y=z&0x0f;FoundPosT able[FoundPosNum++]=_Pos((BYTE)x, (BYTE)y);j=OpenTable[j]&0xfff;} while (j!=0xfff);int RandomNum=-1;while ((RandomNum<0)||(RandomNum>=FoundPosNum)) RandomNum=rand();*pos=FoundPosTable[RandomNum];return true;}}return false;}bool FiveKernel::_ThinkOut(POS * pos){const BYTE ValueRank[2][16]={{0,0,255,253,100,100,100,100,1,1,253,100,100,0,0,0},{0,100,254,100,100,100,100,100,1,1,100,100,100,0,0,0},};const long ValueScore[2][16]={{0,0,10000000,200000,2000,1000,200,100,10,1,100000,10000,200000,0, 0,0},{0,1,1000000, 40000, 200, 100 ,20 ,10, 1, 1,40000, 2000, 20000, 0,0,0} };struct{POS Pos;long Score;}Prob[225];BYTE FoundNum=0;BYTE BestRank=0;BYTE value[2];BYTE ownrank, otherrank, temprank;long tempscore;int i, j;for (i=0;i<15;i++){for (j=0;j<15;j++){value[0]=Board[i][j]>>4;value[1]=Board[i][j]&0x0f;//if the place have chess then continueif (value[0]==0) continue;if (Turn==tnBlackTurn){ownrank=ValueRank[0][value[0]];otherrank=ValueRank[1][value[1]];tempscore=ValueScore[0][value[0]]+ValueScore[1][value[1]];}else{ownrank=ValueRank[0][value[1]];otherrank=ValueRank[1][value[0]];tempscore=ValueScore[0][value[1]]+ValueScore[1][value[0]];}if (ownrank==0) temprank=0;else temprank=(ownrank>otherrank)?ownrank:otherrank;if (temprank>BestRank){BestRank=temprank;FoundNum=1;Prob[0].Pos=_Pos(i,j);Prob[0].Score=tempscore;}else if(temprank==BestRank){int k=FoundNum;while ((k>=1)&&(Prob[k-1].Score<tempscore)){Prob[k]=Prob[k-1];k--;}Prob[k].Pos=_Pos(i,j);Prob[k].Score=tempscore;FoundNum++;}}}int w1=0;while ((w1<FoundNum)&&(Prob[w1].Score==Prob[0].Score)) w1++;int w2=rand()%w1;POS temppos=Prob[w2].Pos;Prob[w2].Pos=Prob[0].Pos;Prob[0].Pos=temppos;if (BestRank>100){*pos=Prob[0].Pos;return true;}if ((HardLevel==hlBeginner)&&(rand()%4==0)||(HardLevel==hlAmateur)&&(rand()%4!=0)){if (_CanWinByFour(&Board, pos, Turn, 6, false)) return true;if (_CanWinByFour(&Board, pos, Turn, 6, true)) return true;if (_CanWinByThree(&Board, pos, Turn, 2)) return true;}bool OtherCanWinFour_ThreeEnable=false;bool OtherCanWinFour_ThreeDisable=false;bool OtherCanWinThree=false;if (HardLevel==hlExpert){if (_CanWinByFour(&Board, pos, Turn, 6, false)) return true;POS OtherWinPos;if (_CanWinByFour(&Board, &OtherWinPos, _GetOtherTurn(Turn), 6, false)) OtherCanWinFour_ThreeDisable=true;else{if (_CanWinByFour(&Board, pos, Turn, 6, true)) return true;if (_CanWinByFour(&Board, &OtherWinPos, _GetOtherTurn(Turn), 6, true)) OtherCanWinFour_ThreeEnable=true;else{if (_CanWinByThree(&Board, pos, Turn, 2)) return true;if (_CanWinByThree(&Board, &OtherWinPos, _GetOtherTurn(Turn), 2)) OtherCanWinThree=true;}}}const char DirDis[8][2]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};BYTE SaveC;char SaveX, SaveY;char tempx, tempy;BYTE tempvalue;for (int t=0;t<FoundNum;t++){SaveX=Prob[t].Pos.x;SaveY=Prob[t].Pos.y;SaveC=Board[SaveX][SaveY];if (Turn==tnBlackTurn)Prob[t].Score=2*ValueScore[0][SaveC&0x0f]-ValueScore[1][SaveC>>4];else Prob[t].Score=2*ValueScore[0][SaveC>>4]-ValueScore[1][SaveC&0x0f]; Board[SaveX][SaveY]=_Chess(Turn);for (i=0;i<8;i++){for (j=1;j<=4;j++){tempx=SaveX+j*DirDis[i][0];tempy=SaveY+j*DirDis[i][1];if (_ValidPos(_Pos(tempx, tempy))&&((Board[tempx][tempy]>>4)>=1)){ tempvalue=Board[tempx][tempy];if (Turn==tnBlackTurn)Prob[t].Score-=(ValueScore[1][tempvalue>>4]-ValueScore[0][tempvalu e&0x0f]);else Prob[t].Score-=(ValueScore[1][tempvalue&0x0f]-ValueScore[0][tempva lue>>4]);tempvalue=_PosValue(&Board, _Pos(tempx, tempy));if (Turn==tnBlackTurn)Prob[t].Score+=(ValueScore[1][tempvalue>>4]-ValueScore[0][tempvalu e&0x0f]);else Prob[t].Score+=(ValueScore[1][tempvalue&0x0f]-ValueScore[0][tempva lue>>4]);}}}Board[SaveX][SaveY]=SaveC;int k=t;POS temppos=Prob[t].Pos;tempscore=Prob[t].Score;while ((k>=1)&&(Prob[k-1].Score<tempscore)){Prob[k]=Prob[k-1];k--;}Prob[k].Pos=temppos;Prob[k].Score=tempscore;}w1=0;while ((w1<FoundNum)&&(Prob[w1].Score==Prob[0].Score)) w1++;w2=rand()%w1;temppos=Prob[w2].Pos;Prob[w2].Pos=Prob[0].Pos;Prob[0].Pos=temppos;if ((HardLevel==hlBeginner)||(HardLevel==hlAmateur)){*pos=Prob[0].Pos;return true;}if (FoundNum>MaxFoundPosNum) FoundNum=MaxFoundPosNum;BOARD tempboard;temppos;for (t=0;t<FoundNum;t++){memcpy(&tempboard, &Board, sizeof(BOARD));_PlaceChess(&tempboard, Prob[t].Pos, Turn);if (OtherCanWinFour_ThreeDisable){if (!_CanWinByFour(&tempboard, &temppos, _GetOtherTurn(Turn), 6, false)){*pos=Prob[t].Pos;return true;}}else if (OtherCanWinFour_ThreeEnable){if (!_CanWinByFour(&tempboard, &temppos, _GetOtherTurn(Turn), 6, true)){*pos=Prob[t].Pos;return true;}}else if (OtherCanWinThree){if (!_CanWinByThree(&tempboard, &temppos, _GetOtherTurn(Turn), 2)){ *pos=Prob[t].Pos;return true;}}else{if (_CanWinByFour(&tempboard, &temppos, Turn, 6, true)){*pos=Prob[t].Pos;return true;}if (_CanWinByThree(&tempboard, &temppos, Turn, 2)){*pos=Prob[t].Pos;return true;}}}*pos=Prob[0].Pos;return true;}VALUE FiveKernel::_PosDirectionValue(BOARD * board, POS pos, DIR dir) {VALUE blackvalue, whitevalue;const char dis[4][2]={{0,1},{1,1},{1,0},{1,-1}};unsigned int address;int j, k;for (int chess=0;chess<=2;chess+=2){address=0;for (int i=-4;i<=4;i++){if (i==0) continue;j=pos.x+i*dis[dir][0];k=pos.y+i*dis[dir][1];if (_ValidPos(_Pos(j, k))){if ((*board)[j][k]==plBlackChess) address+=(address<<1);else if ((*board)[j][k]==plWhiteChess) address+=(address<<1)+2;else address+=(address<<1)+1;}else{address+=(address<<1)+chess;}}if (address>=3280){if (chess==0){whitevalue=ValueT able[6560-address][0]>>4;}else{if (HandLimit) blackvalue=ValueTable[6560-address][1]&0x0f;else blackvalue=ValueTable[6560-address][0]&0x0f;}}else{if (chess==0){whitevalue=ValueT able[address][0]&0x0f;}else{if (HandLimit) blackvalue=ValueTable[address][1]>>4;else blackvalue=ValueTable[address][0]>>4;}}}return (blackvalue<<4)|whitevalue;}VALUE FiveKernel::_PosValue(BOARD * board, POS pos, TURN turn){BYTE FourNum=0, LiveThreeNum=0;VALUE v, value=vlNoUse;for (int i=0;i<4;i++){v=_PosDirectionValue(board, pos, i);if (turn==tnBlackTurn) v=v>>4; else v=v&0x0f;if (v==vlHandLimit) return vlHandLimit;else value=(v<value)?v:value;if ((v==vlLiveFour)||(v==vlDeadFour)) FourNum++;else if (v==vlLiveThree) LiveThreeNum++;}if (FourNum>=2){if ((HandLimit)&&(turn==tnBlackTurn)) return vlHandLimit;else return (value>vlFive)?vlDoubleFour:value;}if (LiveThreeNum>=2){if ((HandLimit)&&(turn==tnBlackTurn)) return vlHandLimit;else value=vlDoubleLiveThree;}if ((FourNum==1)&&(LiveThreeNum>=1))return (value>vlLiveFour)?vlFourLiveThree:value;return value;}VALUE FiveKernel::_PosValue(BOARD * board, POS pos){VALUE blackvalue, whitevalue;blackvalue=_PosValue(board, pos, tnBlackTurn);whitevalue=_PosValue(board, pos, tnWhiteTurn);return (blackvalue<<4)|whitevalue;}VALUE FiveKernel::_PosDirectionValue(BOARD * board, POS pos, DIR dir, TURN turn){VALUE value;value=_PosDirectionValue(board, pos, dir);return (turn==tnBlackTurn)?value>>4:value&0x0f;}bool FiveKernel::_CanWinByFour(BOARD * board, POS * pos, TURN turn, BYTE depth, bool ThreeEnable){const BYTE ValueRank[16]={0,0,255,254,252,0,0,0,0,0,254,251,253,0,0,0}; _InitStack();_OccupyNode(0);char NowIndex=0;NODE * NowNode=&(Stack[0]);NowNode->father=-1;NowNode->son=-1;NowNode->brother=-1;NowNode->pos=_Pos(-1, -1);BOARD NowBoard;memcpy(&NowBoard, board, sizeof(BOARD));TURN NowTurn=turn;BYTE NowDepth=depth;while (1){BYTE FoundNum=0;POS Prob[225];if (NowTurn==turn){for (BYTE i=0;i<15;i++){for (BYTE j=0;j<15;j++){BYTE tempRank;if (NowTurn==tnBlackTurn) tempRank=ValueRank[NowBoard[i][j]>>4];else tempRank=ValueRank[NowBoard[i][j]&0x0f];if ((tempRank>=253)||((tempRank==251)&&(ThreeEnable))){NowNode->Win=true;if (NowIndex==0) NowNode->pos=_Pos(i, j);goto labelBACK;}else if (tempRank>=252){Prob[FoundNum]=_Pos(i, j);FoundNum++;}}}}else{BYTE i1=(NowNode->pos.x>=4)?NowNode->pos.x-4:0;BYTE i2=(NowNode->pos.x<=10)?NowNode->pos.x+4:14;BYTE j1=(NowNode->pos.y>=4)?NowNode->pos.y-4:0;BYTE j2=(NowNode->pos.y<=10)?NowNode->pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if ((NowBoard[i][j]>>4)==0) continue;BYTE tempRank, tempRank1;if (NowTurn==tnBlackTurn){tempRank=ValueRank[NowBoard[i][j]&0x0f];tempRank1=ValueRank[NowBoard[i][j]>>4];}else{tempRank=ValueRank[NowBoard[i][j]>>4];tempRank1=ValueRank[NowBoard[i][j]&0x0f];}if (tempRank==255){if (tempRank1>=252){NowNode->Win=false;if (NowIndex==0) NowNode->pos=_Pos(i, j);goto labelBACK;}Prob[FoundNum]=_Pos(i, j);FoundNum++;}}}}if ((NowDepth==0)||(FoundNum==0)){NowNode->Win=false;goto labelBACK;}char SonIndex;if (_GetVoidNode(&SonIndex)){NODE * tempNode;char tempIndex;NowNode->son=SonIndex;if (NowTurn==turn) NowNode->Win=false; else NowNode->Win=true; for (short t=0;t<FoundNum;t++){if (_GetVoidNode(&tempIndex)){if (t>0) tempNode->brother=tempIndex;_OccupyNode(tempIndex);tempNode=&(Stack[tempIndex]);tempNode->father=NowIndex;tempNode->son=-1;tempNode->pos=Prob[t];}else break;}tempNode->brother=-1;NowIndex=SonIndex;NowNode=&(Stack[NowNode->son]);_PlaceChess(&NowBoard, NowNode->pos, NowTurn);NowTurn=_GetOtherTurn(NowTurn);NowDepth--;}else{NowNode->Win=false;goto labelBACK;}continue;labelBACK:;NODE * tempNode=NowNode;char tempIndex=NowIndex;while ((NowNode->brother==-1)||(NowTurn==turn)&&(!NowNode->Win) ||(NowTurn!=turn)&&(NowNode->Win)){if (NowNode->father==-1){*pos=NowNode->pos;return NowNode->Win;}else{tempNode=NowNode;NowIndex=NowNode->father;_RemoveChess(&NowBoard, NowNode->pos);NowNode=&(Stack[NowIndex]);NowTurn=_GetOtherTurn(NowTurn);NowDepth++;if (NowTurn==turn){if (tempNode->Win){NowNode->Win=true;if (NowIndex==0) NowNode->pos=tempNode->pos;}}else{if (!tempNode->Win){NowNode->Win=false;if (NowIndex==0) NowNode->pos=tempNode->pos;}}tempIndex=NowNode->son;do {tempNode=&(Stack[tempIndex]);_FreeNode(tempIndex);tempIndex=tempNode->brother;}while (tempIndex!=-1);}}_RemoveChess(&NowBoard, NowNode->pos);NowIndex=NowNode->brother;NowNode=&(Stack[NowIndex]);_PlaceChess(&NowBoard, NowNode->pos, _GetOtherTurn(NowTurn));}return false;}bool FiveKernel::_CanWinByThree(BOARD * board, POS * pos, TURN turn, BYTE depth){const BYTE ValueRank[16]={0,0,255,254,252,250,0,0,0,0,254,251,253,0,0,0};const BYTE OwnFive=255;const BYTE OtherFive=254;const BYTE OwnLiveFour=253;const BYTE OtherLiveFour=252;const BYTE OwnTwoLiveThree=251;_InitStack();_OccupyNode(0);char NowIndex=0;NODE * NowNode=&(Stack[0]);NowNode->father=-1;NowNode->son=-1;NowNode->brother=-1;NowNode->pos=_Pos(-1, -1);BOARD NowBoard;memcpy(&NowBoard, board, sizeof(BOARD));TURN NowTurn=turn;BYTE NowDepth=depth;while (1){BYTE FoundNum=0;typedef struct {POS pos; BYTE rank;} PROB;PROB Prob[225];BYTE BestRank=0;if (NowTurn==turn){for (BYTE i=0;i<15;i++){for (BYTE j=0;j<15;j++){BYTE OwnRank, OtherRank;if (NowTurn==tnBlackTurn){OwnRank=ValueRank[NowBoard[i][j]>>4];OtherRank=ValueRank[NowBoard[i][j]&0x0f];}else{OwnRank=ValueRank[NowBoard[i][j]&0x0f];OtherRank=ValueRank[NowBoard[i][j]>>4];}if (OwnRank==255){BestRank=OwnFive;if (NowIndex==0) NowNode->pos=_Pos(i, j);}if ((OtherRank==255)&&(BestRank<OtherFive)) BestRank=OtherFive;if (((OwnRank==254)||(OwnRank==253))&&(BestRank<OwnLiveFour)){ BestRank=OwnLiveFour;if (NowIndex==0) NowNode->pos=_Pos(i, j);}if (((OtherRank==254)||(OwnRank==253))&&(BestRank<OtherLiveFour)) BestRank=OtherLiveFour;if ((OwnRank==251)&&(BestRank<OwnTwoLiveThree)){BestRank=OwnTwoLiveThree;if (NowIndex==0) NowNode->pos=_Pos(i, j);}if (OwnRank>0){int k=FoundNum;while ((k>=1)&&(Prob[k-1].rank<OwnRank)){Prob[k]=Prob[k-1];k--;}Prob[k].pos=_Pos(i,j);Prob[k].rank=OwnRank;FoundNum++;}}}if (BestRank==OwnFive) {NowNode->Win=true;goto labelBACK;}if (BestRank==OtherFive) {NowNode->Win=false;goto labelBACK;}if (BestRank==OwnLiveFour) {NowNode->Win=true;goto labelBACK;}if (BestRank==OtherLiveFour)while ((FoundNum>0)&&(Prob[FoundNum-1].rank<252)) FoundNum--;if (BestRank==OwnTwoLiveThree) {NowNode->Win=true;goto labelBACK;}}else{BYTE i1=(NowNode->pos.x>=4)?NowNode->pos.x-4:0;BYTE i2=(NowNode->pos.x<=10)?NowNode->pos.x+4:14;BYTE j1=(NowNode->pos.y>=4)?NowNode->pos.y-4:0;BYTE j2=(NowNode->pos.y<=10)?NowNode->pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if ((NowBoard[i][j]>>4)==0) continue;BYTE tempRank;if (NowTurn==tnBlackTurn)tempRank=ValueRank[NowBoard[i][j]&0x0f];else tempRank=ValueRank[NowBoard[i][j]>>4];if ((tempRank>=254)){int k=FoundNum;while ((k>=1)&&(Prob[k-1].rank<tempRank)){Prob[k]=Prob[k-1];k--;}Prob[k].pos=_Pos(i,j);Prob[k].rank=tempRank;FoundNum++;}}}}if ((NowDepth==0)||(FoundNum==0)){NowNode->Win=false;goto labelBACK;}char SonIndex;if (_GetVoidNode(&SonIndex)){NODE * tempNode;char tempIndex;NowNode->son=SonIndex;if (NowTurn==turn) NowNode->Win=false; else NowNode->Win=true; for (short t=0;t<FoundNum;t++){if (_GetVoidNode(&tempIndex)){if (t>0) tempNode->brother=tempIndex;_OccupyNode(tempIndex);tempNode=&(Stack[tempIndex]);tempNode->father=NowIndex;tempNode->son=-1;tempNode->pos=Prob[t].pos;}else break;}tempNode->brother=-1;NowIndex=SonIndex;NowNode=&(Stack[NowNode->son]);_PlaceChess(&NowBoard, NowNode->pos, NowTurn);NowTurn=_GetOtherTurn(NowTurn);NowDepth--;}else{NowNode->Win=false;goto labelBACK;}continue;labelBACK:;NODE * tempNode=NowNode;char tempIndex=NowIndex;while ((NowNode->brother==-1)||(NowTurn==turn)&&(!NowNode->Win) ||(NowTurn!=turn)&&(NowNode->Win)){if (NowNode->father==-1){*pos=NowNode->pos;return NowNode->Win;}else{tempNode=NowNode;NowIndex=NowNode->father;_RemoveChess(&NowBoard, NowNode->pos);NowNode=&(Stack[NowIndex]);NowTurn=_GetOtherTurn(NowTurn);NowDepth++;if (NowTurn==turn){if (tempNode->Win){NowNode->Win=true;if (NowIndex==0) NowNode->pos=tempNode->pos;}}else{if (!tempNode->Win){NowNode->Win=false;if (NowIndex==0) NowNode->pos=tempNode->pos;}}tempIndex=NowNode->son;do {tempNode=&(Stack[tempIndex]);_FreeNode(tempIndex);tempIndex=tempNode->brother;}while (tempIndex!=-1);}}_RemoveChess(&NowBoard, NowNode->pos);NowIndex=NowNode->brother;NowNode=&(Stack[NowIndex]);_PlaceChess(&NowBoard, NowNode->pos, _GetOtherTurn(NowTurn));}return false;}//function _GetVoidNode has no error check//if NodeNum less than MaxNodeNum, there must be one void node at least bool FiveKernel::_GetVoidNode(char * nodeindex){if (SearchedPosNum==MaxSearchPosNum) return false;if (NodeNum==MaxNodeNum) return false;else{char i=0;while (!Stack[i].NodeVoid) i++;*nodeindex=i;SearchedPosNum++;return true;}}//function _FreeNode has no error check//the Node to be free must not be void nodevoid FiveKernel::_FreeNode(char nodeindex){Stack[nodeindex].NodeVoid=true;NodeNum--;}//function _OccupyNode has no error check//the Node to be Occupied must be void nodevoid FiveKernel::_OccupyNode(char nodeindex){Stack[nodeindex].NodeVoid=false;NodeNum++;}void FiveKernel::_InitStack(){NodeNum=0;SearchedPosNum=0;for (unsigned short i=0;i<MaxNodeNum;i++) Stack[i].NodeVoid=true;}void FiveKernel::_RemoveChess(BOARD * board, POS pos){(*board)[pos.x][pos.y]=0xff;BYTE i1=(pos.x>=4)?pos.x-4:0;BYTE i2=(pos.x<=10)?pos.x+4:14;BYTE j1=(pos.y>=4)?pos.y-4:0;BYTE j2=(pos.y<=10)?pos.y+4:14;for (BYTE i=i1;i<=i2;i++){for (BYTE j=j1;j<=j2;j++){if (((*board)[i][j]>>4)==0) continue;(*board)[i][j]=_PosValue(board, _Pos(i, j)); }}}。

Java实现五子棋(附详细源码)

Java实现五子棋(附详细源码)

Java实现五⼦棋(附详细源码)本⽂实例为⼤家分享了Java实现五⼦棋游戏的具体代码,供⼤家参考,具体内容如下学习⽬的:熟悉java中swing类与java基础知识的巩固.(⽂末有源代码⽂件和打包的jar⽂件)效果图:思路:**1.⾸先构建⼀个Frame框架,来设置菜单选项与按钮点击事件。

MyFrame.java⽂件代码如下package StartGame;import javax.swing.ButtonGroup;import javax.swing.Icon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JRadioButtonMenuItem;import java.awt.Color;import ponent;import java.awt.Container;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;//窗体框架类public class MyFrame extends JFrame {// static boolean canPlay1 = false;判断是否可以开始游戏final MyPanel panel = new MyPanel();public MyFrame() {// 设置窗体的⼤⼩并居中this.setSize(500, 600); // 设置窗体⼤⼩this.setTitle("五⼦棋游戏"); // 设置窗体标题int height = Toolkit.getDefaultToolkit().getScreenSize().height;// 获取屏幕的⾼度this.setLocation((width - 500) / 2, (height - 500) / 2); // 设置窗体的位置(居中)this.setResizable(false); // 设置窗体不可以放⼤// this.setLocationRelativeTo(null);//这句话也可以设置窗体居中/** 菜单栏的⽬录设置*/// 设置菜单栏JMenuBar bar = new JMenuBar();this.setJMenuBar(bar);// 添加菜单栏⽬录JMenu menu1 = new JMenu("游戏菜单"); // 实例化菜单栏⽬录JMenu menu2 = new JMenu("设置");JMenu menu3 = new JMenu("帮助");bar.add(menu1); // 将⽬录添加到菜单栏bar.add(menu2);bar.add(menu3);JMenu menu4 = new JMenu("博弈模式"); // 将“模式”菜单添加到“设置”⾥⾯menu2.add(menu4);// JMenuItem item1=new JMenuItem("⼈⼈博弈");// JMenuItem item2=new JMenuItem("⼈机博弈");// 设置“”⽬录下⾯的⼦⽬录JRadioButtonMenuItem item1 = new JRadioButtonMenuItem("⼈⼈博弈");JRadioButtonMenuItem item2 = new JRadioButtonMenuItem("⼈机博弈");// item1按钮添加时间并且为匿名类item1.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsManAgainst(true);panel.Start();item1.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Override// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置item2按钮的事件监听事件,也就是设置⼈机博弈item2.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsManAgainst(false);panel.Start();item2.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置按钮组并把⼈机博弈与⼈⼈博弈添加到⼀个按钮组⾥⾯ButtonGroup bg = new ButtonGroup();bg.add(item1);bg.add(item2);// 将按钮组添加到菜单⾥⾯menu4.add(item2);item2.setSelected(true);// 先⾏设置JMenu menu5 = new JMenu("先⾏设置"); // 将“先⾏设置”菜单添加到“设置”⾥⾯menu2.add(menu5);// 设置⿊⼦先⾏还是⽩字先⾏的按钮JRadioButtonMenuItem item3 = new JRadioButtonMenuItem("⿊⽅先⾏");JRadioButtonMenuItem item4 = new JRadioButtonMenuItem("⽩字先⾏");// 设置item3的⿏标点击事件,设置⿊⽅先⾏item3.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsBlack(true);panel.Start();item3.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置item4的⿏标点击事件item4.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsBlack(false);panel.Start();item4.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置按钮组并把⼈机博弈与⼈⼈博弈添加到⼀个按钮组⾥⾯ButtonGroup bg1 = new ButtonGroup();bg1.add(item3);bg1.add(item4);// 将按钮组添加到菜单⾥⾯menu5.add(item3);menu5.add(item4);item3.setSelected(true);// 设置“帮助”下⾯的⼦⽬录JMenuItem menu6 = new JMenuItem("帮助");menu3.add(menu6);/** 菜单栏的⽬录设置完毕*/// 开始游戏菜单设置JMenuItem menu7 = new JMenuItem("开始游戏");menu1.add(menu7);JMenuItem menu8 = new JMenuItem("重新开始");menu1.add(menu8);menu7.addMouseListener(new MouseListener() {@Override// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubpanel.Start();// panel.repaint();}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}});menu8.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否重新开始", "消息", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.Start();}// panel.repaint();}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}});// 退出游戏选项设置JMenuItem menu9 = new JMenuItem("退出游戏");menu1.add(menu9);menu9.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "退出游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否退出游戏", "消息", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {System.exit(0);// 退出程序}// panel.repaint();}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}// 游戏难度设置JRadioButtonMenuItem item5 = new JRadioButtonMenuItem("傻⽠");// 添加按钮JRadioButtonMenuItem item6 = new JRadioButtonMenuItem("简单");JRadioButtonMenuItem item7 = new JRadioButtonMenuItem("普通");// JRadioButtonMenuItem item8= new JRadioButtonMenuItem("困难");ButtonGroup bg3 = new ButtonGroup();// 设置按钮组bg3.add(item5);bg3.add(item6);bg3.add(item7);// bg3.add(item8);JMenu menu10 = new JMenu("游戏难度设置");// 添加菜单到主菜单menu2.add(menu10);menu10.add(item5);// 添加选项到难度设置菜单menu10.add(item6);menu10.add(item7);// menu2.add(item8);item5.setSelected(true);// 默认选项按钮// 傻⽠难度设置的⿏标点击事件item5.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setGameDifficulty(0);panel.Start();item5.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub});// 简单难度设置模式item6.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "难度设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setGameDifficulty(1);panel.Start();item6.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 普通难度设置item7.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setGameDifficulty(2);panel.Start();item7.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});//游戏帮助提⽰信息menu6.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;};JOptionPane.showMessageDialog(null, "制作⼈员:韩红剑");}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});/** 窗⼝⾥⾯的容器设置*/Container con = this.getContentPane(); // 实例化⼀个容器⽗类con.add(panel); // 将容器添加到⽗类/** 窗⼝⾥⾯的容器设置完毕*/}}2.第⼆步,设置显⽰棋盘的容器,⽂件源代码为MyPanel.java package StartGame;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Panel;import java.awt.Toolkit;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.image.*;import java.io.File;import .URL;import java.util.Arrays;import java.util.Random;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;//设置窗体⾥⾯的容器操作public class MyPanel extends JPanel implements MouseListener, Runnable { private static final Toolkit ResourceUtil = null;public Image boardImg; // 定义背景图⽚static int[][] allChess = new int[15][15]; // 棋盘数组static int[][] temporaryChess = new int[15][15];int x;// 保存棋⼦的横坐标int y;// 保存棋⼦的纵坐标Boolean canPlay = false; // 游戏是否继续,默认为继续Boolean isBlack = true;// 是否是⿊⼦,默认为⿊⼦Boolean isManAgainst = false; // 判断是否是⼈⼈对战String message = "⽤户下棋";Thread t = new Thread(this);int maxTime = 120;int blackTime = 120;int whiteTime = 120;String blackMessage = "⽆限制";String whiteMessage = "⽆限制";static int gameDifficulty = 0;// 设置游戏难度,0为傻⽠模式,1为简单,2为普通,3为困难 // 获取isBlack的值public boolean getIsBlack() {return this.isBlack;}// 设置isBlack的值public void setIsBlack(boolean isBlack) {this.isBlack = isBlack;}// 获取isManAgainst的值public boolean getIsManAgainst() {return this.isManAgainst;}// 获取isManAgainst的值public void setIsManAgainst(boolean isManAgainst) {this.isManAgainst = isManAgainst;}// 获取isManAgainst的值public int getGameDifficulty() {return this.gameDifficulty;}// 设置setGameDifficulty的值public void setGameDifficulty(int gameDifficulty) {this.gameDifficulty = gameDifficulty;}// 构造函数public MyPanel() {boardImg = Toolkit.getDefaultToolkit().getImage("./src/StartGame/fiveCHessBourd.jpg"); this.repaint();// 添加⿏标监视器addMouseListener((MouseListener) this);// addMouseMotionListener((MouseMotionListener) this);// this.requestFocus();t.start();t.suspend();// 线程挂起// t.resume();}// 数据初始化@Overridepublic void paint(Graphics g) {super.paint(g);int imgWidth = boardImg.getWidth(this); // 获取图⽚的宽度int imgHeight = boardImg.getHeight(this); // 获取图⽚的⾼度int FWidth = getWidth();int FHeight = getHeight();String message; // 标记谁下棋int x = (FWidth - imgWidth) / 2;int y = (FHeight - imgHeight) / 2;g.drawImage(boardImg, x, y, null); // 添加背景图⽚到容器⾥⾯g.setFont(new Font("宋体", 0, 14));g.drawString("⿊⽅时间:" + blackTime, 30, 470);g.drawString("⽩⽅时间:" + whiteTime, 260, 470);// 绘制棋盘for (int i = 0; i < 15; i++) {g.drawLine(30, 30 + 30 * i, 450, 30 + 30 * i);g.drawLine(30 + 30 * i, 30, 30 + 30 * i, 450);}// 绘制五个中⼼点g.fillRect(240 - 5, 240 - 5, 10, 10); // 绘制最中⼼的正⽅形g.fillRect(360 - 5, 360 - 5, 10, 10); // 绘制右下的正⽅形g.fillRect(360 - 5, 120 - 5, 10, 10); // 绘制右上的正⽅形g.fillRect(120 - 5, 360 - 5, 10, 10);// 绘制左下的正⽅形g.fillRect(120 - 5, 120 - 5, 10, 10);// 绘制左上的正⽅形// 定义棋盘数组for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {// if (allChess[i][j] == 1) {// // ⿊⼦// int tempX = i * 30 + 30;// int tempY = j * 30 + 30;// g.fillOval(tempX - 7, tempY - 7, 14, 14);// }// if (allChess[i][j] == 2) {// // ⽩⼦// int tempX = i * 30 + 30;// int tempY = j * 30 + 30;// g.setColor(Color.WHITE);// g.fillOval(tempX - 7, tempY - 7, 14, 14);// g.setColor(Color.BLACK);// g.drawOval(tempX - 7, tempY - 7, 14, 14);// }draw(g, i, j); // 调⽤下棋⼦函数}}}// ⿏标点击时发⽣的函数@Overridepublic void mousePressed(MouseEvent e) {// x = e.getX();// 获取⿏标点击坐标的横坐标// y = e.getY();// 获取⿏标点击坐标的纵坐标// if (x >= 29 && x <= 451 && y >= 29 && y <= 451) { // ⿏标点击在棋⼦框⾥⾯才有效 //// }if (canPlay == true) {// 判断是否可以开始游戏x = e.getX(); // 获取⿏标的焦点y = e.getY();if (isManAgainst == true) {// 判断是否是⼈⼈对战manToManChess();} else { // 否则是⼈机对战,⼈机下棋manToMachine();}}}// 判断是否输赢的函数private boolean checkWin(int x, int y) {// TODO Auto-generated method stubboolean flag = false;// 保存共有多少相同颜⾊棋⼦相连int count = 1;// 判断横向特点:allChess[x][y]中y值相同int color = allChess[x][y];// 判断横向count = this.checkCount(x, y, 1, 0, color);if (count >= 5) {flag = true;} else {// 判断纵向count = this.checkCount(x, y, 0, 1, color);if (count >= 5) {flag = true;} else {// 判断右上左下count = this.checkCount(x, y, 1, -1, color);if (count >= 5) {flag = true;} else {// 判断左下右上count = this.checkCount(x, y, 1, 1, color);if (count >= 5) {flag = true;}}}}return flag;}// 判断相同棋⼦连接的个数private int checkCount(int x, int y, int xChange, int yChange, int color) {// TODO Auto-generated method stubint count = 1;int tempX = xChange;int tempY = yChange;while (x + xChange >= 0 && x + xChange <= 14 && y + yChange >= 0 && y + yChange <= 14 && color == allChess[x + xChange][y + yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}xChange = tempX;yChange = tempY;while (x - xChange >= 0 && x - xChange <= 14 && y - yChange >= 0 && y - yChange <= 14 && color == allChess[x - xChange][y - yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}return count;}// 机器⼈判断⿊棋相连的数量private int checkCountMachine(int x, int y, int xChange, int yChange, int color) {// TODO Auto-generated method stubint count = 0;int tempX = xChange;int tempY = yChange;while (x + xChange >= 0 && x + xChange <= 14 && y + yChange >= 0 && y + yChange <= 14 && color == allChess[x + xChange][y + yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}xChange = tempX;yChange = tempY;while (x - xChange >= 0 && x - xChange <= 14 && y - yChange >= 0 && y - yChange <= 14 && color == allChess[x - xChange][y - yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}return count;}public void paintConmponents(Graphics g) {super.paintComponents(g);}// 绘制⿊⽩棋⼦public void draw(Graphics g, int i, int j) {if (allChess[i][j] == 1) {g.setColor(Color.black);// ⿊⾊棋⼦g.fillOval(30 * i + 30 - 7, 30 * j + 30 - 7, 14, 14);g.drawString(message, 230, 20);}if (allChess[i][j] == 2) {g.setColor(Color.white);// ⽩⾊棋⼦g.fillOval(30 * i + 30 - 7, 30 * j + 30 - 7, 14, 14);g.drawString(message, 230, 20);}}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void run() {// TODO Auto-generated method stub// 判断是否有时间限制if (maxTime > 0) {while (true) {// System.out.println(canPlay + "11");if (isManAgainst) {if (isBlack) {blackTime--;if (blackTime == 0) {JOptionPane.showMessageDialog(this, "⿊⽅超时,游戏结束!"); }} else {whiteTime--;if (whiteTime == 0) {JOptionPane.showMessageDialog(this, "⽩⽅超时,游戏结束!"); }}} else {// 监控⿊⼦下棋的时间,也就是⽤户下棋的时间blackTime--;if (blackTime == 0) {JOptionPane.showMessageDialog(this, "⽤户超时,游戏结束!");}// 不监控电脑⽩字下棋}blackMessage = blackTime / 3600 + ":" + (blackTime / 60 - blackTime / 3600 * 60) + ":" + (blackTime - blackTime / 60 * 60);whiteMessage = whiteTime / 3600 + ":" + (whiteTime / 60 - whiteTime / 3600 * 60) + ":" + (whiteTime - whiteTime / 60 * 60);this.repaint();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}// 点击开始游戏设置属性,游戏开始public void Start() {this.canPlay = true;for (int i = 0; i < 14; i++) {for (int j = 0; j < 14; j++) {allChess[i][j] = 0;}}if (canPlay == true) {t.resume();}this.repaint();JOptionPane.showMessageDialog(this, "游戏开始了,请开始下棋");if (isBlack == false && isManAgainst == false) {machineChess(gameDifficulty);}// 另⼀种⽅式 allChess=new int[19][19]// message = "⿊⽅先⾏";//// isBlack = true;// blackTime = maxTime;// whiteTime = maxTime;// if (maxTime > 0) {// blackMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600// * 60) + ":"// + (maxTime - maxTime / 60 * 60);// whiteMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600// * 60) + ":"// + (maxTime - maxTime / 60 * 60);// t.resume();// } else {// blackMessage = "⽆限制";// whiteMessage = "⽆限制";// }// this.repaint();// 如果不重新调⽤,则界⾯不会刷新}// ⼈⼈对战下棋函数public void manToManChess() {if (x >= 29 && x <= 451 && y >= 29 && y <= 451) {// System.out.println("在棋盘范围内:"+x+"--"+y);x = (x + 15) / 30 - 1; // 是为了取得交叉点的坐标y = (y + 15) / 30 - 1;if (allChess[x][y] == 0) {// 判断当前要下的是什么棋⼦if (isBlack == true) {allChess[x][y] = 1;isBlack = false;blackTime = 120;message = "轮到⽩⽅";} else {allChess[x][y] = 2;isBlack = true;whiteTime = 120;message = "轮到⿊⽅";}}// 判断这个棋⼦是否和其他棋⼦连成5个boolean winFlag = this.checkWin(x, y);this.repaint(); // 绘制棋⼦if (winFlag == true) {JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "⿊⽅" : "⽩⽅") + "获胜!"); canPlay = false;}} else {// JOptionPane.showMessageDialog(this,// "当前位⼦已经有棋⼦,请重新落⼦");}}// ⼈机对战下棋函数public void manToMachine() {if (x >= 29 && x <= 451 && y >= 29 && y <= 451) {// System.out.println("在棋盘范围内:"+x+"--"+y);x = (x + 15) / 30 - 1; // 是为了取得交叉点的坐标y = (y + 15) / 30 - 1;if (allChess[x][y] == 0) {// 判断当前要下的是什么棋⼦if (isBlack == true) {allChess[x][y] = 1;this.repaint(); // 绘制棋⼦machineChess(gameDifficulty);isBlack = true;blackTime = 120;message = "⽤户下棋";whiteTime = 120;boolean winFlag = this.checkWin(x, y);this.repaint(); // 绘制棋⼦if (winFlag == true) {JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "⿊⽅" : "⽩⽅") + "获胜!"); canPlay = false;}} else {allChess[x][y] = 1;// allChess[x][y] = 2;this.repaint();isBlack = false;whiteTime = 120;blackTime = 120;boolean winFlag = this.checkWin(x, y);this.repaint(); // 绘制棋⼦if (winFlag == true) {JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "⿊⽅" : "⽩⽅") + "获胜!"); canPlay = false;}machineChess(gameDifficulty);}}// 判断这个棋⼦是否和其他棋⼦连成5个// boolean winFlag = this.checkWin(x, y);// this.repaint(); // 绘制棋⼦//// if (winFlag == true) {// JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] ==// 1 ? "⿊⽅" : "⽩⽅") + "获胜!");// canPlay = false;// }}}。

五子棋代码(JAVA)

五子棋代码(JAVA)

package ui;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JOptionPane;public class Welcome extends JLabel implements ActionListener {/*** 欢迎界面*/private static final long serialVersionUID = 1L;private FIR father = null;private JButton btnTwoGame = null;// 游戏界面按钮private JButton btnHelp = null;// 游戏帮助按钮private JButton btnExit = null;// 游戏退出按钮/*** Launch the application** @param args*//*** Create the application*/public Welcome(FIR father) {this.father = father;this.setIcon(IconResourses.bgWelcome);initialize();}/*** Initialize the contents of the frame*/private void initialize() {this.setLayout(null);// 先设置布局,再添加组件/** 实例化btnHelp,btnTwoGame,btnExit并设置相关属性,注册监听器*/btnHelp = new JButton(IconResourses.btnHelp);btnHelp.addActionListener(this);btnHelp.setBounds(450, 290, 138, 43);this.add(btnHelp);btnTwoGame = new JButton(IconResourses.btnTwoGame);btnTwoGame.addActionListener(this);btnTwoGame.setBounds(450, 230, 138, 43);this.add(btnTwoGame);btnExit = new JButton(IconResourses.btnExit);btnExit.setBounds(450, 350, 138, 43);btnExit.addActionListener(this);this.add(btnExit);}public void actionPerformed(ActionEvent e) {if (e.getSource() == btnTwoGame) {// 游戏按钮响应方法father.show("game");// 显示游戏界面} else if (e.getSource() == btnHelp) {// 游戏帮助响应方法father.show("help");// 显示帮助界面} else if (e.getSource() == btnExit) {// 游戏退出响应方法// 点击"是"确定退出游戏if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,"确定退出游戏吗?", "五子棋", JOptionPane.YES_NO_OPTION)) { System.exit(0);}}}}package ui;import javax.swing.JLabel;public class ChessGrid extends JLabel {/*** 棋格*/private static final long serialVersionUID = 1L;private JLabel rim= null;private int row = 0; // 标志当前棋格的行private int col = 0; // 标志当前棋格的列private int flag = 0;// 标志当前棋格的状态:0无子,1黑子,2白子/*** 棋格构造函数无棋子状态** @param row 指定行位置* @param col 指定列位置*/public ChessGrid(int row, int col) {this.row = row;this.col = col;this.init();// 设用类成员初始化方法}/*** 棋格构造函数同时指定棋子状态** @param row 指定行位置* @param col 指定列位置* @param flag:指定状态*/public ChessGrid(int row, int col, int flag) {this.row = row;this.col = col;this.flag = flag;this.init();// 设用类成员初始化方法}/*** 初始化类成员*/private void init() {// 实例化类成员rim = new JLabel(IconResourses.rim);// 设置类成员相关属性rim.setBounds(0, 0, 35, 35);rim.setVisible(false);// 先设置布局,后添加组件this.setLayout(null);this.add(rim);}// 设置选框是否可见public void setRim(boolean flag) {rim.setVisible(flag);}public int getRow() {return row;}public void setRow(int row) {this.row = row;}public int getCol() {return col;}public void setCol(int col) {this.col = col;}// 返回当前棋格的状态public int getFlag() {return flag;}// 设置当前棋格的状态public void setFlag(int flag) {this.flag = flag;if (flag == 0) {this.setIcon(null);} else if (flag == 1) {this.setIcon(IconResourses.lblBlack);} else if (flag == 2) {this.setIcon(IconResourses.lblWhite);}}package ui;import javax.swing.Icon;import javax.swing.ImageIcon;public class IconResourses {public static Icon lblWhite=new ImageIcon(IconResourses.class.getResource("bai.gif"));//白棋子public static Icon lblBlack=new ImageIcon(IconResourses.class.getResource("hei.gif"));//黑棋子public static Icon bq_yiban=new ImageIcon(IconResourses.class.getResource("yiban.gif"));//表情一般public static Icon bq_shikao=new ImageIcon(IconResourses.class.getResource("shikao.gif"));//表情思考public static Icon yiban=new ImageIcon(IconResourses.class.getResource("yiban.gif"));public static Icon lose=new ImageIcon(IconResourses.class.getResource("lose.gif"));//表情一般public static Icon victory=new ImageIcon(IconResourses.class.getResource("victory.gif"));//胜利表情public static Icon btn_pass_un=new ImageIcon(IconResourses.class.getResource("btn_pass_un.gif"));//通过public static Icon btn_pass_on=new ImageIcon(IconResourses.class.getResource("btn_pass_on.gif"));//通过public static Icon btn_reset_un=new ImageIcon(IconResourses.class.getResource("btn_reset_un.gif"));//重置public static Icon btn_reset_on=new ImageIcon(IconResourses.class.getResource("btn_reset_on.gif"));//重置public static Icon btn_send=new ImageIcon(IconResourses.class.getResource("send.jpg"));//发送按钮public static Icon btn_return_un=new ImageIcon(IconResourses.class.getResource("btn_return_un.gif"));//返回public static Icon btn_return_on=new ImageIcon(IconResourses.class.getResource("btn_return_on.gif"));//返回public static Icon btn_goon_on=new ImageIcon(IconResourses.class.getResource("btn_goon_on.gif"));public static Icon btn_goon_un=new ImageIcon(IconResourses.class.getResource("btn_goon_un.gif"));public static Icon btn_start_on=new ImageIcon(IconResourses.class.getResource("btn_start_on.gif"));//开始public static Icon btn_start_un=new ImageIcon(IconResourses.class.getResource("btn_start_on.gif"));//开始public static Icon btn_back_on=new ImageIcon(IconResourses.class.getResource("btn_back_on.gif"));//返回public static Icon btn_back_un=new ImageIcon(IconResourses.class.getResource("btn_back_on.gif"));//返回public static Icon btnHelp=new ImageIcon(IconResourses.class.getResource("help.gif"));//帮助按钮背景public static Icon btnExit=new ImageIcon(IconResourses.class.getResource("exit.gif")); //退出游戏按钮背景public static Icon btnTwoGame=new ImageIcon(IconResourses.class.getResource("twogame.gif"));//双人游戏按钮背景public static Icon btnReturn=new ImageIcon(IconResourses.class.getResource("return.jpg"));public static Icon bgWelcome=new ImageIcon(IconResourses.class.getResource("welcome.gif"));//欢迎界面背景public static Icon bgMain=new ImageIcon(IconResourses.class.getResource("main.gif"));//游戏主界面背景public static Icon bgHelp=new ImageIcon(IconResourses.class.getResource("bg_help.gif"));//帮助界面背景public static Icon rim=new ImageIcon(IconResourses.class.getResource("kuang.gif"));//棋子外框public static Icon sound=new ImageIcon(IconResourses.class.getResource("bg.mid"));//背景音乐}package ui;import java.applet.Applet;import java.applet.AudioClip;/*** 播放声音类* 支持格式: .au、.aiff、.Wav、.Midi、.rfm*/public class Sound{//音乐路径private String url="bg.mid";//音乐对象private AudioClip audio=null;//默认构造函数,播放背景音乐public Sound(){this.init();}//根据新路径播放音乐public Sound(String url){this.url=url;this.init();}//初始化类成员private void init(){if(!"".equals(url)){try {audio = Applet.newAudioClip(Sound.class.getResource(url));} catch (Exception e) {e.printStackTrace();}}}//单曲public void play(){if(audio!=null){audio.stop();audio.play();}}//停止播放public void stop(){if(audio!=null){audio.stop();}}//循环播放public void loop(){if(audio!=null){audio.loop();}}}package ui;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JLabel;/*** 游戏帮助界面* @author*/public class Help extends JLabel implements ActionListener {/*** 版本号*/private static final long serialVersionUID = 1L;private FIR father = null;//父容器引用,构造函数中传入private JButton btnReturn = null;//返回欢迎界面按钮/*** 游戏帮助界面构造函数* @param father父容器引用*/public Help(FIR father) {//父容器引用传入,赋值this.father = father;//调用类成员初始化方法this.init();//此类继函至JLabel,以此可设置游戏欢迎界面的背景this.setIcon(IconResourses.bgHelp);}/*** 初始化方法* 此方法主要目的是:1 实例化类成员2 布局*/private void init(){//实例化类成员btnReturn = new JButton(IconResourses.btnReturn);//设置类成员位置大小btnReturn.setBounds(310, 470, 50,23);//为类成员注册监听器btnReturn.addActionListener(this);//先设设置布局,再添加组件this.setLayout(null);//添加组件this.add(btnReturn);}public void actionPerformed(ActionEvent e) {if (e.getSource() == btnReturn) {//返回按钮响应方法//显示欢迎界面father.show("welcome");}}}package ui;import java.awt.Color;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import javax.swing.*;public class Timer extends JPanel implements Runnable{/*** 时间设置以JLable作为载体*/private static final long serialVersionUID = 1L;private static Image image=Toolkit.getDefaultToolkit().createImage(Timer.class.getResource("number.gif"));private Game father;//调用父类private int secTemp;//从play开始到pause用了多少秒,每次play之后归0,secTemp记录从双方每一次落子到落子完成并暂停计时器时所消耗的时间private int seconds=1800;//比赛总时间private Thread time;//时间线程private boolean flag;//是否处于计时中/** 构造函数,默认比赛总时间为30分钟*/public Timer(Game father){this.father=father;this.init();}/** 构造函数,设置比赛总时间*/public Timer(Game father,int seconds){this.father=father;this.seconds=seconds;this.init();}/** 对私有属性seconds公开化*/public int getSeconds(){return this.seconds;}public void setSeconds(int seconds){this.seconds=seconds;this.repaint();//重置完时间后,刷新画板}/** 初始化相关成员*/private void init(){this.setBackground(Color.black);flag=false;time=new Thread(this);time.start();//启动线程,使其处于就绪状态}/** 重写JLalbe中的paint方法*/public void paint(Graphics g){super.paint(g);int temp=seconds/60;int i=0;//画分钟十位i=temp/10;g.drawImage(image, 0, 0, 9, 16, i*9, 0, (i+1)*9, 16, this);//画分钟个位i=temp%10;g.drawImage(image, 10, 0, 19, 16, i*9, 0, (i+1)*9, 16, this);//画中间线g.drawImage(image, 20, 0,29 ,16, 90, 0, 99, 16, this);//计算出秒数temp=seconds%60;//画秒钟个位i=temp/10;g.drawImage(image, 30, 0, 39, 16, i*9, 0, (i+1)*9, 16, this);//画秒钟个位i=temp%10;g.drawImage(image, 40, 0,49, 16, i*9, 0, (i+1)*9, 16, this); }/** 暂停时间*/public void pause(){this.flag=false;}/** 继续时间*/public void play(){this.flag=true;this.secTemp=0;}/** 实现线程的run接口*/public void run(){while(true){if(flag){if(seconds>0){seconds--;secTemp++;this.repaint();}else{father.timeOver();}}try{Thread.sleep(1000);}catch(Exception e){e.printStackTrace();}}}public int getSecTemp(){return this.secTemp;}}package ui;import java.awt.Cursor;import java.awt.Graphics;import java.awt.Image;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.util.ArrayList;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JOptionPane;public class Game extends JLabel implements MouseListener, ActionListener { /*** 游戏主界面*/private static final long serialVersionUID = 1L;private FIR father;private ChessGrid[][] crosses = new ChessGrid[15][15];// 实例化棋盘数组private ChessGrid temp = null;// 上一步棋格private int start = 0;// 游戏运行状态0未开始1进行中2暂停3回放private boolean flag = true;// 哪方行棋,true为黑方,false为白方private JButton btnStart = null;// 开始按钮private JButton btnReturn = null;// 返回按钮private JButton btnPass = null;// 暂停按钮private JButton btnBack = null;// 悔棋private Timer palTimeBai = null;// 白方剩余时间private Timer palTimeHei = null;// 黑方剩余时间private JLabel lblEmotionBai = null;// 白方表情private JLabel lblEmotionHei = null;// 黑方表情private ArrayList<ChessGrid> qb = null;// 棋步private Image image;// 鼠标图片/** 构造函数,转到FIR中去*/public Game(FIR father) {this.father = father;init();// 初始化类成员getImage("hei.gif");// 当转到该界面时,鼠标变成黑色的棋子this.setVisible(true);this.reSet();// 重置游戏参数}/** 初始化*/public void init() {this.setIcon(IconResourses.bgMain);// 棋盘背景界面this.setLayout(null);// 无布局// 循环棋盘格子,实例化,设置属性,同时添加监听器,并添加到游戏界面上int i = 0;// 行int j = 0;// 列for (i = 0; i < 15; i++) {for (j = 0; j < 15; j++) {crosses[i][j] = new ChessGrid(i, j);crosses[i][j].setBounds(163 + j * 35, 13 + i * 35, 35, 35);crosses[i][j].addMouseListener(this);this.add(crosses[i][j]);}}// 实例化保存棋步的容器qb = new ArrayList<ChessGrid>();// 实例化其它成员lblEmotionBai = new JLabel(IconResourses.bq_yiban);lblEmotionHei = new JLabel(IconResourses.bq_yiban);btnStart = new JButton(IconResourses.btn_start_on);btnBack = new JButton(IconResourses.btn_back_un);btnPass = new JButton(IconResourses.btn_pass_un);btnReturn = new JButton(IconResourses.btn_return_on);/** 黑白双方时间*/palTimeBai = new Timer(this);// palTimeBai.setSeconds(600);palTimeBai.setVisible(true);palTimeHei = new Timer(this);// palTimeHei.setSeconds(600);palTimeHei.setVisible(true);// 设置其它成员属性lblEmotionBai.setBounds(45, 65, 65, 65);lblEmotionHei.setBounds(45, 345, 65, 65);palTimeBai.setBounds(73, 206, 50, 16);palTimeHei.setBounds(73, 487, 50, 16);btnStart.setBounds(13, 250, 30, 60);btnBack.setBounds(78, 250, 30, 60);btnPass.setBounds(45, 250, 30, 60);btnReturn.setBounds(110, 250, 30, 60);// btnStart.setDisabledIcon(IconResourses.btn_start_un);// btnBack.setDisabledIcon(IconResourses.btn_back_un);// btnPass.setDisabledIcon(IconResourses.btn_pass_un);// btnReturn.setDisabledIcon(IconResourses.btn_return_un);btnStart.addActionListener(this);btnBack.addActionListener(this);btnPass.addActionListener(this);btnReturn.addActionListener(this);// 添加其它成员this.add(palTimeBai);this.add(palTimeHei);this.add(lblEmotionBai);this.add(lblEmotionHei);this.add(btnStart);this.add(btnBack);this.add(btnPass);this.add(btnReturn);}public void reSet() {// 重置棋盘for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {crosses[i][j].setFlag(0);crosses[i][j].setRim(false);}}start = 0;// 游戏标志设置为0,未开始flag = true;// 重新开始游戏,黑方先行棋// 暂停时间,并重置为1800秒palTimeBai.pause();palTimeBai.setSeconds(1800);palTimeHei.pause();palTimeHei.setSeconds(1800);// 重置表情lblEmotionBai.setIcon(IconResourses.bq_yiban);lblEmotionHei.setIcon(IconResourses.bq_yiban);qb.clear();// 清空棋步数组// 重置按钮图标btnStart.setIcon(IconResourses.btn_start_on);btnPass.setIcon(IconResourses.btn_pass_on);// 锁定一些功能按钮btnBack.setEnabled(false);btnPass.setEnabled(false);}/** 实现四个按钮的动作监听*/public void actionPerformed(ActionEvent e) {if (e.getSource() == btnStart) {// 开始游戏或重置游戏if (start == 0) {// 游戏未开始,执行开始操作btnStart.setIcon(IconResourses.btn_reset_on);// 开始按钮变为重置按钮btnPass.setIcon(IconResourses.btn_pass_on);// 暂停按钮变为可用的按钮btnBack.setIcon(IconResourses.btn_back_un);// 悔棋按钮变为可用的按钮/** 初始化并将黑子居中*/crosses[7][7].setBounds(163 + 7 * 35, 13 + 7 * 35, 35, 35);crosses[7][7].setFlag(1);crosses[7][7].setRim(true);qb.add(crosses[7][7]);// palTimeHei.play();// palTimeBai.pause();getImage("bai.gif");// 鼠标变成白子的图片flag = false;// 下一步为白子// 黑方先走,开始计时if (flag == true) {palTimeHei.play();palTimeBai.pause();} else {palTimeBai.play();palTimeHei.pause();}lblEmotionBai.setIcon(IconResourses.bq_shikao);// 设置黑方表情btnPass.setEnabled(true);// 暂停按钮可用btnBack.setEnabled(false);// 悔棋按钮不可用start = 1;// 标志游戏是在进行中} else {// 否则执行游戏重置操作this.reSet();}} else if (e.getSource() == btnPass) {// 暂停或继续游戏if (start == 1) {// 游戏进行中,进行暂停操作// 暂停时间palTimeBai.pause();palTimeHei.pause();start = 2;// 标志游戏为暂停状态btnPass.setIcon(IconResourses.btn_goon_on);// 更改成继续图标/** 暂停中不可悔棋*/btnBack.setIcon(IconResourses.btn_back_un);btnBack.setEnabled(false);} else if (start == 2) {// 游戏暂停中,进行继续操作// 根据当前是哪方下子,play相应的时间if (flag == true) {// 黑方行棋,开始计时palTimeHei.play();} else {// 白方行棋,开始计时palTimeBai.play();}start = 1;// 标志游戏为进行状态btnPass.setIcon(IconResourses.btn_pass_on);// 更改成暂停图标/** 游戏进行中可悔棋*/btnBack.setIcon(IconResourses.btn_back_on);btnBack.setEnabled(true);}} else if (e.getSource() == btnBack) {// 悔棋// 有棋步记录,且获得对方的同意,才可以悔棋int answer = JOptionPane.showConfirmDialog(null, "对方请求悔棋,是不答应?","信息", JOptionPane.YES_NO_OPTION);if (qb.size() > 0) {// 清除掉可能后来选择的一些格子方框if (temp != null) {temp.setRim(false);}// 取得最后下的一步棋,同时将它从棋步数组中移除/** 只能在白方行了第二着棋之后才能悔棋*/if (answer == 0 && qb.size() >= 5) {// 如果用户点击“确定”所做的操作ChessGrid box = qb.remove(qb.size() - 1);// 置空最后一步棋box.setFlag(0);box.setRim(false);}else{btnBack.setEnabled(false);}// 下棋角色,时间,表情对换// int answer=1;if (flag) {// 当前为黑方下棋,说明是白方悔棋flag = false;lblEmotionBai.setIcon(IconResourses.bq_shikao);lblEmotionHei.setIcon(IconResourses.bq_yiban);// 把被白方浪费掉的时间,返还给黑方,同时被浪费掉的这部分时间视为白方的palTimeHei.pause();int timewasteHei = palTimeHei.getSecTemp();// 黑棋还未下这一步棋所用时间palTimeHei.setSeconds(palTimeHei.getSeconds()+ timewasteHei);// palTimeBai.setSeconds(palTimeBai.getSeconds()-timewasteHei);palTimeBai.play();getImage("bai.gif");}} else {// 当前为白方下棋,说明是黑方悔棋flag = true;lblEmotionBai.setIcon(IconResourses.bq_yiban);lblEmotionHei.setIcon(IconResourses.bq_shikao);// 把被黑方浪费掉的时间,返还给白方,同时被浪费掉的这部分时间视为黑方的palTimeBai.pause();int timewasteBai = palTimeBai.getSecTemp();// 白棋上一步棋所用时间palTimeBai.setSeconds(palTimeBai.getSeconds() + timewasteBai);// palTimeHei.setSeconds(palTimeHei.getSeconds()-timewasteBai);palTimeHei.play();getImage("hei.gif");}// 没有棋步记录时,悔棋不可用,否则取得当前棋步数组中的最后一个子,进行红框标注if (qb.size() == 0) {btnBack.setEnabled(false);} else {// get(index)和remove(index)都返回当前数组中的最后一个对象// 区别是,get仅返回不从数组中删除这个对象,而remove返回的同时从数组中移除这个对象qb.get(qb.size() - 1).setRim(true);btnBack.setIcon(IconResourses.btn_back_on);btnBack.setEnabled(true);}} else if (e.getSource() == btnReturn) {// 返回欢迎界面// 游戏中,提示是否返回if (start > 0) {if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, "正在游戏中,返回将导至游戏信息丢失!", "五子棋",JOptionPane.YES_NO_OPTION)) {father.show("welcome");// 重置游戏this.reSet();}} else {father.show("welcome");}}}/** 当改白子行棋时鼠标上的图片变成白棋的图片,当改黑子行棋时鼠标上的图片变成黑棋的图片*/private void getImage(String image_url) {image = java.awt.Toolkit.getDefaultToolkit().createImage(FIR.class.getResource(image_url));Cursor transparentCursor = java.awt.Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor"); // invisiblecursor是任意取的this.setCursor(transparentCursor);}/** 下棋的事件操作方法*/public void mouseClicked(MouseEvent e) {}/** 实现落子功能*/public void mousePressed(MouseEvent e) {crosses[7][7].setRim(false);/* 去掉当前棋上一步棋的外框*/if (qb.size() != 0) {temp = qb.get(qb.size() - 1);temp.setRim(false);}if (qb.size() == 4) {btnBack.setEnabled(true);}ChessGrid lblChessGrid = (ChessGrid) e.getSource();// 按键触发的是棋格上的JLableif (start == 1 && e.getButton() == 1) {// 游戏是否在进行中,同时只有左键起效if (lblChessGrid.getFlag() == 0) {// 只有无子的情况下,才允许落子,有子的情况下,不允许落子if (flag == false) {// 白子行棋getImage("hei.gif");// 鼠标变成黑子palTimeBai.pause();palTimeHei.play();lblChessGrid.setFlag(2);lblChessGrid.setVisible(true);lblChessGrid.setRim(true);qb.add(lblChessGrid);lblEmotionBai.setIcon(IconResourses.bq_yiban);lblEmotionHei.setIcon(IconResourses.bq_shikao);if (checkWin(lblChessGrid.getRow(), lblChessGrid.getCol())) {// System.out.println("fdk;");lblEmotionBai.setIcon(IconResourses.victory);lblEmotionHei.setIcon(IconResourses.lose);palTimeHei.pause();JOptionPane.showMessageDialog(this, "白方赢了!");this.gameOver();}flag = true;} else {// 黑子行棋getImage("bai.gif");// 鼠标变成白子palTimeHei.pause();palTimeBai.play();lblChessGrid.setFlag(1);lblChessGrid.setVisible(true);lblChessGrid.setRim(true);qb.add(lblChessGrid);lblEmotionBai.setIcon(IconResourses.bq_shikao);lblEmotionHei.setIcon(IconResourses.bq_yiban);if (checkWin(lblChessGrid.getRow(), lblChessGrid.getCol())) {lblEmotionBai.setIcon(IconResourses.lose);lblEmotionHei.setIcon(IconResourses.victory);palTimeBai.pause();JOptionPane.showMessageDialog(this, "黑方赢了!");this.gameOver();}flag = false;}}}}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}@Overridepublic void printComponents(Graphics arg0) {// TODO Auto-generated method stubsuper.printComponents(arg0);}/** 判胜处理*/// 检查当前下子是否可以胜利private boolean checkWin(int row, int col) {if (checkNum(row, col, 1) >= 5 || checkNum(row, col, 2) >= 5|| checkNum(row, col, 3) >= 5 || checkNum(row, col, 4) >= 5) { return true;} else {return false;}}// 判断连子数,type:1纵向,2横向,3左斜,4右斜private int checkNum(int row, int col, int type) {int nextrow = 0;// 向上走int nextcol = 0;int count = 1;int num = 0;if (row >= 0 && row < 15 && col >= 0 && col < 15) {if (type == 1) {// 纵向nextrow = row;// 向上走nextcol = col - 1;while (crosses[row][col].getFlag() != 0 && nextcol >= 0) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextcol--;} else {break;}}nextrow = row;// 向下走nextcol = col + 1;while (crosses[row][col].getFlag() != 0 && nextcol < 15) { if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextcol++;} else {break;}}num = count;}if (type == 2) {// 横向nextrow = row - 1;// 向左走nextcol = col;while (crosses[row][col].getFlag() != 0 && nextcol >= 0) { if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow--;} else {break;}}nextrow = row + 1;// 向右走nextcol = col;while (crosses[row][col].getFlag() != 0 && nextcol < 15) { if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow++;} else {break;}}num = count;}if (type == 3) {// 左斜nextrow = row - 1;// 向左上走nextcol = col - 1;while (crosses[row][col].getFlag() != 0 && nextcol >= 0&& nextrow >= 0) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow--;nextcol--;} else {break;}}nextrow = row + 1;// 向左下走nextcol = col + 1;while (crosses[row][col].getFlag() != 0 && nextcol < 15&& nextrow < 15) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow++;nextcol++;} else {break;}}num = count;}if (type == 4) {// 右斜nextrow = row - 1;// 向右下走nextcol = col + 1;while (crosses[row][col].getFlag() != 0 && nextcol >= 0&& nextrow >= 0) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow--;nextcol++;} else {break;}}nextrow = row + 1;// 向右上走nextcol = col - 1;while (crosses[row][col].getFlag() != 0 && nextcol < 15&& nextrow < 15) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow++;nextcol--;} else {break;}}num = count;}}return num;}// 游戏结束后清空棋盘public void gameOver() {this.reSet();// 重置棋盘}// 游戏重新开始的处理方法public void reStart() {}/** 双方任何一方还未分胜负之前时间用完后的处理*/public void timeOver() {if (palTimeBai.getSeconds() == 0 && palTimeHei.getSeconds() != 0) { JOptionPane.showMessageDialog(this, "白方游戏时间到,黑方获胜");gameOver();}if (palTimeBai.getSeconds() != 0 && palTimeHei.getSeconds() == 0) { JOptionPane.showMessageDialog(this, "黑方游戏时间到,白方获胜");gameOver();}if (palTimeBai.getSeconds() == 0 && palTimeHei.getSeconds() == 0) { JOptionPane.showMessageDialog(this, "游戏时间到,不分胜负");gameOver();}}}package ui;import java.awt.CardLayout;import java.awt.Dimension;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.JFrame;import javax.swing.JOptionPane;import java.awt.Toolkit;public class FIR extends JFrame implements WindowListener{private static final long serialVersionUID = 1L;private CardLayout layout;//布局private Welcome welcome;//欢迎界面private Help help;//帮助界面private Sound bgSound;//游戏背景音乐private Game game;//游戏界面/*** Launch the application* @param args*/public static void main(String args[]) {try {FIR window = new FIR();window.setVisible(true);} catch (Exception e) {e.printStackTrace();}}/*** Create the application*/public FIR() {initialize();init();}/*** Initialize the attributes of the frame*/private void initialize() {this.setTitle("单机版五子棋(无禁手)");this.setSize(700, 575);Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();this.setLocation((screen.width-700)/2, (screen.height-550)/2);this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);this.addWindowListener(this);//添加窗体监听器this.setResizable(false);}/*** 动态初始化该窗体*/public void init(){welcome=new Welcome(this);help=new Help(this);game=new Game(this);bgSound=new Sound();bgSound.loop();//循环播放背景音乐layout=new CardLayout();//将窗体设置为卡片布局this.setLayout(layout);this.add(welcome, "welcome");this.add(help,"help");this.add(game,"game");}/*** 显示相应名称的卡片* @param name 要显示的卡片的名称*/public void show(String name){layout.show(this.getContentPane(), name);}/***实现WindowListener接口中的抽象方法*/public void windowOpened(WindowEvent e){}/*** 在点游戏窗体关闭按钮时,提示是否退出游戏*/public void windowClosing(WindowEvent arg0) {//点击"是"确定退出游戏if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(this, "确定退出游戏吗?","五子棋",JOptionPane.YES_NO_OPTION)){System.exit(0);}}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}}。

java五子棋(人机版1.2)

java五子棋(人机版1.2)

Java五子棋人机版1.2public class FiveChessFinally_005_ok {private static char[][] chess = new char[17][17];private static Random r = new Random();private static int s = 0;private static boolean win = true;private static Scanner sc = null;private static String str = null;private static int first = 0;private static int f1 = 0, f2 = 0;private static int c1 = 0, c2 = 0;private static int x1 = 0, y1 = 0, x2 = 0, y2 = 0;private static int z = 0;public static void structure() {char[] ches = { ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };for (int i = 0; i < ches.length; i++) {chess[0][i] = chess[i][0] = ches[i];}for (int i = 1; i < chess.length; i++) {for (int j = 1; j < chess[i].length; j++) {chess[i][j] = '.';}}}public static void printChess() {for (int i = 0; i < chess.length; i++) {for (int j = 0; j < chess[i].length; j++) {System.out.print(chess[i][j] + " ");}System.out.println();}}public static boolean isRational(char a, char b) {if (((a >= '0' && a <= '9') || (a >= 'a' && a <= 'f'))&& ((b >= '0' && b <= '9') || (b >= 'a' && b <= 'f'))) { int x = 0, y = 0;for (int i = 1; i < chess.length; i++) {if (chess[i][0] == a)x = i;if (chess[0][i] == b)y = i;}if (chess[x][y] == 'o' || chess[x][y] == 'x')return false;elsereturn true;}return false;}public static boolean isWin(char a) {for (int i = chess.length - 1; i > 4; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 4) {if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j - 1])&& (chess[i - 1][j - 1] == chess[i - 2][j - 2])&& (chess[i - 2][j - 2] == chess[i - 3][j - 3])&& (chess[i - 3][j - 3] == chess[i - 4][j - 4])) {return true;}}if (j < chess[i].length - 4) {if (((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& (chess[i - 1][j] == chess[i - 2][j])&& (chess[i - 2][j] == chess[i - 3][j]) && (chess[i - 3][j] == chess[i - 4][j]))|| ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j + 1])&& (chess[i - 1][j + 1] == chess[i - 2][j + 2])&& (chess[i - 2][j + 2] == chess[i - 3][j + 3]) && (chess[i - 3][j + 3] == chess[i - 4][j + 4]))|| ((chess[i][j] == a)&& (chess[i][j] == chess[i][j + 1])&& (chess[i][j + 1] == chess[i][j + 2])&& (chess[i][j + 2] == chess[i][j + 3]) && (chess[i][j + 3] == chess[i][j + 4]))) {return true;}} else {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& (chess[i - 1][j] == chess[i - 2][j])&& (chess[i - 2][j] == chess[i - 3][j])&& (chess[i - 3][j] == chess[i - 4][j])) {return true;}}}}return false;}public static void gamer(char a, char b) {int x = 0, y = 0;for (int i = 1; i < chess.length; i++) {if (chess[i][0] == a)x = i;if (chess[0][i] == b)y = i;}if (first == 0) {f1 = x;f2 = y;}chess[x][y] = 'o';}public static void firstOneChess() {int x = f1, y = f2;int i = r.nextInt(8);switch (i) {case 0:chess[x - 1][y - 1] = 'x';break;case 1:chess[x - 1][y] = 'x';break;case 2:chess[x - 1][y + 1] = 'x';break;case 3:chess[x][y - 1] = 'x';break;case 4:chess[x][y + 1] = 'x';break;case 5:chess[x + 1][y - 1] = 'x';break;case 6:chess[x][y + 1] = 'x';break;case 7:chess[x + 1][y + 1] = 'x';break;}}public static void computerStep() {chess[c1][c2] = 'x';}public static boolean isFour(char a) {for (int i = chess.length - 1; i > 3; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 3) {if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j - 1])&& (chess[i - 1][j - 1] == chess[i - 2][j - 2])&& (chess[i - 2][j - 2] == chess[i - 3][j - 3])) {x1 = i - 3;y1 = j - 3;x2 = i;y2 = j;z = 3;if (a == 'o') {if (isNullFour('o'))return true;} else if (a == 'x') {if (isNullFour('x'))return true;}}}if (j < chess[i].length - 3) {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& (chess[i - 1][j] == chess[i - 2][j])&& (chess[i - 2][j] == chess[i - 3][j])) {x1 = i - 3;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isNullFour('o'))return true;} else if (a == 'x') {if (isNullFour('x'))return true;}}if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j + 1])&& (chess[i - 1][j + 1] == chess[i - 2][j + 2])&& (chess[i - 2][j + 2] == chess[i - 3][j + 3])) { x1 = i;y1 = j;x2 = i - 3;y2 = j + 3;z = 4;if (a == 'o') {if (isNullFour('o'))return true;} else if (a == 'x') {if (isNullFour('x'))return true;}}if ((chess[i][j] == a) && (chess[i][j] == chess[i][j + 1]) && (chess[i][j + 1] == chess[i][j + 2])&& (chess[i][j + 2] == chess[i][j + 3])) { x1 = i;y1 = j;x2 = i;y2 = j + 3;z = 1;if (a == 'o') {if (isNullFour('o'))return true;} else if (a == 'x') {if (isNullFour('x'))return true;}}} else {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& (chess[i - 1][j] == chess[i - 2][j])&& (chess[i - 2][j] == chess[i - 3][j])) {x1 = i - 3;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isNullFour('o'))return true;} else if (a == 'x') {if (isNullFour('x'))return true;}}}}}return false;}public static boolean isThree(char a) {for (int i = chess.length - 1; i > 2; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 2) {if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j - 1])&& (chess[i - 1][j - 1] == chess[i - 2][j - 2])) {x1 = i - 2;y1 = j - 2;x2 = i;y2 = j;z = 3;if (a == 'o') {if (isNullThree('o'))return true;} else if (a == 'x') {if (isNullThree('x'))return true;}}}if (j < chess[i].length - 2) {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& (chess[i - 1][j] == chess[i - 2][j])) {x1 = i - 2;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isNullThree('o'))return true;} else if (a == 'x') {if (isNullThree('x'))return true;}}if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j + 1])&& (chess[i - 1][j + 1] == chess[i - 2][j + 2])) { x1 = i;y1 = j;x2 = i - 2;y2 = j + 2;z = 4;if (a == 'o') {if (isNullThree('o'))return true;} else if (a == 'x') {if (isNullThree('x'))return true;}}if ((chess[i][j] == a) && (chess[i][j] == chess[i][j + 1])&& (chess[i][j + 1] == chess[i][j + 2])) {x1 = i;y1 = j;x2 = i;y2 = j + 2;z = 1;if (a == 'o') {if (isNullThree('o'))return true;} else if (a == 'x') {if (isNullThree('x'))return true;}}} else {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& (chess[i - 1][j] == chess[i - 2][j])) {x1 = i - 2;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isNullThree('o'))return true;} else if (a == 'x') {if (isNullThree('x'))return true;}}}}}return false;}public static boolean isLeftThree(char a) {for (int i = chess.length - 1; i > 3; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 3) {if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j - 1])&& (chess[i - 2][j - 2] == '.')&& (a == chess[i - 3][j - 3])) {x1 = i - 3;y1 = j - 3;x2 = i;y2 = j;z = 3;if (a == 'o') {if (isLeftNullThree('o'))return true;} else if (a == 'x') {if (isLeftNullThree('x'))return true;}}}if (j < chess[i].length - 3) {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& ('.' == chess[i - 2][j])&& (a == chess[i - 3][j])) {x1 = i - 3;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isLeftNullThree('o'))return true;} else if (a == 'x') {if (isLeftNullThree('x'))return true;}}if ((chess[i][j] == a) && ('.' == chess[i - 1][j + 1])&& (a == chess[i - 2][j + 2])&& (chess[i - 2][j + 2] == chess[i - 3][j + 3])) { x1 = i;y1 = j;x2 = i - 3;y2 = j + 3;z = 4;if (a == 'o') {if (isLeftNullThree('o'))return true;} else if (a == 'x') {if (isLeftNullThree('x'))return true;}}if ((chess[i][j] == a) && ('.' == chess[i][j + 1])&& (a == chess[i][j + 2])&& (chess[i][j + 2] == chess[i][j + 3])) {x1 = i;y1 = j;x2 = i;y2 = j + 3;z = 1;if (a == 'o') {if (isLeftNullThree('o'))return true;} else if (a == 'x') {if (isLeftNullThree('x'))return true;}}} else {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])&& ('.' == chess[i - 2][j])&& (a == chess[i - 3][j])) {x1 = i - 3;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isLeftNullThree('o'))return true;} else if (a == 'x') {if (isLeftNullThree('x'))return true;}}}}}return false;}public static boolean isRightThree(char a) {for (int i = chess.length - 1; i > 3; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 3) {if ((chess[i][j] == a) && ('.' == chess[i - 1][j - 1])&& (chess[i - 2][j - 2] == chess[i - 3][j - 3])&& (a == chess[i - 3][j - 3])) {x1 = i - 3;y1 = j - 3;x2 = i;y2 = j;z = 3;if (a == 'o') {if (isRightNullThree('o'))return true;} else if (a == 'x') {if (isRightNullThree('x'))return true;}}}if (j < chess[i].length - 3) {if ((chess[i][j] == a) && ('.' == chess[i - 1][j])&& (chess[i - 3][j] == chess[i - 2][j])&& (a == chess[i - 3][j])) {x1 = i - 3;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isRightNullThree('o'))return true;} else if (a == 'x') {if (isRightNullThree('x'))return true;}}if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j + 1])&& ('.' == chess[i - 2][j + 2])&& (a == chess[i - 3][j + 3])) {x1 = i;y1 = j;x2 = i - 3;y2 = j + 3;z = 4;if (a == 'o') {if (isRightNullThree('o'))return true;} else if (a == 'x') {if (isRightNullThree('x'))return true;}}if ((chess[i][j] == a) && (chess[i][j] == chess[i][j + 1])&& ('.' == chess[i][j + 2])&& (a == chess[i][j + 3])) {x1 = i;y1 = j;x2 = i;y2 = j + 3;z = 1;if (a == 'o') {if (isRightNullThree('o'))return true;} else if (a == 'x') {if (isRightNullThree('x'))return true;}}} else {if ((chess[i][j] == a) && ('.' == chess[i - 1][j])&& (chess[i - 3][j] == chess[i - 2][j])&& (a == chess[i - 3][j])) {x1 = i - 3;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isRightNullThree('o'))return true;} else if (a == 'x') {if (isRightNullThree('x'))return true;}}}}}return false;}public static boolean isTwo(char a) {for (int i = chess.length - 1; i > 1; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 1) {if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j - 1])) {x1 = i - 1;y1 = j - 1;x2 = i;y2 = j;z = 3;if (a == 'x') {if (isNullTwo('x'))return true;} else if (a == 'o') {if (isNullTwo('o'))return true;}}}if (j < chess[i].length - 1) {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])) { x1 = i - 1;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'x') {if (isNullTwo('x'))return true;} else if (a == 'o') {if (isNullTwo('o'))return true;}}if ((chess[i][j] == a)&& (chess[i][j] == chess[i - 1][j + 1])) {x1 = i;y1 = j;x2 = i - 1;y2 = j + 1;z = 4;if (a == 'x') {if (isNullTwo('x'))return true;} else if (a == 'o') {if (isNullTwo('o'))return true;}}if ((chess[i][j] == a) && (chess[i][j] == chess[i][j + 1])) {x1 = i;y1 = j;x2 = i;y2 = j + 1;z = 1;if (a == 'x') {if (isNullTwo('x'))return true;} else if (a == 'o') {if (isNullTwo('o'))return true;}}} else {if ((chess[i][j] == a) && (chess[i][j] == chess[i - 1][j])) {x1 = i - 1;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'x') {if (isNullTwo('x'))return true;} else if (a == 'o') {if (isNullTwo('o'))return true;}}}}}return false;}public static boolean isCenterTwo(char a) {for (int i = chess.length - 1; i > 2; i--) {for (int j = 1; j < chess[0].length; j++) {if (j > 2) {if ((chess[i][j] == a) && ('.' == chess[i - 1][j - 1])&& (a == chess[i - 2][j - 2])) {x1 = i - 2;y1 = j - 2;x2 = i;y2 = j;z = 3;if (a == 'o') {if (isCenterNullTwo('o'))return true;} else if (a == 'x') {if (isCenterNullTwo('x'))return true;}}}if (j < chess[i].length - 2) {if ((chess[i][j] == a) && ('.' == chess[i - 1][j])&& (a == chess[i - 2][j])) {x1 = i - 2;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isCenterNullTwo('o'))return true;} else if (a == 'x') {if (isCenterNullTwo('x'))return true;}}if ((chess[i][j] == a) && ('.' == chess[i - 1][j + 1])&& (a == chess[i - 2][j + 2])) {x1 = i;y1 = j;x2 = i - 2;y2 = j + 2;z = 4;if (a == 'o') {if (isCenterNullTwo('o'))return true;} else if (a == 'x') {if (isCenterNullTwo('x'))return true;}}if ((chess[i][j] == a) && ('.' == chess[i][j + 1])&& (a == chess[i][j + 2])) {x1 = i;y1 = j;x2 = i;y2 = j + 2;z = 1;if (a == 'o') {if (isCenterNullTwo('o'))return true;} else if (a == 'x') {if (isCenterNullTwo('x'))return true;}}} else {if ((chess[i][j] == a) && ('.' == chess[i - 1][j])&& (a == chess[i - 2][j])) {x1 = i - 2;y1 = j;x2 = i;y2 = j;z = 2;if (a == 'o') {if (isCenterNullTwo('o'))return true;} else if (a == 'x') {if (isCenterNullTwo('x'))return true;}}}}}return false;}public static boolean isNullFour(char a) {if (z == 1 && a == chess[x1][y1]) {x1 = x1;y1 = y1 - 1;x2 = x2;y2 = y2 + 1;if (isNot(x1, y1) || isNot(x2, y2)) {if (chess[x1][y1] == '.') {c1 = x1;c2 = y1;return true;} else if (chess[x2][y2] == '.') {c1 = x2;c2 = y2;return true;}}} else if (z == 2 && a == chess[x1][y1]) { x1 = x1 - 1;y1 = y1;x2 = x2 + 1;y2 = y2;if (isNot(x1, y1) || isNot(x2, y2)) {if (chess[x1][y1] == '.') {c1 = x1;c2 = y1;return true;} else if (chess[x2][y2] == '.') {c1 = x2;c2 = y2;return true;}}} else if (z == 3 && a == chess[x1][y1]) { x1 = x1 - 1;y1 = y1 - 1;x2 = x2 + 1;y2 = y2 + 1;if (isNot(x1, y1) || isNot(x2, y2)) {if (chess[x1][y1] == '.') {c1 = x1;c2 = y1;return true;} else if (chess[x2][y2] == '.') {c1 = x2;c2 = y2;return true;}}} else if (z == 4 && a == chess[x1][y1]) { x1 = x1 + 1;y1 = y1 - 1;x2 = x2 - 1;y2 = y2 + 1;if (isNot(x1, y1) || isNot(x2, y2)) {if (chess[x1][y1] == '.') {c1 = x1;c2 = y1;return true;} else if (chess[x2][y2] == '.') {c1 = x2;c2 = y2;return true;}}}return false;}public static boolean isNot(int x, int y) {if (x < 1 || y < 1 || x > chess.length - 1 || y > chess[0].length - 1) return false;elsereturn true;}public static boolean isLeftNullThree(char a) {if (z == 1 && '.' == chess[x1][y1 + 1]) {x1 = x1;y1 = y1 - 1;x2 = x2;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x1;c2 = y1 + 2;return true;}}} else if (z == 2 && '.' == chess[x1 + 1][y1]) {x1 = x1 - 1;y1 = y1;x2 = x2 + 1;y2 = y2;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x1 + 2;c2 = y1;return true;}}} else if (z == 3 && '.' == chess[x1 + 1][y1 + 1]) {x1 = x1 - 1;y1 = y1 - 1;x2 = x2 + 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x1 + 2;c2 = y1 + 2;return true;}}} else if (z == 4 && a == chess[x1 - 1][y1 + 1]) {x1 = x1 + 1;y1 = y1 - 1;x2 = x2 - 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x1 - 2;c2 = y1 + 2;return true;}}}return false;}public static boolean isRightNullThree(char a) {if (z == 1 && '.' == chess[x2][y2 - 1]) {x1 = x1;y1 = y1 - 1;x2 = x2;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x2;c2 = y2 - 2;return true;}}} else if (z == 2 && '.' == chess[x2 - 1][y2]) {x1 = x1 - 1;y1 = y1;x2 = x2 + 1;y2 = y2;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x2 - 2;c2 = y2;return true;}}} else if (z == 3 && '.' == chess[x2 - 1][y2 - 1]) {x1 = x1 - 1;y1 = y1 - 1;x2 = x2 + 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x2 - 2;c2 = y2 - 2;return true;}}} else if (z == 4 && a == chess[x2 + 1][y2 - 1]) {x1 = x1 + 1;y1 = y1 - 1;x2 = x2 - 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {c1 = x2 + 2;c2 = y2 - 2;return true;}}}return false;}public static boolean isNullThree(char a) {if (z == 1 && a == chess[x1][y1]) {x1 = x1;y1 = y1 - 1;x2 = x2;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') { s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}} else if (z == 2 && a == chess[x1][y1]) {x1 = x1 - 1;y1 = y1;x2 = x2 + 1;y2 = y2;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') { s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}} else if (z == 3 && a == chess[x1][y1]) {x1 = x1 - 1;y1 = y1 - 1;x2 = x2 + 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') { s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}} else if (z == 4 && a == chess[x1][y1]) {x1 = x1 + 1;y1 = y1 - 1;x2 = x2 - 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}}return false;}public static boolean isCenterNullTwo(char a) {if (z == 1 && a == chess[x1][y1]) {x1 = x1;y1 = y1 - 1;x2 = x2;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (a == 'o') {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1 + 2;} else {c1 = x1;c2 = y1 + 2;}return true;}} else {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1 + 2;} else {c1 = x1;c2 = y1 + 2;}return true;}if (chess[x1][y1] == '.') {c1 = x1;c2 = y1 + 2;return true;}if (chess[x2][y2] == '.') {c1 = x1;c2 = y1 + 2;return true;}}}} else if (z == 2 && a == chess[x1][y1]) {x1 = x1 - 1;y1 = y1;x2 = x2 + 1;y2 = y2;if (isNot(x1, y1) && isNot(x2, y2)) {if (a == 'o') {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1 + 2;c2 = y1;} else {c1 = x1 + 2;c2 = y1;}return true;} else {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1 + 2;} else {c1 = x1;c2 = y1 + 2;}return true;}if (chess[x1][y1] == '.') {c1 = x1;c2 = y1 + 2;return true;}if (chess[x2][y2] == '.') {c1 = x1;c2 = y1 + 2;return true;}}}}} else if (z == 3 && a == chess[x1][y1]) {x1 = x1 - 1;y1 = y1 - 1;x2 = x2 + 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (a == 'o') {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1 + 2;c2 = y1 + 2;} else {c1 = x1 + 2;c2 = y1 + 2;}return true;} else {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1 + 2;} else {c1 = x1;c2 = y1 + 2;}return true;}if (chess[x1][y1] == '.') {c1 = x1;c2 = y1 + 2;return true;}if (chess[x2][y2] == '.') {c1 = x1;c2 = y1 + 2;return true;}}}}} else if (z == 4 && a == chess[x1][y1]) {x1 = x1 + 1;y1 = y1 - 1;x2 = x2 - 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (a == 'o') {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1 - 2;c2 = y1 + 2;} else {c1 = x1 - 2;c2 = y1 + 2;}return true;} else {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1 + 2;} else {c1 = x1;c2 = y1 + 2;}return true;}if (chess[x1][y1] == '.') {c1 = x1;c2 = y1 + 2;return true;}if (chess[x2][y2] == '.') {c1 = x1;c2 = y1 + 2;return true;}}}}}return false;}public static boolean isNullTwo(char a) {if (z == 1 && a == chess[x1][y1]) {x1 = x1;y1 = y1 - 1;x2 = x2;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}} else if (z == 2 && a == chess[x1][y1]) {x1 = x1 - 1;y1 = y1;x2 = x2 + 1;y2 = y2;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') { s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}} else if (z == 3 && a == chess[x1][y1]) {x1 = x1 - 1;y1 = y1 - 1;x2 = x2 + 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') { s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}} else if (z == 4 && a == chess[x1][y1]) {x1 = x1 + 1;y1 = y1 - 1;x2 = x2 - 1;y2 = y2 + 1;if (isNot(x1, y1) && isNot(x2, y2)) {if (chess[x1][y1] == '.' && chess[x2][y2] == '.') {s = r.nextInt(2);if (s == 0) {c1 = x1;c2 = y1;} else {c1 = x2;c2 = y2;}return true;}}}return false;}public static boolean haveComputer() {for (int i = 1; i < chess.length; i++) {for (int j = 1; j < chess[0].length; j++) {if (chess[i][j] == 'x') {if (computerRational(i, j))return true;}}}return false;}public static boolean computerRational(int x, int y) {int i = 0;int[][] is = new int[2][8];if (y > 1 && chess[x][y - 1] == '.') {is[0][i] = x;is[1][i] = y - 1;i++;}if (y < chess[0].length - 1 && chess[x][y + 1] == '.') { is[0][i] = x;is[1][i] = y + 1;i++;}if (z == 2) {if (x > 1 && chess[x - 1][y] == '.') {。

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实现五子棋大战

java实现五子棋大战

java实现五⼦棋⼤战本⽂实例为⼤家分享了java实现五⼦棋⼤战的具体代码,供⼤家参考,具体内容如下这是我接近⼀年前的项⽬了,以前没有养成写博客的习惯,打算陆续把以前做过的项⽬补上来。

⼀、介绍主要实现的功能有棋⼦颜⾊选择,悔棋,重新开始,玩家对战和⼈机对战,效果图如图所是:模式选择:棋⼦选择:⼈机对战:玩家对战:⼆、具体实现五⼦棋的开发⾸先需要在界⾯上绘制⼀个表格,因为七班是不变的,棋⼦⼤⼩是不变的,所以我们⾸先可以⾃定义⼀个接⼝来设置项⽬中的常量,这样改变这些参数时也⽐较⽅便,CS.java代码如下:public interface CS {public static final int x0=60;//棋盘开始位置public static final int y0=70;public static final int line=15;//棋盘有多少条线public static final int size=40;//棋⼦⼤⼩}和上⼀篇博客中的画图板类似,⾸先需要⼀个界⾯,这⾥可以定义⼀个Chess类继承Jframe,然后再重写paint(Graphics g)⽅法,来绘制棋盘,Chess.java代码如下:Chess.java:public class Chess extends JFrame implements CS{int i=2;private qizi qizilarry2[][]=new qizi[line][line];//⽤qizi类型的⼆维数组来存储棋⼦private JButton b = new JButton("悔棋");private JButton b2=new JButton("重新开始");private JLabel jLabel=new JLabel("请选择对战模式");private JLabel jLabel2=new JLabel("请选择棋⼦颜⾊");private int value;//提⽰框选项的值private int value2;Dimension dimension=new Dimension(100, 30);String color[]= {"⽩棋","⿊棋"};String moshi[]= {"玩家对战","⼈机对战"};public void chessUI() {b.setPreferredSize(dimension);b2.setPreferredSize(dimension);this.setSize(700, 700);this.setLayout(new FlowLayout());this.setTitle("五⼦棋");this.setLocationRelativeTo(null);this.setDefaultCloseOperation(3);this.setVisible(true);this.add(b);this.add(b2);value=JOptionPane.showOptionDialog(this, jLabel, "提⽰", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null, moshi, null);value2=JOptionPane.showOptionDialog(this, jLabel2, "提⽰", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null, color, null);//关闭提⽰框则退出程序if(value==JOptionPane.CLOSED_OPTION||value2==JOptionPane.CLOSED_OPTION) {System.exit(1);}Graphics g=this.getGraphics();mouslistener mouslistener =new mouslistener(g,qizilarry2,this,value,value2);this.addMouseListener(mouslistener);//窗⼝添加监听b.addActionListener(mouslistener);//按钮添加监听b2.addActionListener(mouslistener);}public void paint(Graphics g) {//重绘棋盘和棋⼦super.paint(g);drawChess(g);drawQZ();}//画⼀个棋盘public void drawChess(Graphics g) {g.setColor(Color.black);for(int i=0;i<line;i++) {g.drawLine(x0, y0+size*i, x0+(line-1)*size, y0+size*i);}for(int j=0;j<line;j++) {g.drawLine(x0+size*j, y0, x0+size*j, y0+(line-1)*size);}}//重构画棋⼦public void drawQZ() {for(int ix=0;ix<line;ix++) {for(int iy=0;iy<line;iy++) {if(qizilarry2[ix][iy]!=null) {qizi qizi21=qizilarry2[ix][iy];qizi21.drawq();}}}}public static void main(String[] args) {new Chess().chessUI();}}⽤qizi类型的⼆维数组来存储棋⼦,在重绘时重绘整个棋盘和⼆维数组上的棋⼦,如果⼆维数组为null则不⽤重绘。

最新 java五子棋源代码(完整版)

最新 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) {}}。

Java编程实现五子棋人人对战代码示例

Java编程实现五子棋人人对战代码示例

Java编程实现五⼦棋⼈⼈对战代码⽰例利⽤Java,在控制台操作下,编写的五⼦棋,作为复习⼆维数组,⾯向对象等基础知识。

w表⽰⽩棋,b表⽰⿊棋import java.util.Scanner;public class MainMethod {public static char[][] c = new char[10][10];public static void main(String[] args) {MainMethod mainMethod = new MainMethod();mainMethod.init();int i;boolean color;int[] point = new int[2];Scanner scanner = new Scanner(System.in);for (i = 1; i < 100; i++) {mainMethod.draw();// 绘制棋盘System.out.println("请输⼊坐标,范围为(0,0)到(9,9)");int x = scanner.nextInt();int y = scanner.nextInt();if (i % 2 == 1)color = true;elsecolor = false;point[0] = x;point[1] = y;if (mainMethod.paint(point, color) == false) {//System.out.println("下的位置不合理,请重新开始");break;}if (mainMethod.win() == 1) {mainMethod.draw();System.out.println("恭喜⽩棋赢!!");break;} else if (mainMethod.win() == -1) {mainMethod.draw();System.out.println("恭喜⿊棋赢!!");break;}}if (i == 100)System.out.println("平局");}public char[][] init() {// 初始化棋盘for (int i = 0; i < c.length; i++) {for (int j = 0; j < c.length; j++) {c[i][j] = '+';}}return c;}public boolean paint(int[] point, boolean colr) {// 判断下的位置是否正确,若正确改变棋盘boolean b = true;int x = point[0];int y = point[1];if (inBoard(point) == false || c[x][y] == 'w' || c[x][y] == 'b' || x < 0) {b = false;return b;}else if (colr == true) {// ⽩棋下if (c[x][y] == '+') {c[x][y] = 'w';}}else if (colr == false) {// ⿊棋下if (c[x][y] == '+') {c[x][y] = 'b';}}return b;}public boolean inBoard(int[] point) {// 判断point是否在棋盘上int x = point[0];int y = point[1];if (x < 0 || y < 0 || x >= c.length || y >= c.length)return false;elsereturn true;}public int win() {// 判断输赢,1表⽰⽩的赢,-1⿊的赢,0暂⽆输赢int whoWin = 0;int[] point = new int[2];outer: while (true) {for (int i = 0; i < c.length; i++) {for (int j = 0; j < c.length; j++) {if (c[i][j] == 'w') {// 遍历数组,找到的第⼀个⽩棋point[0] = i;point[1] = j + 4;if (inBoard(point)) {// 如果存在向右数4个的棋盘if (c[i][j + 1] == 'w' && c[i][j + 2] == 'w' && c[i][j + 3] == 'w' && c[i][j + 4] == 'w') { whoWin = 1;break outer;}}point[0] = i + 4;point[1] = j + 4;if (inBoard(point)) {// 如果存在向右,向下数4个的棋盘if (c[i + 1][j + 1] == 'w' && c[i + 2][j + 2] == 'w' && c[i + 3][j + 3] == 'w'&& c[i + 4][j + 4] == 'w') {whoWin = 1;break outer;}}point[0] = i + 4;point[1] = j;if (inBoard(point)) {// 如果存在向下数4个的棋盘if (c[i + 1][j] == 'w' && c[i + 2][j] == 'w' && c[i + 3][j] == 'w' && c[i + 4][j] == 'w') { whoWin = 1;break outer;}}point[0] = i - 4;point[1] = j + 4;if (inBoard(point)) {// 如果存在向左,向下数4个的棋盘if (c[i - 1][j + 1] == 'w' && c[i - 2][j + 2] == 'w' && c[i - 3][j + 3] == 'w'&& c[i - 4][j + 4] == 'w') {whoWin = 1;break outer;}}} else if (c[i][j] == 'b') {point[0] = i;point[1] = j + 4;if (inBoard(point)) {// 如果存在向右数4个的棋盘if (c[i][j + 1] == 'b' && c[i][j + 2] == 'b' && c[i][j + 3] == 'b' && c[i][j + 4] == 'b') { whoWin = -1;break outer;}}point[0] = i + 4;point[1] = j + 4;if (inBoard(point)) {// 如果存在向右,向下数4个的棋盘if (c[i + 1][j + 1] == 'b' && c[i + 2][j + 2] == 'b' && c[i + 3][j + 3] == 'b'&& c[i + 4][j + 4] == 'b') {whoWin = -1;break outer;}}point[0] = i + 4;point[1] = j;if (inBoard(point)) {// 如果存在向下数4个的棋盘if (c[i + 1][j] == 'b' && c[i + 2][j] == 'b' && c[i + 3][j] == 'b' && c[i + 4][j] == 'b') { whoWin = -1;break outer;}}point[0] = i - 4;point[1] = j + 4;if (inBoard(point)) {// 如果存在向左,向下数4个的棋盘if (c[i - 1][j + 1] == 'b' && c[i - 2][j + 2] == 'b' && c[i - 3][j + 3] == 'b'&& c[i - 4][j + 4] == 'b') {whoWin = -1;break outer;}}}}}whoWin = 0;break outer;}return whoWin;}public void draw() {// 绘制棋盘for (int i = 0; i < c.length; i++) {for (int j = 0; j < c.length; j++) {System.out.print(c[i][j] + " ");}System.out.println();}}}运⾏结果:+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 请输⼊坐标,范围为(0,0)到(9,9)46+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + w + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 请输⼊坐标,范围为(0,0)到(9,9)65+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + w + + + + + + + + + + + + + + + + + + b + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 请输⼊坐标,范围为(0,0)到(9,9)谁输谁赢我就不弄出来了,太长,占地。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

//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(){}}。

相关文档
最新文档