java编程五子棋全程(完整版)

合集下载

java五子棋游戏

java五子棋游戏

程序代码:import java.util.*;import java.io.*;import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;class Gobang extends JFrame implements Runnable, ActionListener{final static int Player=1;final static int AI =-1;ClassLoader cl = this.getClass().getClassLoader();Toolkit tk = Toolkit.getDefaultToolkit();int length=14, game_state, winner, check, step;int grid[][] = new int[length][length];int locX, locY /* */, count /* 硈囱计*/, x, y /* */, displace_x=0, displace_y=0 /* */, direction;ArrayList steps = new ArrayList(); /* 癘魁囱˙*/JPopupMenu control_menu = new JPopupMenu(); /* */JMenuItem[] command = new JMenuItem[4];String[] command_str={"", "", "弄郎", ""};int[][] dir = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };boolean[] dir2 = new boolean[8];boolean turn;String message;final JDialog dialog = new JDialog(this, "", true);Font font=new Font("new_font", Font.BOLD, 20);Grid grids[][] = new Grid[length][length];Image white= tk.getImage(cl.getResource("res/white.png"));Image black= tk.getImage(cl.getResource("res/black.png"));Image title= tk.getImage(cl.getResource("res/title.png"));Image temp;JPanel boardPanel, bigpanel;JRadioButton[] choice = new JRadioButton[2];final static int Start =0;final static int Select =1;final static int Playing =2;final static int End =3;final static int nil=-1; /* */final static int oblique_1 =0; /* */final static int oblique_2 =1; /* */final static int horizontal =2; /* */final static int vertical=3; /* */Gobang(){super("");boardPanel = new JPanel();boardPanel.setLayout(new GridLayout(length, length, 0, 0));boardPanel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);for(int i=0; i<length; i++)for(int j=0; j<length; j++){grids[i][j] = new Grid(i, j);boardPanel.add(grids[i][j]);}bigpanel = new JPanel();bigpanel.add(boardPanel, BorderLayout.CENTER);getContentPane().add(bigpanel, BorderLayout.SOUTH);game_state=Start;ThreadStart();dialog.setSize(160, 100);dialog.setResizable(false);dialog.setLocationRelativeTo(null);ButtonGroup choice_group = new ButtonGroup();JPanel choice_menu = new JPanel();choice[0] = new JRadioButton("", new ImageIcon(black), true); choice[1] = new JRadioButton("", new ImageIcon(white));for(int i=0; i<choice.length; i++){choice_menu.add(choice[i]);choice_group.add(choice[i]);}for(int i=0; i<command.length; i++){command[i] =new JMenuItem(command_str[i]);command[i].addActionListener(this);control_menu.add(command[i]);}JButton select = new JButton("絋﹚");JPanel select_menu = new JPanel();select_menu.add(select);select.addActionListener(this);dialog.getContentPane().add(choice_menu, BorderLayout.NORTH); dialog.getContentPane().add(select_menu, BorderLayout.CENTER);setIconImage(title);setResizable(false);setSize(300, 335);setVisible(true);setLocationRelativeTo(null);}public static void main(String[] arg){Gobang application = new Gobang();application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);public void actionPerformed(ActionEvent event) {if( event.getSource().equals(command[0]) ) {if(steps.size()!=0)undo();}else if(event.getSource().equals(command[1]) ) Save();else if(event.getSource().equals(command[2]) ) Load();else if(event.getSource().equals(command[3]) ) ReStart();else{if(choice[1].isSelected()){temp=white;white=black;black=temp;}dialog.dispose();}}public void WinCheck(){check = turn? Player: AI;direction=oblique_1;WinCheck2();}public void WinCheck2(){count=1;switch(direction){case oblique_1: displace_x=1;displace_y=-1;direction=oblique_2;break;case oblique_2: displace_x=displace_y=1;direction=horizontal;break;case horizontal: displace_x=1;displace_y=0;direction=vertical;break;case vertical: displace_x=0;displace_y=1;direction=nil;break;}x=locX+displace_x;y=locY+displace_y;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check) {count=count+1;x=x+displace_x;y=y+displace_y;}x=locX-displace_x;y=locY-displace_y;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check) {count=count+1;x=x-displace_x;y=y-displace_y;}if(count>=5){game_state=End;winner=check;ThreadStart();}else if(direction!=nil)WinCheck2();}public void ReStart(){for(int i=0; i<length; i++)for(int j=0; j<length; j++)grids[i][j].Initial();winner=0;steps.clear();game_state=Playing;}public void gobangRandom(){displace_y=0;do{displace_x=(int)(Math.random()*8);x =locX+dir[displace_x][0];y =locY+dir[displace_x][1];if(!dir2[displace_x]){displace_y=displace_y+1;dir2[displace_x]=true;}}while((x<0 || x>=length || y<0 || y>=length || grid[x][y]!=0) && displace_y<8);for(int i=0; i<8; i++)dir2[i]=false;if(x>=0 && x<length && y>=0 && y<length && grid[x][y]==0)setMark(x, y);elsegobangRandom2();}private void gobangRandom2(){do{x=(int)(Math.random()*length);y=(int)(Math.random()*length);}while(grid[x][y]!=0);setMark(x, y);}private void gobangAI(){boolean play=true;for(int i=2; i>0; i--){play=!play;gobangAI4(play);if(turn)return;}for(int i=7; i>=4; i--){play=!play;step=i/2;gobangAI2(play);if(turn)return;}gobangAI5();if(!turn)gobangRandom();}private void gobangAI2(boolean player) {check = player? Player: AI;for(int i=0; i<length; i++)for(int j=0; j<length; j++){if(turn)break;if(grid[i][j] == check){count=1;direction=oblique_1;gobangAI3(i, j);}}}private void gobangAI3(int x, int y){if(count==1){locX=x;locY=y;}switch(direction){case oblique_1: displace_x=1;displace_y=-1;break;case oblique_2: displace_x=displace_y=1;break;case horizontal: displace_x=1;displace_y=0;break;case vertical: displace_x=0;displace_y=1;break;}x=x+displace_x;y=y+displace_y;if(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check){count=count+1;if(count==step){if(x+displace_x>=0 && x+displace_x<length && y+displace_y>=0 && y+displace_y<length && grid[x+displace_x][y+displace_y]==0){if(x-step*displace_x<0 || x-step*displace_x>=length || y-step*displace_y<0 || y-step*displace_y>=length || !gobang_SpaceAI(x+displace_x, y+displace_y) || (grid[x-step*displace_x][y-step*displace_y]!=0 && step<3) ) /* */gobangAI3_2();elsesetMark2(x+displace_x, y+displace_y);}elsegobangAI3_2();}elsegobangAI3(x, y);}elsegobangAI3_2();}private void gobangAI3_2(){if(direction!=vertical){count=1;direction=direction+1;gobangAI3(locX, locY);}}private void gobangAI4(boolean player){check = player? Player: AI;for(int i=0; i<length; i++)for(int j=0; j<length; j++){if(turn)break;if(grid[i][j]==0){direction=oblique_1;locX=i;locY=j;gobangAI4();}}}private void gobangAI4(){count=0;switch(direction){case oblique_1: displace_x=1;displace_y=-1;direction=oblique_2;break;case oblique_2: displace_x=displace_y=1;direction=horizontal;break;case horizontal: displace_x=1;displace_y=0;direction=vertical;break;case vertical: displace_x=0;displace_y=1;direction=nil;break;}x=locX+displace_x;y=locY+displace_y;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check) {count=count+1;x=x+displace_x;y=y+displace_y;}x=locX-displace_x;y=locY-displace_y;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==check) {count=count+1;x=x-displace_x;y=y-displace_y;}if(count>=4)setMark(locX, locY);else if(direction!=nil)gobangAI4();}private void gobangAI5(){for(int i=0; i<length; i++)for(int j=0; j<length; j++){if(turn)break;if(grid[i][j]==-1){direction=oblique_1;locX=i;locY=j;gobangAI5_2();}}}/* */private void gobangAI5_2(){count=0;switch(direction){case oblique_1: displace_x=1;displace_y=-1;direction=oblique_2;break;case oblique_2: displace_x=displace_y=1;direction=horizontal;break;case horizontal: displace_x=1;displace_y=0;direction=vertical;break;case vertical: displace_x=0;displace_y=1;direction=nil;break;}x=locX+displace_x;y=locY+displace_y;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==0 && count<4) {count=count+1;x=x+displace_x;y=y+displace_y;}x=locX-displace_x;y=locY-displace_y;if(count==4 && x>=0 && x<length && y>=0 && y<length && grid[x][y]==0) setMark(locX+displace_x, locY+displace_y);else if(count>1){count = count==4? 3: count;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==0 && count<4) {count=count+1;x=x-displace_x;y=y-displace_y;}if(count==4)setMark(locX+displace_x, locY+displace_y);else if(direction!=nil)gobangAI5_2();}else if(direction!=nil)gobangAI5_2();}private boolean gobang_SpaceAI(int x, int y) /* */{int space=0;do{space=space+1;x=x+displace_x;y=y+displace_y;}while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==0 && space<4);if(space+count>=5) /* Τ*/return true;else{space=0;x=locX-displace_x;y=locY-displace_y;while(x>=0 && x<length && y>=0 && y<length && grid[x][y]==0 && space<4){space=space+1;x=x-displace_x;y=y-displace_y;}if(space+count>=5) /* Τ*/return true;elsereturn false;}}public void ThreadStart(){new Thread(this).start();}private void setMark(int x, int y){steps.add(grids[x][y]);grids[x][y].setValue(-1);WinCheck();turn=true;}/* Τ*/private void setMark2(int x, int y){int space=0, temp_x=x, temp_y=y;do{space=space+1;temp_x=temp_x+displace_x;temp_y=temp_y+displace_y;}while(temp_x>=0 && temp_x<length && temp_y>=0 && temp_y<length && grid[temp_x][temp_y]==0 && space<4);if(space+step>=5)setMark(x, y);elsesetMark(x-(step+1)*displace_x, y-(step+1)*displace_y); /* э*/ }public void run(){try{switch(game_state){case Start: Thread.sleep(2000);dialog.show();game_state=Playing;repaint();break;case End: repaint();Thread.sleep(1500);ReStart();repaint();break;}}catch(InterruptedException ex){}}public void paint(Graphics g){super.paint(g);switch(game_state){case Start: g.drawString("wu zi qi", 91, 240);g.setFont(font);g.setColor(Color.BLUE);g.drawString("Gobang", 112, 120);g.drawImage(title, 134, 135, this);break;case Playing:case End:g.drawString(": 筿福:", 105, 40);g.drawImage(black, 132, 30, this);g.drawImage(white, 182, 30, this);if(winner!=0){g.setFont(font);g.setColor(Color.RED);message = winner==1? "":"";g.drawString(message, 120, 185);}break;}}public void undo(){if(steps.size()>0){for(int i=0; i<2; i++){((Grid)steps.get(steps.size()-1)).Initial();steps.remove(steps.size()-1);}}}private void Save(){String str;try{File file = new File("innings.men");file.createNewFile();BufferedWriter write = new BufferedWriter(new FileWriter(file));for(int i=0; i<steps.size(); i++){str=(((Grid)steps.get(i)).getLocX())+","+(((Grid)steps.get(i)).getLocY())+","+(((Grid)steps.get(i)).get Value());write.write(str);write.newLine();}write.close();}catch(Exception ex){}}private void Load(){try{String[] step_array;String str;File file = new File("innings.men");if(!file.exists()){JOptionPane.showMessageDialog(null, "⊿Τ");return;}BufferedReader read = new BufferedReader(new FileReader(file));ReStart();while(read.ready()){str=read.readLine();step_array=str.split(",");grids[Integer.parseInt(step_array[0])][Integer.parseInt(step_array[1])].setValue(Integer.parseInt(st ep_array[2]));steps.add(grids[Integer.parseInt(step_array[0])][Integer.parseInt(step_array[1])]);}}catch(Exception ex){}}private class Grid extends JPanel implements MouseListener {int x, y, value;boolean selected;public Grid(int x, int y){this.x=x;this.y=y;addMouseListener(this);}public void mousePressed(MouseEvent event){if(game_state==Playing){int button=event.getButton();if(button==MouseEvent.BUTTON1){if(value==0){steps.add(this);setValue(1);WinCheck();turn=false;if(game_state==Playing)gobangAI();}}elsecontrol_menu.show(this, event.getX(), event.getY()); }}public void mouseEntered(MouseEvent event){if(game_state==Playing)setSelected(true);}public void mouseExited(MouseEvent event) {if(game_state==Playing)setSelected(false);}public void mouseClicked(MouseEvent event) {}public void mouseReleased(MouseEvent event) {}public Dimension getPreferredSize(){return new Dimension(20, 20);}public Dimension getMinimumSize(){return getPreferredSize();}public int getLocX(){return x;}public int getLocY(){return y;}public int getValue(){return value;}public void Initial(){value=grid[x][y]=0;selected=false;repaint();}public void setValue(int new_value){locX=x;locY=y;value=grid[x][y]=new_value;repaint();}public void setSelected(boolean select){selected=select;repaint();}public void paintComponent(Graphics g){super.paintComponent(g);if(game_state!=Start && game_state!=Select) {g.drawLine(0, 10, 19, 10);g.drawLine(10, 0, 10, 19);/* 礶娩絬*/g.setColor(Color.BLUE);if(x==0)g.drawLine(0, 0, 19, 0);else if(x==length-1)g.drawLine(0, 19, 19, 19);if(y==0)g.drawLine(19, 0, 19, 19);else if(y==length-1)g.drawLine(0, 0, 0, 19);if(selected)setBackground(Color.WHITE);elsesetBackground(Color.LIGHT_GRAY);}//g.drawString(x+" "+y, 1, 10);if(value!=0){temp = value==1? black: white;g.drawImage(temp, 4, 4, this);}}}}。

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

/*********WZQMIDlet.java*********/import javax.microedition.lcdui.Display;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;public class WZQMIDlet extends MIDlet {wuziqi canvas;public WZQMIDlet() {}protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}protected void pauseApp() {}protected void startApp() throws MIDletStateChangeException {canvas=new wuziqi(Display.getDisplay(this));}}/**************wuziqi.java**************/import java.io.IOException;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Graphics;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.GameCanvas;import yer;import yerManager;import javax.microedition.lcdui.game.Sprite;class wuziqi extends GameCanvas implements Runnable {Display display;Image qp; //棋盘图片Sprite white ,black; //棋子图片Sprite gb; //光标int []gbx=new int[13];//光标x坐标int []gby=new int[13]; //光标y坐标int sleeping; //循环间隔时间int w; //棋子的宽度int []qpx=new int[13]; //棋盘放置棋子的位置的x坐标int []qpy=new int[13]; //棋放置棋子的位置的y坐标int [][]zb =new int[13][13]; //判断每个位置是否放置了棋子,0表示还没有放置棋子, //1表示放置白棋,2表示放置了黑棋int qp0x; //存放棋盘0格子的x坐标int qp0y; //存放棋盘0格子的y坐标int x=6,y=6;xq xq;LayerManager layer;String pd; //判断输赢;//构造函数public wuziqi(Display d) {super(true);display=d;display.setCurrent(this);//载入图片try {qp=Image.createImage("/qp.png");white=new Sprite(Image.createImage("/White.png"));black=new Sprite(Image.createImage("/Black.png"));gb=new Sprite(Image.createImage("/gb.png"));w=gb.getHeight();gbx[x]=qp.getWidth()/2-w/2; //光标x坐标gby[y]=qp.getHeight()/2-w/2;//光标y坐标gb.setPosition(gbx[6],gby[6]); //设置光标初始坐标} catch (IOException e) {e.printStackTrace();}qp0x=qp.getWidth()/2-6*16-w/2;//棋盘0格子的x坐标qp0y=qp.getHeight()/2-6*16-w/2;//棋盘0格子的y坐标//初始化存放棋盘横,纵的坐标for(int i=0;i<=12;i++){qpx[ i ]=qp0x+16*i;}for(int i=0;i<=12;i++){qpy=qp0y+16*i;}//true or falsefor(int i=0;i<=12;i++){for(int j=0;j<=12;j++)zb[j]=0;}sleeping=200;layer=new LayerManager();layer.append(gb);(new Thread(this)).start(); // 载入线程}public void run() {Graphics g=getGraphics();while(true){update();draw(g);try {Thread.sleep(sleeping);} catch (InterruptedException e) {e.printStackTrace();}}}private void update() {keyboard(); //响应键盘;layer.setViewWindow(0, 0, getWidth(), getHeight()); pd();}private void keyboard() {int key;key=getKeyStates();if((key&LEFT_PRESSED)!=0){if(x==0)gb.setPosition(gbx[x], gby[y]);else{x--;gbx[x]=qpx[x];gb.setPosition(gbx[x], gby[y]);}}elseif((key&RIGHT_PRESSED)!=0){if(x==12)gb.setPosition(gbx[x], gby[y]);else{x++;gbx[x]=qpx[x];gb.setPosition(gbx[x], gby[y]);}}else if((key&UP_PRESSED)!=0){if(y==0)gb.setPosition(gbx[x], gby[y]);else{y--;gby[y]=qpy[y];gb.setPosition(gbx[x], gby[y]);}}else if((key&DOWN_PRESSED)!=0){if(y==12)gb.setPosition(gbx[x], gby[y]);else{y++;gby[y]=qpy[y];gb.setPosition(gbx[x], gby[y]);}}if((key&FIRE_PRESSED)!=0) //放下棋子 {if(zb[x][y]==0){xq=new xq(gbx[x],gby[y], layer);layer=xq.rtn();zb[x][y]=xq.rn();}}}private void pd() {//纵向4个连续就胜利 for(int i=0;i<=12;i++) for(int j=0;j<=9;j++)for(int k=1;k<=3;k++) {if(zb[j]!=0){if(zb[j]!=zb[j+k])break;else if(k==3){if(zb[j]==1)pd="White win";else if(zb[j]==2)pd="black win";}}}//横向4个连续就胜利 for(int i=0;i<=9;i++)for(int j=0;j<=12;j++)for(int k=1;k<=3;k++) {if(zb[j]!=0){if(zb[j]!=zb[i+k][j])break;else if(k==3){if(zb[j]==1)pd="White win";else if(zb[j]==2)pd="black win";}}}// 左上到右下4个连续就胜利for(int i=3;i<=9;i++)for(int j=3;j<=9;j++)for(int k=1;k<=3;k++){if(zb[j]!=0){if(zb[j]!=zb[i+k][j+k])break;else if(k==3){if(zb[j]==1)pd="White win";else if(zb[j]==2)pd="black win";}}}// 左下到右上4个连续就胜利for(int i=3;i<=9;i++)for(int j=3;j<=9;j++)for(int k=1;k<=3;k++){if(zb[j]!=0){if(zb[j]!=zb[i+k][j-k])break;else if(k==3){if(zb[j]==1)pd="White win";else if(zb[j]==2)pd="black win";}}}}//进行绘画public void draw(Graphics g){g.drawImage(qp, 0, 0, Graphics.TOP|Graphics.LEFT);layer.paint(g,0,0);if(pd=="White win"){g.setColor(255,255,255);g.fillRect(0, 0, getWidth(), getHeight());g.setColor(0,0,0);g.drawString(pd, 100, 100, 0);}else if(pd=="black win"){g.setColor(255,255,255);g.fillRect(0, 0, getWidth(), getHeight());g.setColor(0,0,0);g.drawString(pd, 100, 100, 0);}flushGraphics();}}/**************xq.java*************/import java.io.IOException;import javax.microedition.lcdui.Image;import javax.microedition.lcdui.game.GameCanvas;import yerManager; import javax.microedition.lcdui.game.Sprite;/*放下棋子并且返回layer*/public class xq extends GameCanvas {int x; //光标横坐标int y; //光标纵坐标Sprite white;Sprite black;LayerManager layer;static int pd=1; //判断下黑棋还是白棋,1下白棋,0下黑棋public xq(int a,int b,LayerManager l){super(true);x=a;y=b;layer=l;try {if(pd==1)white=new Sprite(Image.createImage("/White.png"));elseblack=new Sprite(Image.createImage("/Black.png")); } catch (Exception e) {e.printStackTrace();}keyboard();}public void keyboard(){if(pd==1){white.setPosition(x, y);layer.append(white);pd=0;}else{black.setPosition(x, y);layer.append(black);pd=1;}}public LayerManager rtn() {// TODO Auto-generated method stubreturn layer;}// 如果下白棋,返回1 。

Java五子棋源代码

Java五子棋源代码

Java五子棋源代码本程序共有3个类,下载后将三个类复制到三个记事本里然后重名记事本(为了阅读方便分三个文件),其中main()方法在StartChessJFrame 类中。

我是菜鸟,交流QQ:609429837import java.awt.Color;public class Point {private int x;//棋盘中X的索引private int y;//棋盘中Y的索引private Color color;//颜色public static final int DIAMETER = 30;//直径public Point(int x,int y,Color color){ this.x=x;this.y=y;this.color =color;}//拿到棋盘中的Y索引public int getX(){return x;}public int getY(){return y;}//得到颜色public Color getColor(){return color;}}import javax.swing.*;import java.awt.*;import java.awt.event.MouseListener; importjava.awt.event.MouseMotionListener; import java.awt.event.MouseEvent;/*五子棋-棋盘类*/public class ChessBoard extends JPanel implements MouseListener {public static final int MARGIN = 30;//边距protected static final int GRID_SPAN = 35;//网格间距public static final int ROWS = 10;//棋盘行数public static final int COLS = 10;//棋盘列数Point[] chessList = new Point[(ROWS+1)*(COLS+1)];//初始化每个数组元素为nullboolean isBlack = true;//默认开始是黑棋先下boolean gameOver = false;//游戏是否结束int chessCount;//当前棋盘棋子的个数int xIndex,yIndex;//当前刚下的棋子的索引public ChessBoard(){super.setBackground(Color.ORANGE);//setBackground(Color.ORANGE);//设置背景颜色为橘黄色addMouseListener(this);//添加监听器addMouseMotionListener(new MouseMotionListener(){//匿名内部类public void mouseDragged(MouseEvent e){}public void mouseMoved(MouseEvent e){int x1 = (e.getX()- MARGIN +GRID_SPAN/2)/GRID_SPAN;//将鼠标单击的坐标位置转换成网格索引int y1 = (e.getY()- MARGIN +GRID_SPAN/2)/GRID_SPAN;//游戏已经结束,落在棋盘外,x、y 位置已经有棋子存在,不能下if(x1<0||x1>ROWS||y1<0||y1>COLS||gameOv er||findChess(x1,y1))setCursor(newCursor(Cursor.DEFAULT_CURSOR));//设置成默认形状elsesetCursor(newCursor(Cursor.HAND_CURSOR));//设置成手型}});}//绘制public void paintComponent(Graphics g){ super.paintComponent(g);//画棋类for(int i=0;i<=ROWS;i++){//画横线g.drawLine(MARGIN,MARGIN+i*GRID_SPAN,MARGIN+COLS*GRID_SPAN,MARGIN+i*GRID_SPAN);}for(int i=0;i<=COLS;i++){//画直线g.drawLine(MARGIN+i*GRID_SPAN,MARGIN,MA RGIN+i*GRID_SPAN,MARGIN+ROWS*GRID_SPAN);}//画棋子for(int i=0;i<chessCount;i++) {int xPos = chessList[i].getX()*GRID_SPAN+MARGIN;//网络交叉点的x坐标int yPos = chessList[i].getY()*GRID_SPAN+MARGIN;//网络交叉点的y坐标g.setColor(chessList[i].getColor());//设置颜色g.fillOval(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER);//标记最后一个棋子的红矩形框if(i == chessCount -1){//最后一个棋子g.setColor(Color.red);g.drawRect(xPos - Point.DIAMETER/2,yPos-Point.DIAMETER/2,Po int.DIAMETER,Point.DIAMETER);}}}//鼠标按键在组建上按下时调用public void mousePressed(MouseEvent e){ //游戏已经结束,不能下if(gameOver)return;String colorName = isBlack ?"黑棋":"白棋";xIndex = (e.getX() - MARGIN + GRID_SPAN/2)/GRID_SPAN;//将鼠标单击的坐标位置转换成网格索引yIndex = (e.getY() - MARGIN + GRID_SPAN/2)/GRID_SPAN;//落在棋盘外,不能下if(xIndex <0 || xIndex > ROWS || yIndex < 0 || yIndex > COLS)return;//x、y位置都已经有棋子存在,不能下if(findChess(xIndex , yIndex))return;Point ch = new Point(xIndex,yIndex,isBlack ? Color.black:Color.white);chessList[chessCount++] = ch;repaint();//通知系统重新绘制if(isWin()){//给出胜利信息,不能再继续下棋String msg = String.format("恭喜,%s赢了!", colorName);JOptionPane.showMessageDialog(this, msg);gameOver = true;}isBlack = !isBlack;}//覆盖MouseListener的方法public void mouseClicked(MouseEvent e){ }//鼠标按键在组件上单击(按下并释放)时调用public void mouseEntered(MouseEvent e){ }//鼠标进入到组件上时调用public void mouseExited(MouseEvent e){ }//鼠标离开组件时调用public void mouseReleased(MouseEvent e){ }//鼠标离开组件时调用//在棋子数组中查找是否有索引为x、y的棋子存在private boolean findChess(int x, int y){ for(Point c : chessList){if(c !=null && c.getX() == x && c.getY() == y)return true;}return false;}//判定哪方赢private boolean isWin(){int continueCount =1;//连续棋子的个数//横向向西寻找for(int x = xIndex-1; x>=0;x--){Color c = isBlack ? Color.black : Color.white;if(getChess(x,yIndex,c) !=null){continueCount++;}elsebreak;}//横向向东寻找for(int x =xIndex+1;x<=ROWS;x++){ Color c = isBlack ? Color.black : Color.white;if(getChess(x,yIndex,c) !=null){continueCount++;}elsebreak;}//判定记录数大于等于五,即表示此方取胜if(continueCount>=5){return true;}elsecontinueCount =1;//继续另一种情况的搜索:纵向//纵向向上寻找for(int y = yIndex - 1; y >= 0; y--){ Color c =isBlack ? Color.black : Color.white;if(getChess(xIndex,y,c) !=null){continueCount++;}elsebreak;}//纵向向下寻找for(int y = yIndex + 1; y<=ROWS; y++){ Color c = isBlack ? Color.black : Color.white;if(getChess(xIndex,y,c)!=null){continueCount++;}elsebreak;}if(continueCount>=5){return true;}elsecontinueCount =1;//继续另一种情况的搜索:斜向//东北寻找for(int x = xIndex + 1,y=yIndex-1; y>=0 && x<=COLS; x++,y--){Color c = isBlack ? Color.black : Color.white;if(getChess(x,y,c)!=null){continueCount++;}elsebreak;}//西南寻找for(int x = xIndex - 1,y=yIndex+1; y<=ROWS && x>=0; x--,y++){Color c = isBlack ? Color.black : Color.white;if(getChess(x,y,c)!=null){continueCount++;}elsebreak;}if(continueCount >=5){return true;}elsecontinueCount = 1;//继续另一种情况的搜索:斜向//西北寻找for(int x = xIndex - 1,y = yIndex-1; y>=0 && x>=0; x--,y--){Color c = isBlack ? Color.black : Color.white;if(getChess(x,y,c)!=null){continueCount++;}elsebreak;}//西南寻找for(int x = xIndex + 1,y=yIndex+1; y<=ROWS && x<=COLS; x++,y++){Color c = isBlack ? Color.black : Color.white;if(getChess(x,y,c)!=null){continueCount++;}elsebreak;}if(continueCount >=5){return true;}elsecontinueCount = 1;return false;}private Point getChess(int xIndex, intyIndex, Color color){for(Point c: chessList){if(c !=null && c.getX() == xIndex && c.getY() == yIndex && c.getColor() == color)return c;}return null;}public void restartGame(){//清除棋子for(int i=0; i< chessList.length; i++) chessList[i]=null;//恢复游戏相关的变量值isBlack = true;gameOver = false;//游戏是否结束chessCount = 0;//当前棋盘的棋子个数//System.out.println(this.toString());//repaint();}//悔棋public void goback(){if (chessCount == 0)return;chessList[chessCount-1]=null;chessCount--;if(chessCount >0){xIndex = chessList[chessCount -1].getX();yIndex = chessList[chessCount -1].getY();}isBlack = !isBlack;//repaint();}//Dimension:矩形public Dimension getPreferredSize(){ return new Dimension (MARGIN*2 + GRID_SPAN*COLS,MARGIN*2 + GRID_SPAN*ROWS);}}import java.awt.BorderLayout;import java.awt.Color;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;public class StartChessJFrame extends JFrame {private ChessBoard chessBoard;//对战面板private JPanel toolbar;//工具条面板private JButton startButton;private JButton backButton;private JButton exitButton;//“重新开始”按钮,“悔棋”按钮,“退出”按钮private JMenuBar menuBar;//菜单栏private JMenu sysMenu;//系统菜单private JMenuItem startMenuItem;private JMenuItem exitMenuIatem;private JMenuItem backMenuItem;//“重新开始”,“退出”和“悔棋”菜单项public StartChessJFrame(){setTitle("单机版五子棋");//设置标题chessBoard =new ChessBoard();//初始化面板对象//创建和添加菜单menuBar = new JMenuBar();//初始化菜单栏sysMenu = new JMenu("系统");//初始化菜单startMenuItem = new JMenuItem("重新开始");exitMenuIatem = new JMenuItem("退出");backMenuItem = new JMenuItem("悔棋");//初始化菜单项sysMenu.add(startMenuItem);//将三个菜单项添加到菜单上sysMenu.add(backMenuItem);sysMenu.add(exitMenuIatem);MyItemListener lis = new MyItemListener();//初始化按钮事件监听器内部类this.startMenuItem.addActionListener(li s);//将三个菜单项注册到事件监听器上backMenuItem.addActionListener(lis);exitMenuIatem.addActionListener(lis);menuBar.add(sysMenu);//将“系统”菜单添加到菜单栏上setJMenuBar(menuBar);//将menuBar设置为菜单栏toolbar =new JPanel();//工具面板实例化startButton = new JButton("重新开始");//三个按钮初始化backButton = new JButton("悔棋");exitButton = new JButton("退出");toolbar.setLayout(newFlowLayout(FlowLayout.LEFT));//将工具面板按钮用FlowLayout布局toolbar.add(startButton);//将三个按钮添加到工具面板上toolbar.add(backButton);toolbar.add(exitButton);startButton.addActionListener(lis);//将三个按钮注册监听事件backButton.addActionListener(lis);exitButton.addActionListener(lis);add(toolbar,BorderLayout.SOUTH);//将工具面板布局到界面“南”方也就是下面add(chessBoard);//将面板对象添加到窗体上setDefaultCloseOperation(JFrame.EXIT_ON _CLOSE);//设置界面关闭事件//setSize(600,650);pack();//自适应大小}//事件监听器内部类private class MyItemListener implements ActionListener{public void actionPerformed(ActionEvent e){Object obj = e.getSource();//取得事件源if(obj == StartChessJFrame.this.startMenuItem || obj ==startButton){//重新开始//JFiveFrame.this //内部类引用外部类System.out.println("重新开始...");chessBoard.restartGame();repaint();}else if (obj == exitMenuIatem || obj == exitButton){System.exit(0);//结束应用程序}else if (obj == backMenuItem || obj == backButton){//悔棋System.out.println("悔棋...");chessBoard.goback();repaint();}}}public static void main(String[] args){ StartChessJFrame f = newStartChessJFrame();//创建主框架f.setVisible(true);//显示主框架}}。

java课程设计五子棋游戏完整版

java课程设计五子棋游戏完整版

沈阳大学沈阳大学沈阳大学沈阳大学沈阳大学沈阳大学沈阳大学沈阳大学算下一步棋,isMatrix位true参数为插入点棋格坐标,否则参数为插入点像素坐标。

当游戏结束的时候使用Graphics g调用方法,在游戏过程中如果是黑方或是白方获胜在棋盘中就会显示是哪方获胜。

3.设计结果与分析(1)当进入到游戏当中可以选择是哪个颜色的棋先出,选择好之后便可以单机开始进行下棋,如果在游戏过程中出现什么问题可以单机再来一局重新开始游。

五子棋游戏的主界面如图2所示:图2.程序主界面(2)如果实黑棋先开始那么开始后的界面中先出的棋显示的是黑棋,如果是白棋先出则显示的是白棋,以黑棋为例如图3所示:沈阳大学图3.黑棋先出的界面图(3)对于五子棋游戏,无论人机对战,还是双人对战,都需要判断棋盘上是否存在五子连珠情况,这既是游戏名字的由来,也是游戏结束的标志。

判断五子连珠的原理是从横,竖,左斜线,右斜线4条线上判断是否存在5个相连的同类棋子,黑棋的五个棋子在横、竖或斜方向上连接成一线即为该方赢如图4所示:沈阳大学图4.游戏结束界面(4)白棋的五个棋子在横、竖或斜方向上连接成一线即为该方赢如图4所示:沈阳大学图5.白棋胜利界面图4.设计体会通过这次课程设计,我进一步加深对基础理论的理解,扩大专业知识面,对收集资料、查阅文献、方案制定等实践方面得到了很好的锻练,促进对所学知识应用能力的提高。

同时我渐渐的复习了Java使用方法和编程语法,之后的编程过程也相对得心应手,基本完成了预期计划的要求。

在此感谢我的指导老师—原玥老师,她在课题的研究上不遗余力的给予指导。

她严谨的治学态度深深的影响了我,使我受益匪浅!这个课设题对我来说有一定的挑战性,因为我自己也不知道自己到底学到了一个什么样的境界。

但可以肯定,这个课设题的要求绝对在我的能力范围以上。

之所以选择这个题目是想逼着自己去查更多的资料,学到更多的东西。

结果也确实是这样的,我在这次课设中学到了不少东西,也理解了许多原来不理解的东西。

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、游戏效果是通过画笔画在组件上实现的,获取画笔:图形显⽰在哪个组件上,画笔就从该组件上获取。

JAVA课程设计 五子棋(内附完整代码)

JAVA课程设计 五子棋(内附完整代码)

JAVA课程设计设计题目:五子棋游戏一.简要的介绍五子棋1.五子棋的起源五子棋,又被称为“连五子、五子连、串珠、五目、五目碰、五格、五石、五法、五联、京棋”。

五子棋相传起源于四千多年前的尧帝时期,比围棋的历史还要悠久,可能早在“尧造围棋”之前,民间就已有五子棋游戏。

有关早期五子棋的文史资料与围棋有相似之处,因为古代五子棋的棋具与围棋是完全相同的。

2.现在五子棋标准棋盘(如图所示)3.五子棋的棋子五子棋采用两种颜色棋子,黑色棋子和白色棋子,和围棋相同,4.五子棋规则五子棋就是五个棋子连在一起就算赢,黑棋先行,下棋下在棋盘交叉线上,由于黑棋先行,优势太大,所以对黑棋设了禁手,又规定了“三手交换”,就是黑棋下第 2 手棋,盘面第 3 着棋之后,白方在应白 2 之前,如感觉黑方棋形不利于己方,可出交换,即执白棋一方变为执黑棋一方。

和“五手两打法”,就是黑棋在下盘面上关键的第 5 手时,必须下两步棋,让白方在这两步棋中任选一步,然后再续下。

不过一般爱好者不需要遵循这么多规则。

二.程序流程三.代码设计与分析main方法创建了ChessFrame类的一个实例对象(cf),并启动屏幕显示显示该实例对象。

public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}用类ChessFrame创建五子棋游戏主窗体和菜单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;class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"标准棋盘","改进棋盘","扩大棋盘"}; 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(14,14);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", null,"棋盘",null,"模式", null, "退出"}, this));JMenu lookMenu =new JMenu("外观");mbar.add(makeMenu(lookMenu,new Object[] {"类型一","类型二","类型三"},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 * 24, h * 27);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 >= 0){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("类型三"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("类型二"))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("标准棋盘")){this.width=14;this.height=14;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("改进棋盘")){this.width=18;this.height=18;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("扩大棋盘")){this.width=22;this.height=22;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(null, "第一版", "版本",JOptionPane.PLAIN_MESSAGE );if(arg.equals("退出"))System.exit(0);}}用类ChessModel实现了整个五子棋程序算法的核心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;class ChessModel {规定棋盘的宽度、高度、棋盘的模式private int width,height,modeChess;规定棋盘方格的横向、纵向坐标private int x=0,y=0;棋盘方格的横向、纵向坐标所对应的棋子颜色,数组arrMapShow只有3个值:1,2,3,-1,其中1代表该棋盘方格上下的棋子为黑子,2代表该棋盘方格上下的棋子为白子,3代表为该棋盘方格上没有棋子,-1代表该棋盘方格不能够下棋子private int[][] arrMapShow;交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(14, 14, modeChess);}if(modeChess == 2){PanelInit(18, 18, modeChess);}if(modeChess == 3){PanelInit(22, 22, 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] = -1;}}}获取是否交换棋手的标识符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;判断右边for(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;}判断左边x_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;判断上面x_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;}判断下面y_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;判断左上方x_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;}判断右下方x_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;判断右上方x_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;}判断左下方x_temp1=x_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++){x_temp1-=1;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++){y_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,"你赢了","结果",RMATION_MESSAGE);}输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了","结果",RMATION_MESSAGE);}}用类MainPanel主要完成如下功能:1、构建一个面板,在该面板上画上棋盘;2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)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;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.darkGray);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();}}import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;响应退出窗口class ChessWindowEvent extends WindowAdapter{public void windowClosing(WindowEvent e){System.exit(0);}ChessWindowEvent(){}}四.程序调试与运行运行:标准棋盘改进棋盘:扩大棋盘:外观类型二:外观类型三:人机对战:结果:五.结论通过对五子棋游戏的编写,使自己对java语言有了更深的了解。

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语言)

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

JAVA五子棋

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;public class WuZiQi extends KeyAdapter{boolean start=false;JFrame frame;Thread timerThread;int h,l;//¶¨Òå±äÁ¿int pans[][] =new int[11][11]; //±äÁ¿³õʼֵint gbx=5;int gby=5;int ziShu=0;int shui=0;WuZiQi(){frame = new JFrame("Îå×ÓÆå");frame.getContentPane().add(new Screen());frame.addKeyListener(this);frame.setSize(12*40+5*2,12*40+22+5*2+100);//´°¿Ú´óС frame.setVisible(true);frame.repaint();frame.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){ System.exit(0);}});//¹Ø±Õ´°Ìå}public void keyPressed(KeyEvent evt){switch(evt.getKeyCode()){ case KeyEvent.VK_ENTER:if(ziShu%2==0)//×ÓÊýÀ´ÅжÏË-Ó®{heiXia();}else{baiXia();}shui=shuiYing();break;case KeyEvent.VK_ESCAPE:System.exit(1);break;case KeyEvent.VK_LEFT:guangBiaoDong(-1,0);//¹â±ê¶¯µÄ×ø±êbreak;case KeyEvent.VK_RIGHT:guangBiaoDong(1,0);//¹â±ê¶¯µÄ×ø±êbreak;case KeyEvent.VK_DOWN:guangBiaoDong(0,1);//¹â±ê¶¯µÄ×ø±êbreak;case KeyEvent.VK_UP:guangBiaoDong(0,-1);//¹â±ê¶¯µÄ×ø±êbreak;}frame.repaint();}class Screen extends JComponent{public void paint(Graphics g){Graphics2D g2d=(Graphics2D)g;xianShi(g2d);//»-ͼ}}public static void main(String[] args){new WuZiQi();}void xianShi(Graphics2D g2d)//ÏÔʾ{xianShiQiPan(g2d);//ÏÔʾÆåÅÌxianShiQiZis(g2d);//ÏÔʾÆì×ÓxianShiGuangBiao(g2d);//ÏÔʾ¹â±êg2d.setFont(new Font("STXingkai",1,30));//0708µÚ¶þС×é g2d.setColor(Color.black);g2d.drawString("0708µÚ¶þС×é",280,580);g2d.setFont(new Font("stCaiyun",1,40));if(shui==0)//ÅжÏ{g2d.setColor(Color.black);xianShiTiShiXia(g2d);// ÏÔʾË-ÏÂÆå}else{g2d.setColor(Color.black);xianShiTiShiYing(g2d); //ÏÔʾË-Ó®Æå}}void guangBiaoDong(int fangX,int fangY)////¹â±ê¶¯{if(gbx+fangX>10 || gbx+fangX<0 || gby+fangY>10 || gby+fangY<0) {}else{gbx=gbx+fangX;gby=gby+fangY;}}void heiXia()//ºÚÆå{if(pans[gby][gbx]==0){pans[gby][gbx]=-1;ziShu++;}}void baiXia()//°×Æå{if(pans[gby][gbx]==0){pans[gby][gbx]=1;ziShu++;}}int shuiYing()//0: 1:bai -1:heiË-Ó®À-{returnkanFangShuiYing(1,0)+kanFangShuiYing(0,1)+kanFangShuiYing(1,1)+kan FangShuiYing(1,-1);}//---------------------------------------------void xianShiQiPan(Graphics2D g2d)//ÏÔʾÆåÅÌ{g2d.setColor(Color.pink);g2d.fillRect(0,0,40*12,40*12);// 0,0,40*12,40*12g2d.setColor(Color.BLACK);//Ðиñfor(int i=0;i<11;i++)// 40,ÐÐ*40+40,440,ÐÐ*40+40{g2d.drawLine(40,i*40+40,440,i*40+40);}//Áиñfor(int k=0;k<11;k++)// ÁÐ*40+40,40,ÁÐ*40+40,440{g2d.drawLine(k*40+40,40,k*40+40,440);}}void xianShiQiZis(Graphics2D g2d)//ÏÔʾÆì×Ó{for(int h=0;h<11;h++){for(l=0;l<11;l++){switch(pans[h][l]){case 1:g2d.setColor(Color.BLACK);g2d.fillOval(40-15+l*40,40-15+h*40,30,30);//(40-15+l*40,40-15+h*40 ,30,30);break;case -1:g2d.setColor(Color.white);。

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();

简单JAVA五子棋代码

简单JAVA五子棋代码

简单JA V A五子棋代码只需要建两个类就可以了1.MainFrame类继承JFrame类2.MainPanel类继承JPanel类实现接口MouseListener两个类详细代码如下MainFrame类,如下:package game.gobang;import java.awt.BorderLayout;import java.awt.Color;import javax.swing.JFrame;/*** 五子棋* @WangJB* @version 19:46 13/03/17*/public class MainFrame extends JFrame{public static void main(String[] args) {M ainPanel panel = new MainPanel();MainFrame frame = new MainFrame("五子棋");frame.setSize(680,680);panel.setBackground(Color.GRAY);frame.add(panel,BorderLayout.CENTER);panel.addMouseListener(panel);frame.setVisible(true);}public MainFrame(){s uper();}public MainFrame(String str){s uper(str);}}MainPanel类如下:package game.gobang;import java.awt.Color;import java.awt.Graphics;import java.awt.Panel;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JOptionPane;/*** 五子棋的面板设计* @author WangJB* @version 00.59 13/3/16*/public class MainPanel extends Panel implements MouseListener{ private static final int COLUMN = 16;//列数private static final int ROW = 16;//行数private static final int GAP = 40;//间距private static boolean isBlack = true;private static int click_X;private static int click_Y;private char[][] allChess= new char[ROW][COLUMN];public MainPanel(){super();for(int i=0;i<allChess.length;i++){for(int j=0;j<allChess[i].length;j++){allChess[i][j]='*';}}}public void paint(Graphics g){f or(int i=0;i<ROW;i++){//划横线g.setColor(Color.BLACK);g.drawLine(20, 20+i*GAP, 640-20, 20+i*GAP);}f or(int i=0;i<COLUMN;i++){//划纵线g.setColor(Color.BLACK);g.drawLine(20+i*GAP, 20, 20+i*GAP, 640-20);}f or(int i=0;i<allChess.length;i++){for(int j=0;j<allChess[i].length;j++){if(allChess[i][j]=='~'){g.setColor(Color.WHITE);g.fillOval(5+i*40, 5+j*40, 30, 30);g.drawOval(5+i*40, 5+j*40, 30, 30);}if(allChess[i][j]=='!'){g.setColor(Color.BLACK);g.fillOval(5+i*40, 5+j*40, 30, 30);g.drawOval(5+i*40, 5+j*40, 30, 30);}}}}public boolean isWin(int x,int y,boolean isColor){//判断是否为5个相同的棋子,是返回true,否返回falsec har ch=allChess[x][y];/* 横向判断 */i nt RLastX = x;w hile(RLastX>=0 && allChess[RLastX][y]==ch){//横向判断是否到达5个相同的棋子RLastX --;}int RNum = 0;//统计横向相同的棋子数RLastX ++;w hile(RLastX<allChess.length && allChess[RLastX][y]==ch){//横向判断是否到达5个相同的棋子RNum ++;RLastX ++;}/* 纵向判断 */i nt LLastY = y;w hile(LLastY>=0 && allChess[x][LLastY]==ch){//纵向判断是否到达5个相同的棋子LLastY --;}i nt LNum = 0;//统计纵向相同的棋子数L LastY ++;w hile(LLastY<allChess[x].length && allChess[x][LLastY]==ch){//纵向判断是否到达5个相同的棋子LLastY ++;LNum ++;}/* 左下右上判断 */i nt LDLastX = x;i nt RULastY = y;w hile(LDLastX>=0 && RULastY<allChess.length &&allChess[LDLastX][RULastY]==ch){LDLastX --;RULastY ++;}i nt LDNum = 0;L DLastX ++;R ULastY --;w hile(LDLastX<allChess.length && RULastY>=0 &&allChess[LDLastX][RULastY]==ch){LDNum ++;LDLastX ++;RULastY --;}/* 左上右下判断 */i nt RULastX = x;i nt LDLastY = y;w hile(RULastX>=0 && LDLastY>=0 && allChess[RULastX][LDLastY]==ch){ RULastX --;LDLastY --;}i nt RUNum = 0;R ULastX ++;L DLastY ++;w hile(RULastX>=0 && LDLastY<allChess.length &&allChess[RULastX][LDLastY]==ch){RULastX ++;LDLastY ++;RUNum ++;}i f(RNum>=5||LNum>=5||RUNum>=5||LDNum>=5){return true;}r eturn false;}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub//System.out.println(e.getX());//e.getY();}public void mousePressed(MouseEvent e) {//鼠标点击事件处理过程// TODO Auto-generated method stubint click_x = e.getX();int click_y = e.getY();int chess_x = Math.round((float)(click_x-20)/GAP);int chess_y = Math.round((float)(click_y-20)/GAP);click_X = chess_x;click_Y = chess_y;if(isBlack==true&&allChess[chess_x][chess_y]=='*'){ allChess[chess_x][chess_y] = '!';isBlack = false;}if(isBlack==false&&allChess[chess_x][chess_y]=='*'){allChess[chess_x][chess_y] = '~';isBlack = true;}System.out.println(e.getX());System.out.println(e.getY());repaint();for(int j=0;j<16;j++){f or(int i=0;i<16;i++){System.out.print(allChess[i][j]+" ");}S ystem.out.println();}System.out.println();if(isWin(chess_x,chess_y,isBlack)){S ystem.out.println("你赢了");}if(isWin(chess_x,chess_y,isBlack)){i f(isBlack){JOptionPane.showMessageDialog(null,"白子赢了");}else{JOptionPane.showMessageDialog(null,"黑子赢了");}System.exit(0);}}@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}public void setAllChess(char[][] allChess) { this.allChess = allChess;}public char[][] getAllChess() {return allChess;}}运行结果图片:更多精彩代码请访问【安卓阅】。

Java实现五子棋游戏的完整代码

Java实现五子棋游戏的完整代码

Java实现五⼦棋游戏的完整代码⽤Java编写简单的五⼦棋,供⼤家参考,具体内容如下前⾔这两天在空闲时间做了个五⼦棋项⽬,分享给⼤家看⼀下,界⾯是这样的:界⾯很丑我知道,本⼈虽有⼏年PS基础,但知识浅薄,审美观不尽⼈意,做到如此实属极限(其实我懒得做了),⼤家将就着看看吧。

下⾯放出代码,为⽅便⼤家参考,我⼏乎每条代码都标有注释。

测试类代码public class Test {public static void main(String[] args) {MyJFrame mj=new MyJFrame();mj.myJFrame();}}MyJFrame类代码import javax.imageio.ImageIO;import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;public class MyJFrame extends JFrame implements MouseListener {int qx = 20, qy = 40, qw = 490, qh = 490;//棋盘位置、宽⾼int bw = 150, bh = 50, bx = 570, by = 150;//按钮宽⾼、位置int x = 0, y = 0;//保存棋⼦坐标int[][] SaveGame = new int[15][15];//保存每个棋⼦int qc = 1;//记录⽩棋=2,⿊棋=1int qn = 0;//判断棋⼦是否重复boolean canplay = true;//判断游戏是否开始和结束String go = "⿊⼦先⾏";//游戏信息//---------------------------------------------------------------------------------------------------------------------//窗体public void myJFrame() {this.setTitle("五⼦棋"); //标题this.setSize(800, 550); //窗⼝⼤⼩this.setResizable(false); //窗⼝是否可以改变⼤⼩=否this.setDefaultCloseOperation(MyJFrame.EXIT_ON_CLOSE);//窗⼝关闭⽅式为关闭窗⼝同时结束程序 int width = Toolkit.getDefaultToolkit().getScreenSize().width;//获取屏幕宽度int height = Toolkit.getDefaultToolkit().getScreenSize().height;//获取屏幕⾼度// System.out.println("宽度:"+width);//测试// System.out.println("⾼度:"+height);//测试this.setLocation((width - 800) / 2, (height - 600) / 2); //设置窗⼝默认位置以屏幕居中this.addMouseListener(this);this.setVisible(true); //窗⼝是否显⽰=是}//---------------------------------------------------------------------------------------------------------------------//覆写paint⽅法,绘制界⾯public void paint(Graphics g) {//双缓冲技术防⽌屏幕闪烁BufferedImage bi = new BufferedImage(800, 550, BufferedImage.TYPE_INT_ARGB);Graphics g2 = bi.createGraphics();//获取图⽚路径BufferedImage image = null;try {image = ImageIO.read(new File("D:/#Java/五⼦棋/tp/wzqbj.jpg"));} catch (IOException e) {e.printStackTrace();}g2.drawImage(image, 10, 10, this);//显⽰图⽚g2.setColor(Color.BLACK);//设置画笔颜⾊g2.setFont(new Font("华⽂⾏楷", 10, 50));//设置字体g2.drawString("晓时五⼦棋", 525, 100);//绘制字符//棋盘g2.setColor(Color.getHSBColor(30, (float) 0.10, (float) 0.90));//设置画笔颜⾊g2.fillRect(qx, qy, qw, qh);//绘制棋盘背景矩形//开始按钮g2.setColor(Color.WHITE);//设置画笔颜⾊g2.fillRect(bx, by, bw, bh);//绘制开始按钮g2.setFont(new Font("华⽂⾏楷", 10, 30));//设置字体g2.setColor(Color.black);//设置画笔颜⾊g2.drawString("开始", 615, 185);//绘制字符//悔棋按钮g2.setColor(Color.LIGHT_GRAY);//设置画笔颜⾊g2.fillRect(bx, by + 60, bw, bh);//绘制悔棋按钮g2.setFont(new Font("华⽂⾏楷", 10, 30));//设置字体g2.setColor(Color.WHITE);//设置画笔颜⾊g2.drawString("悔棋", 615, 245);//绘制字符//认输按钮g2.setColor(Color.GRAY);//设置画笔颜⾊g2.fillRect(bx, by + 120, bw, bh);//绘制认输按钮g2.setFont(new Font("华⽂⾏楷", 10, 30));//设置字体g2.setColor(Color.WHITE);//设置画笔颜⾊g2.drawString("认输", 615, 305);//绘制字符//游戏信息栏g2.setColor(Color.getHSBColor(30, (float) 0.10, (float) 0.90));//设置画笔颜⾊g2.fillRect(550, 350, 200, 150);//绘制游戏状态区域g2.setColor(Color.black);//设置画笔颜⾊g2.setFont(new Font("⿊体", 10, 20));//设置字体g2.drawString("游戏信息", 610, 380);//绘制字符g2.drawString(go, 610, 410);//绘制字符g2.drawString("作者:晓时⾕⾬", 560, 440);//绘制字符g2.drawString("联系⽅式:", 560, 465);//绘制字符g2.drawString("qq 717535996", 560, 490);//绘制字符g2.setColor(Color.BLACK);//设置画笔颜⾊//绘制棋盘格线for (int x = 0; x <= qw; x += 35) {g2.drawLine(qx, x + qy, qw + qx, x + qy);//绘制⼀条横线g2.drawLine(x + qx, qy, x + qx, qh + qy);//绘制⼀条竖线}//绘制标注点for (int i = 3; i <= 11; i += 4) {for (int y = 3; y <= 11; y += 4) {g2.fillOval(35 * i + qx - 3, 35 * y + qy - 3, 6, 6);//绘制实⼼圆}}//绘制棋⼦for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {if (SaveGame[i][j] == 1)//⿊⼦{int sx = i * 35 + qx;int sy = j * 35 + qy;g2.setColor(Color.BLACK);g2.fillOval(sx - 13, sy - 13, 26, 26);//绘制实⼼圆}if (SaveGame[i][j] == 2)//⽩⼦{int sx = i * 35 + qx;int sy = j * 35 + qy;g2.setColor(Color.WHITE);g2.fillOval(sx - 13, sy - 13, 26, 26);//绘制实⼼圆g2.setColor(Color.BLACK);g2.drawOval(sx - 13, sy - 13, 26, 26);//绘制空⼼圆}}}g.drawImage(bi, 0, 0, this);// g.drawRect(20, 20, 20, 20);//绘制空⼼矩形}//--------------------------------------------------------------------------------------------------------------------- //判断输赢private boolean WinLose() {boolean flag = false;//输赢int count = 1;//相连数int color = SaveGame[x][y];//记录棋⼦颜⾊//判断横向棋⼦是否相连int i = 1;//迭代数while (color == SaveGame[x + i][y]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x - i][y]) {count++;i++;}if (count >= 5) {flag = true;}//判断纵向棋⼦是否相连count = 1;i = 1;//迭代数while (color == SaveGame[x][y + i]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x][y - i]) {count++;i++;}if (count >= 5) {flag = true;}//判断斜向棋⼦是否相连(左上右下)count = 1;i = 1;//迭代数while (color == SaveGame[x - i][y - i]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x + i][y + i]) {count++;i++;}if (count >= 5) {flag = true;}//判断斜向棋⼦是否相连(左下右上)count = 1;i = 1;//迭代数while (color == SaveGame[x + i][y - i]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x - i][y + i]) {count++;i++;}if (count >= 5) {flag = true;}return flag;}//--------------------------------------------------------------------------------------------------------------------- //初始化游戏public void Initialize() {//遍历并初始化数组for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {SaveGame[i][j] = 0;}}//⿊⼦先⾏qc = 1;go = "轮到⿊⼦";}//--------------------------------------------------------------------------------------------------------------------- @Override//⿏标点击public void mouseClicked(MouseEvent e) {}@Override//⿏标按下public void mousePressed(MouseEvent e) {//获取⿏标点击位置x = e.getX();y = e.getY();//判断是否已开始游戏if (canplay == true) {//判断点击是否为棋盘内if (x > qx && x < qx + qw && y > qy && y < qy + qh) {//计算点击位置最近的点if ((x - qx) % 35 > 17) {x = (x - qx) / 35 + 1;} else {x = (x - qx) / 35;}if ((y - qy) % 35 > 17) {y = (y - qy) / 35 + 1;} else {y = (y - qy) / 35;}//判断当前位置有没有棋⼦if (SaveGame[x][y] == 0) {SaveGame[x][y] = qc;qn = 0;} else {qn = 1;}//切换棋⼦if (qn == 0) {if (qc == 1) {qc = 2;go = "轮到⽩⼦";} else {qc = 1;go = "轮到⿊⼦";}}this.repaint();//重新执⾏⼀次paint⽅法//弹出胜利对话框boolean wl = this.WinLose();if (wl) {JOptionPane.showMessageDialog(this, "游戏结束," + (SaveGame[x][y] == 1 ? "⿊⽅赢了" : "⽩⽅赢了"));//弹出提⽰对话框 canplay = false;}// System.out.println(1);//测试} else {// System.out.println(0);//测试}}//实现开始按钮//判断是否点击开始按钮if (e.getX() > bx && e.getX() < bx + bw && e.getY() > by && e.getY() < by + bh) {//判断游戏是否开始if (canplay == false) {//如果游戏结束,则开始游戏canplay = true;JOptionPane.showMessageDialog(this, "游戏开始");//初始化游戏Initialize();this.repaint();//重新执⾏⼀次paint⽅法} else {//如果游戏进⾏中,则重新开始JOptionPane.showMessageDialog(this, "重新开始");//初始化游戏Initialize();this.repaint();//重新执⾏⼀次paint⽅法}}//实现悔棋按钮//判断是否点击悔棋按钮if (e.getX() > bx && e.getX() < bx + bw && e.getY() > by + 60 && e.getY() < by + 60 + bh) {//判断游戏是否开始if (canplay == true) {//遍历棋盘上是否有棋⼦int z = 0;for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {if (SaveGame[i][j] != 0) {z++;}}}//判断是否有棋⼦if (z != 0) {JOptionPane.showMessageDialog(this, "下棋亦如⼈⽣,你⾛的每⼀步都没有回头路。

java五子棋程序

java五子棋程序

一个很经典的java 五子棋程序(源码)import java.awt.*;import java.awt.event.*;import java.applet.Applet;import java.awt.Color;publicclass enzit extends Applet implementsActionListener,MouseListener,MouseMotionListener,ItemListener { int color_Qizi=0;// 旗子的颜色标识0: 白子1: 黑子int intGame_Start=0;// 游戏开始标志0 未开始 1 游戏中int intGame_Body[][]=newint[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();}publicvoid itemStateChanged(ItemEvent e){if (ckbHB[0].getState()) // 选择黑子先还是白子先{color_Qizi=0;}else{color_Qizi=1;}}publicvoid actionPerformed(ActionEvent e){Graphics g=getGraphics();if (e.getSource()==b1){Game_start();}else{Game_re();}}publicvoid mousePressed(MouseEvent e){} publicvoid 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);}publicvoid mouseEntered(MouseEvent e){} publicvoid mouseExited(MouseEvent e){} publicvoid mouseReleased(MouseEvent e){} publicvoid mouseDragged(MouseEvent e){}public void mouseMoved(MouseEvent e){}publicvoid paint(Graphics g){ draw_qipan(g);}publicvoid set_Qizi(int x,int y) // 落子{if (intGame_Start==0) // 判断游戏未开始{return;}if (intGame_Body[x/20][y/20]!=0){return;}Graphics g=getGraphics();if (color_Qizi==1)// 判断黑子还是白子{g.setColor(Color.black);color_Qizi=0;}else{g.setColor(Color.white);color_Qizi=1;g.fillOval(x-10,y-10,20,20);intGame_Body[x/20][y/20]=color_Qizi+1;if (Game_win_1(x/20,y/20)) // 判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+" intGame_Start=0;}if (Game_win_2(x/20,y/20)) // 判断输赢{ lblWin.setText(Get_qizi_color(color_Qizi)+" intGame_Start=0;}if (Game_win_3(x/20,y/20)) // 判断输赢{ lblWin.setText(Get_qizi_color(color_Qizi)+" intGame_Start=0;}if (Game_win_4(x/20,y/20)) // 判断输赢{ lblWin.setText(Get_qizi_color(color_Qizi)+" intGame_Start=0;}}赢了!");赢了!");赢了!");赢了!");public String Get_qizi_color(int x) {if (x==0) return} else{return" 白子";}}publicvoid draw_qipan(Graphics G) // 画棋盘15*15{G.setColor(Color.lightGray); G.fill3DRect(10,10,300,300,true);G.setColor(Color.black);for(int i=1;i<16;i++){G.drawLine(20,20*i,300,20*i);G.drawLine(20*i,20,20*i,300);}}publicvoid Game_start() // 游戏开始{ intGame_Start=1;Game_btn_enable(false); b2.setEnabled(true);}publicvoid Game_start_csh() // 游戏开始初始化设置组件状判断{intGame_Start=0; Game_btn_enable(true); b2.setEnabled(false); ckbHB[0].setState(true);for (int i=0;i<16 ;i++ ){for (int j=0;j<16 ;j++ ){intGame_Body[j]=0;}}lblWin.setText("");}publicvoid Game_re() // 游戏重新开始{repaint();Game_start_csh();}publicvoid Game_btn_enable(boolean e) //{b1.setEnabled(e);b2.setEnabled(e);ckbHB[0].setEnabled(e);ckbHB[1].setEnabled(e);}publicboolean Game_win_1(int x,int y) //{int x1,y1,t=1; x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1]==intGame_Body[x][y]) { t+=1; }else{break;}}for (int i=1;i<5 ;i++ ){if (x1<1){break;} if(intGame_Body[x1-i][y1]==intGame_Body[x][y]){t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_2(int x,int y) // 判断输赢竖{int x1,y1,t=1;x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){if (intGame_Body[x1][y1+i]==intGame_Body[x][y]){t+=1;}else{break;} for (int i=1;i<5 ;i++ ) {if (x1<1){break;} if(intGame_Body[x1][y1-i]==intGame_Body[x][y]){t+=1;}else{break;}}return true;}else{return false;}}publicboolean Game_win_3(int x,int y) // 判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1-i]==intGame_Body[x][y]) {t+=1;}else{for (int i=1;i<5 ;i++ ) {if (x1<1){break;if(intGame_Body[x1-i][y1+i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){return true;}else{return false;}}publicboolean Game_win_4(int x,int y) // 判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1+i]==intGame_Body[x][y]){t+=1;}else{break;}}for (int i=1;i<5 ;i++ ) {if (x1<1){if(intGame_Body[x1-i][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}}。

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

下面的源代码分为4个文件;(1)chessClient.java:客户端主程序。

(2)chessInterface.java:客户端的界面。

(3)chessPad.java:棋盘的绘制。

(4)chessServer.java:服务器端。

可同时容纳50个人同时在线下棋,聊天。

/********************************************************************************************* 1.chessClient.java**********************************************************************************************/import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class clientThread extends Thread{chessClient chessclient;clientThread(chessClient chessclient){this.chessclient=chessclient;}public void acceptMessage(String recMessage){if(recMessage.startsWith("/userlist ")){StringTokenizer userToken=new StringTokenizer(recMessage," ");int userNumber=0;erList.removeAll();erChoice.removeAll();erChoice.addItem("所有人");while(userToken.hasMoreT okens()){String user=(String)userToken.nextToken(" ");if(userNumber>0 && !user.startsWith("[inchess]")){erList.add(user);erChoice.addItem(user);}userNumber++;}erChoice.select("所有人");}else if(recMessage.startsWith("/yourname ")){chessclient.chessClientName=recMessage.substring(10);chessclient.setTitle("Java五子棋客户端"+"用户名:"+chessclient.chessClientName);}else if(recMessage.equals("/reject")){try{chessclient.chesspad.statusText.setText("不能加入游戏");chessclient.controlpad.cancelGameButton.setEnabled(false);chessclient.controlpad.joinGameButton.setEnabled(true);chessclient.controlpad.creatGameButton.setEnabled(true);}catch(Exception ef){chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");}chessclient.controlpad.joinGameButton.setEnabled(true);}else if(recMessage.startsWith("/peer ")){chessclient.chesspad.chessPeerName=recMessage.substring(6);if(chessclient.isServer){chessclient.chesspad.chessColor=1;chessclient.chesspad.isMouseEnabled=true;chessclient.chesspad.statusText.setText("请黑棋下子");}else if(chessclient.isClient){chessclient.chesspad.chessColor=-1;chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");}}else if(recMessage.equals("/youwin")){chessclient.isOnChess=false;chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor); chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接"); chessclient.chesspad.isMouseEnabled=false;}else if(recMessage.equals("/OK")){chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");}else if(recMessage.equals("/error")){chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入\n"); }else{chessclient.chatpad.chatLineArea.append(recMessage+"\n");chessclient.chatpad.chatLineArea.setCaretPosition(chessclient.chatpad.chatLineArea.getT ext().length());}}public void run(){String message="";try{while(true){message=chessclient.in.readUTF();acceptMessage(message);}}catch(IOException es){}}}public class chessClient extends Frame implements ActionListener,KeyListener {userPad userpad=new userPad();chatPad chatpad=new chatPad();controlPad controlpad=new controlPad();chessPad chesspad=new chessPad();inputPad inputpad=new inputPad();Socket chatSocket;DataInputStream in;DataOutputStream out;String chessClientName=null;String host=null;int port=4331;boolean isOnChat=false; //在聊天?boolean isOnChess=false; //在下棋?boolean isGameConnected=false; //下棋的客户端连接?boolean isServer=false; //如果是下棋的主机boolean isClient=false; //如果是下棋的客户端Panel southPanel=new Panel();Panel northPanel=new Panel();Panel centerPanel=new Panel();Panel westPanel=new Panel();Panel eastPanel=new Panel();chessClient(){super("Java五子棋客户端");setLayout(new BorderLayout());host=controlpad.inputIP.getText();westPanel.setLayout(new BorderLayout());westPanel.add(userpad,BorderLayout.NORTH);westPanel.add(chatpad,BorderLayout.CENTER);westPanel.setBackground(Color.pink);inputpad.input word s.addKeyListener(this);chesspad.host=controlpad.inputIP.getText();centerPanel.add(chesspad,BorderLayout.CENTER); centerPanel.add(inputpad,BorderLayout.SOUTH); centerPanel.setBackground(Color.pink);controlpad.connectButton.addActionListener(this); controlpad.creatGameButton.addActionListener(this); controlpad.joinGameButton.addActionListener(this); controlpad.cancelGameButton.addActionListener(this); controlpad.exitGameButton.addActionListener(this);controlpad.creatGameButton.setEnabled(false); controlpad.joinGameButton.setEnabled(false); controlpad.cancelGameButton.setEnabled(false);southPanel.add(controlpad,BorderLayout.CENTER); southPanel.setBackground(Color.pink);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){if(isOnChat){try{chatSocket.close();}catch(Exception ed){}}if(isOnChess || isGameConnected){try{chesspad.chessSocket.close();}catch(Exception ee){}}System.exit(0);public void windowActivated(WindowEvent ea){}});add(westPanel,BorderLayout.WEST);add(centerPanel,BorderLayout.CENTER);add(southPanel,BorderLayout.SOUTH);pack();setSize(670,548);setVisible(true);setResizable(false);validate();}public boolean connectServer(String serverIP,int serverPort) throws Exception{try{chatSocket=new Socket(serverIP,serverPort);in=new DataInputStream(chatSocket.getInputStream());out=new DataOutputStream(chatSocket.getOutputStream());clientThread clientthread=new clientThread(this);clientthread.start();isOnChat=true;return true;}catch(IOException ex){chatpad.chatLineArea.setT ext("chessClient:connectServer:无法连接,建议重新启动程序\n");}return false;}public void actionPerformed(ActionEvent e){if(e.getSource()==controlpad.connectButton){host=chesspad.host=controlpad.inputIP.getText();try{if(connectServer(host,port)){chatpad.chatLineArea.setT ext("");controlpad.connectButton.setEnabled(false);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");}}catch(Exception ei){chatpad.chatLineArea.setT ext("controlpad.connectButton:无法连接,建议重新启动程序\n");}}if(e.getSource()==controlpad.exitGameButton){if(isOnChat){try{chatSocket.close();}catch(Exception ed){}}if(isOnChess || isGameConnected){try{chesspad.chessSocket.close();}catch(Exception ee){}}System.exit(0);}if(e.getSource()==controlpad.joinGameButton){String selectedUser=erList.getSelectedItem();if(selectedUser==null || selectedUser.startsWith("[inchess]") ||selectedUser.equals(chessClientName)){chesspad.statusText.setText("必须先选定一个有效用户");}else{try{if(!isGameConnected){if(chesspad.connectServer(chesspad.host,chesspad.port)){isGameConnected=true;isOnChess=true;isClient=true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+erList.getSelectedItem()+" "+chessClientName);}}else{isOnChess=true;isClient=true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/joingame "+erList.getSelectedItem()+" "+chessClientName);}}catch(Exception ee){isGameConnected=false;isOnChess=false;isClient=false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chatpad.chatLineArea.setT ext("chesspad.connectServer无法连接\n"+ee);}}}if(e.getSource()==controlpad.creatGameButton){try{if(!isGameConnected){if(chesspad.connectServer(chesspad.host,chesspad.port)){isGameConnected=true;isOnChess=true;isServer=true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); }}else{isOnChess=true;isServer=true;controlpad.creatGameButton.setEnabled(false);controlpad.joinGameButton.setEnabled(false);controlpad.cancelGameButton.setEnabled(true);chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName); }}catch(Exception ec){isGameConnected=false;isOnChess=false;isServer=false;controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);ec.printStackTrace();chatpad.chatLineArea.setT ext("chesspad.connectServer无法连接\n"+ec); }}if(e.getSource()==controlpad.cancelGameButton){if(isOnChess){chesspad.chessthread.sendMessage("/giveup "+chessClientName); chesspad.chessVictory(-1*chesspad.chessColor);controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}if(!isOnChess){controlpad.creatGameButton.setEnabled(true);controlpad.joinGameButton.setEnabled(true);controlpad.cancelGameButton.setEnabled(false);chesspad.statusText.setText("请建立游戏或者加入游戏");}isClient=isServer=false;}}public void keyPressed(KeyEvent e){TextField inputWords=(TextField)e.getSource();if(e.getKeyCode()==KeyEvent.VK_ENTER){if(erChoice.getSelectedItem().equals("所有人")){try{out.writeUTF(inputWords.getText());inputWords.setText("");}catch(Exception ea){chatpad.chatLineArea.setT ext("chessClient:KeyPressed无法连接,建议重新连接\n"); erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}}else{try{out.writeUTF("/"+erChoice.getSelectedItem()+" "+inputWords.getText()); inputWords.setText("");}catch(Exception ea){chatpad.chatLineArea.setT ext("chessClient:KeyPressed无法连接,建议重新连接\n"); erList.removeAll();erChoice.removeAll();inputWords.setText("");controlpad.connectButton.setEnabled(true);}}}}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}public static void main(String args[]){chessClient chessClient=new chessClient();}/******************************************************************************************下面是:chessInteface.java******************************************************************************************/import java.awt.*;import java.awt.event.*;import java.io.*;import .*;class userPad extends Panel{List userList=new List(10);userPad(){setLayout(new BorderLayout());for(int i=0;i<50;i++){userList.add(i+"."+"没有用户");}add(userList,BorderLayout.CENTER);}}class chatPad extends Panel{TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);chatPad(){setLayout(new BorderLayout());add(chatLineArea,BorderLayout.CENTER);}class controlPad extends Panel{Label IPlabel=new Label("IP",Label.LEFT); TextField inputIP=new TextField("localhost",10); Button connectButton=new Button("连接主机"); Button creatGameButton=new Button("建立游戏"); Button joinGameButton=new Button("加入游戏"); Button cancelGameButton=new Button("放弃游戏"); Button exitGameButton=new Button("关闭程序");controlPad(){setLayout(new FlowLayout(FlowLayout.LEFT)); setBackground(Color.pink);add(IPlabel);add(inputIP);add(connectButton);add(creatGameButton);add(joinGameButton);add(cancelGameButton);add(exitGameButton);}}class inputPad extends Panel{TextField inputWords=new TextField("",40);Choice userChoice=new Choice();inputPad(){setLayout(new FlowLayout(FlowLayout.LEFT));for(int i=0;i<50;i++){userChoice.addItem(i+"."+"没有用户");}userChoice.setSize(60,24);add(userChoice);add(inputWords);}}/********************************************************************************************** 下面是:chessPad.java**********************************************************************************************/ import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class chessThread extends Thread{chessPad chesspad;chessThread(chessPad chesspad){this.chesspad=chesspad;}public void sendMessage(String sndMessage){try{chesspad.outData.writeUTF(sndMessage);}catch(Exception ea){System.out.println("chessThread.sendMessage:"+ea);}}public void acceptMessage(String recMessage){if(recMessage.startsWith("/chess ")){StringTokenizer userToken=new StringTokenizer(recMessage," ");String chessToken;String[] chessOpt={"-1","-1","0"};int chessOptNum=0;while(userToken.hasMoreT okens()){chessToken=(String)userT oken.nextToken(" ");if(chessOptNum>=1 && chessOptNum<=3){chessOpt[chessOptNum-1]=chessToken;}chessOptNum++;}ChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Inte ger.parseInt(chessOpt[2]));}else if(recMessage.startsWith("/yourname ")){chesspad.chessSelfName=recMessage.substring(10);}else if(recMessage.equals("/error")){chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入");}else{//System.out.println(recMessage);}}public void run(){String message="";try{while(true){message=chesspad.inData.readUTF();acceptMessage(message);}}catch(IOException es){}}}class chessPad extends Panel implements MouseListener,ActionListener {int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;int chessBlack_x[]=new int[200];int chessBlack_y[]=new int[200];int chessWhite_x[]=new int[200];int chessWhite_y[]=new int[200];int chessBlackCount=0,chessWhiteCount=0;int chessBlackWin=0,chessWhiteWin=0;boolean isMouseEnabled=false,isWin=false,isInGame=false;TextField statusText=new TextField("请先连接服务器");Socket chessSocket;DataInputStream inData;DataOutputStream outData;String chessSelfName=null;String chessPeerName=null;String host=null;int port=4331;chessThread chessthread=new chessThread(this);chessPad(){setSize(440,440);setLayout(null);setBackground(Color.pink);addMouseListener(this);add(statusText);statusText.setBounds(40,5,360,24);statusText.setEditable(false);}public boolean connectServer(String ServerIP,int ServerPort) throws Exception{try{chessSocket=new Socket(ServerIP,ServerPort);inData=new DataInputStream(chessSocket.getInputStream());outData=new DataOutputStream(chessSocket.getOutputStream());chessthread.start();return true;}catch(IOException ex){statusText.setText("chessPad:connectServer:无法连接\n");}return false;}public void chessVictory(int chessColorWin){this.removeAll();for(int i=0;i<=chessBlackCount;i++){chessBlack_x[i]=0;chessBlack_y[i]=0;}for(int i=0;i<=chessWhiteCount;i++){chessWhite_x[i]=0;chessWhite_y[i]=0;}chessBlackCount=0;chessWhiteCount=0;add(statusText);statusText.setBounds(40,5,360,24);if(chessColorWin==1){ chessBlackWin++;statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子...");}else if(chessColorWin==-1){chessWhiteWin++;statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子...");}}public void getLocation(int a,int b,int color){if(color==1){chessBlack_x[chessBlackCount]=a*20;chessBlack_y[chessBlackCount]=b*20;chessBlackCount++;}else if(color==-1){chessWhite_x[chessWhiteCount]=a*20;chessWhite_y[chessWhiteCount]=b*20;chessWhiteCount++;}}public boolean checkWin(int a,int b,int checkColor){int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;if(checkColor==1){chessLink=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if(((a+step)*20==chessBlack_x[chessCompare]) && ((b*20)==chessBlack_y[chessCompare])){chessLink=chessLink+1;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if(((a-step)*20==chessBlack_x[chessCompare]) && (b*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}chessLink=1;chessLinkTest=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if((a*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}chessLink=1;chessLinkTest=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if(((a-step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if(((a+step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}chessLink=1;chessLinkTest=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if(((a+step)*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++){if(((a-step)*20==chessBlack_x[chessCompare]) && ((b-step)*20==chessBlack_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}}else if(checkColor==-1){chessLink=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if(((a+step)*20==chessWhite_x[chessCompare]) && (b*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if(((a-step)*20==chessWhite_x[chessCompare]) && (b*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}chessLink=1;chessLinkTest=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if((a*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if((a*20==chessWhite_x[chessCompare]) && ((b-step)*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}chessLink=1;chessLinkTest=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if(((a-step)*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if(((a+step)*20==chessWhite_x[chessCompare]) && ((b-step)*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}chessLink=1;chessLinkTest=1;for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if(((a+step)*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}for(step=1;step<=4;step++){for(chessCompare=0;chessCompare<=chessWhiteCount;chessCompare++){if(((a-step)*20==chessWhite_x[chessCompare]) && ((b-step)*20==chessWhite_y[chessCompare])){chessLink++;if(chessLink==5){return(true);}}}if(chessLink==(chessLinkTest+1))chessLinkTest++;elsebreak;}}return(false);}public void paint(Graphics g){for (int i=40;i<=380;i=i+20){g.drawLine(40,i,400,i);}g.drawLine(40,400,400,400);for(int j=40;j<=380;j=j+20){g.drawLine(j,40,j,400);}g.drawLine(400,40,400,400);g.fillOval(97,97,6,6);g.fillOval(337,97,6,6);g.fillOval(97,337,6,6);g.fillOval(337,337,6,6);g.fillOval(217,217,6,6);}public void chessPaint(int chessPoint_a,int chessPoint_b,int color){chessPoint_black chesspoint_black=new chessPoint_black(this);chessPoint_white chesspoint_white=new chessPoint_white(this);if(color==1 && isMouseEnabled){getLocation(chessPoint_a,chessPoint_b,color);isWin=checkWin(chessPoint_a,chessPoint_b,color);if(isWin==false){chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);this.add(chesspoint_black);chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); statusText.setText("黑(第"+chessBlackCount+"步)"+chessPoint_a+" "+chessPoint_b+",请白棋下子");isMouseEnabled=false;}else{chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);this.add(chesspoint_black);chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); chessVictory(1);isMouseEnabled=false;}}else if(color==-1 && isMouseEnabled){getLocation(chessPoint_a,chessPoint_b,color);isWin=checkWin(chessPoint_a,chessPoint_b,color);if(isWin==false){chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);this.add(chesspoint_white);chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); statusText.setText("白(第"+chessWhiteCount+"步)"+chessPoint_a+" "+chessPoint_b+",请黑棋下子");isMouseEnabled=false;}else{chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);this.add(chesspoint_white);chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); chessVictory(-1);isMouseEnabled=false;}}}public void netChessPaint(int chessPoint_a,int chessPoint_b,int color){chessPoint_black chesspoint_black=new chessPoint_black(this);chessPoint_white chesspoint_white=new chessPoint_white(this);getLocation(chessPoint_a,chessPoint_b,color);if(color==1){isWin=checkWin(chessPoint_a,chessPoint_b,color);if(isWin==false){this.add(chesspoint_black);chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); statusText.setText("黑(第"+chessBlackCount+"步)"+chessPoint_a+" "+chessPoint_b+",请白棋下子");isMouseEnabled=true;}else{this.add(chesspoint_black);chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); chessVictory(1);isMouseEnabled=true;}}else if(color==-1){isWin=checkWin(chessPoint_a,chessPoint_b,color);if(isWin==false){this.add(chesspoint_white);chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); statusText.setText("白(第"+chessWhiteCount+"步)"+chessPoint_a+" "+chessPoint_b+",请黑棋下子");isMouseEnabled=true;}else{chessthread.sendMessage("/"+chessPeerName+" /victory "+color);this.add(chesspoint_white);chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16); chessVictory(-1);isMouseEnabled=true;}}}public void mousePressed(MouseEvent e)if (e.getModifiers()==InputEvent.BUTTON1_MASK){chessPoint_x=(int)e.getX();chessPoint_y=(int)e.getY();int a=(chessPoint_x+10)/20,b=(chessPoint_y+10)/20;if(chessPoint_x/20<2||chessPoint_y/20<2||chessPoint_x/20>19||chessPoint_y/20>19) {}else{chessPaint(a,b,chessColor);}}}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseClicked(MouseEvent e) {}public void actionPerformed(ActionEvent e){}}class chessPoint_black extends Canvas implements MouseListener{chessPad chesspad=null;chessPoint_black(chessPad p){setSize(20,20);chesspad=p;addMouseListener(this);}public void paint(Graphics g){g.setColor(Color.black);g.fillOval(0,0,14,14);}public void mousePressed(MouseEvent e)。

相关文档
最新文档