您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么用java實現簡單網絡象棋游戲”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
本文實例為大家分享了java實現網絡象棋游戲的具體代碼,供大家參考,具體內容如下
游戲規則:
1.將/帥:不能出田字格,不能走斜線,只能前進后退向左向右,每次只走一格;
2.士/仕:不能出田字格,只能走斜線,每次只走一格;
3.象/相:只能走田字格,中間防止蹩腳,不能有棋;
4.馬:只能走日,(這個比較麻煩,且看下圖標識)
5.車:車只能走直線,這個很好理解,不細說了;
6.炮:
情況一:純走路—->中間和目的地都不能有棋 情況二:吃棋—–>中間要有一顆棋,目標也有棋,且是敵方的棋,畢竟不能自己吃自己哈
7.卒/兵:
河這邊:只能前進不能后退,不能橫著走!!! 河對面:可以前進,可以橫著走,不能后退!!!
面板設計
看上去一定很挫!哈哈,別急,聽我細細道來! 一般的界面設計我們都知道橫縱坐標是這樣的:
但是我選擇背道而行,不是因為別的,是為了更好的去讓初學者理解,我們把原本的x坐標看成數組的列(col),把y坐標看成我們數組的行(row),這樣是不是更好理解一點呢,當然了我就是這么理解的,哈哈,接下來的游戲代碼編程我們會把橫坐標用y*width,縱坐標用x*height你們應該就能理解為什么了,因為x是數組的行,也就是坐標縱坐標(y)的體現,同理數組中的y也是如此。
數據傳輸:這里我們采用UDP協議來進行通訊,所以你們也要先去了解一下UDP協議的一些基本方法,這里就不細講了。
通訊協議:這里我們自定義通訊協議啊: “play|”——–以此開頭代表一端發出了游戲邀請,等待另一端的回應; “connect|”——-以此開頭代表另一端收到邀請并且同意建立連接通訊!如果邀請者受到這條消息就代表通訊建立成功,可以開始游戲了; “move|”——以此開頭代表移動數據傳輸,如果一端移動了棋子,那么另一端也要收到信息,重新繪制界面; “lose|”——–以此開頭代表一方認輸,如果有一方認輸就會向另一方發送該信息; “quit|”——-以此開頭代表一方退出游戲,任意一方離開都會向對方發送該信息,以提示對方; “success|”—–以此開頭代表勝利,某一方勝利就向對方發出信息,通知對方; “regret|”——以此開頭表示悔棋,這個不用講了吧,大家都明白,但是本次編程中我沒有把這個加進去,這個你們可以自己根據自己需要去添加。 (肯定有人問我這個協議是誰定義的,啊哈哈,讓你們失望了,這是我自己定義的,這個通訊協議只適用于你們寫的這個代碼,和使用這個代碼的兩個人通訊使用,所以協議如何自己可以定義的哦)
代碼實現
1.Chess類:
package internet_chess;import java.awt.Graphics;import java.awt.Image;import java.awt.Point;import java.awt.Toolkit;import java.awt.image.ImageObserver;import javax.swing.JPanel;public class Chess { public int Row = 12; public int Col = 11; public String chessName;//當前棋子對象的名字 public int owner;//當前棋子對象的所有者--黑方還是紅方 public Point point;//當前棋子對象的位置 public Image chessImage;//當前棋子對象的圖像 private int BLACKCHESS = 1; private int REDCHESS = 0;//紅方0,黑方1 private int width = 40; private int height = 40; public Chess(String name, int own,Point point)//獲取每一個棋子對象名字,所有者,位置,和圖片信息 { this.chessName = name; this.owner = own; this.point = point; if(owner == BLACKCHESS)//如果所有者是黑方 { if(chessName.equals("將")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/0.png"); } else if(chessName.equals("士")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/1.png"); } else if(chessName.equals("象")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/3.png"); } else if(chessName.equals("馬")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/5.png"); } else if(chessName.equals("車")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/7.png"); } else if(chessName.equals("炮")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/9.png"); } else if(chessName.equals("卒")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/11.png"); } } else//如果所有者是紅方 { if(chessName.equals("帥")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/16.png"); } else if(chessName.equals("仕")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/17.png"); } else if(chessName.equals("相")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/19.png"); } else if(chessName.equals("馬")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/21.png"); } else if(chessName.equals("車")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/23.png"); } else if(chessName.equals("炮")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/25.png"); } else if(chessName.equals("兵")) { chessImage = Toolkit.getDefaultToolkit().getImage("F:/Image/chess/27.png"); } } } protected void paint(Graphics g,JPanel i)//畫棋子 { g.drawImage(chessImage, point.y*width-width/2, point.x*height-height/2, width, height, (ImageObserver)i); } protected void paintSeclected(Graphics g)//畫鼠標選擇了以后的棋子對象的邊框 { g.drawRect(point.y*width-width/2, point.x*height-height/2, width, height); } public void SetPos(int x, int y)//重新設置移動以后的棋子對象的位置坐標 { point.x = x; point.y = y; } public void ReversePos()//將該對象的位置坐標逆置輸出,用于方便顯示信息情況 { point.x = Row-1 - point.x; point.y = Col-1 - point.y; }}
2.ChessPanel類:
package internet_chess;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Point;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException;import javax.swing.JOptionPane;import javax.swing.JPanel;public class ChessPanel extends JPanel implements Runnable{ private int BLACKCHESS = 1; private int REDCHESS = 0;//黑棋是1,紅旗是0 public Chess chess[] = new Chess[32];//創建了32個棋子對象 private int width = 40; private int height = 40; public int Row = 12; public int Col = 11;//11行10列 public int map[][] = new int [Row][Col]; public int player;//設置當前玩家對象 private boolean isFirst = false;//判斷是否是第一次點擊的棋子,以此分開兩次點擊棋子的碰撞矛盾 private int x1,y1,x2,y2;//用來保存第一次第二次選中的坐標的 private boolean flag = true;//用來控制線程的運行 private boolean isPlay = false; private Chess firstChess = null; private Chess secondChess = null;//設置第一次點擊的棋子和第二次選中的棋子對象 private InetAddress myID;//自己id地址 private InetAddress youID;//目標ID地址 private int sendport;//發送端口 private int receiveport = 8888;//接收端口 public ChessPanel()//構造函數 { init_map();//初始化棋盤 //給這個面板添加鼠標監聽機制 this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if(isPlay == true)//判斷是否該本方下棋 { SelectChess(e.getPoint());//選擇要移動的棋子 repaint(); } } public void SelectChess(Point pos) { int x = pos.x; int y = pos.y;//獲取此時此刻鼠標點擊的位置坐標 System.out.println("選擇要移動的棋子坐標:x->"+x+" y->"+y); if(x > 0 && x < (Col-1)*width && y > 0 && y < (Row-1)*height)//判斷鼠標是否在合理的范圍,不在就直接退出 { Point point = ReSetID(x,y); if(isFirst)//判斷是否是第一次選中的棋子 { x1 = point.x; y1 = point.y; //判斷第一次選中的棋子是不是自己的棋子或者是不是無效棋子,不是就失敗 int id = map[x1][y1]; if(id != -1 && chess[id].owner == player) { isFirst = false; firstChess = chess[id]; System.out.println("id->"+id); } else//第一次選擇的棋子無效 { JOptionPane.showConfirmDialog(null, "提示", "第一次選棋無效!請重新選擇!", JOptionPane.OK_OPTION); isFirst = true; } } else//第二次選中的棋子 { x2 = point.x; y2 = point.y; int id = map[x2][y2]; if(id != -1 && chess[id].owner != player)//第二次選擇了敵方棋子,將敵方棋子保存起來 { isFirst = true; secondChess = chess[id]; //開始判斷是否可以移動棋子,如果可以就將棋子移動,并發信息給對方我們已經移動的棋子信息 //判斷是否可以移動棋子 if(IsMoveChess(firstChess,x2,y2))//可以移動-吃棋 { int idx1 = map[x1][y1]; map[x1][y1] = -1; map[x2][y2] = idx1; chess[id] = null; firstChess.SetPos(x2, y2); repaint(); send("move|"+String.valueOf(idx1)+"|"+String.valueOf(Row-1-x2)+"|"+String.valueOf(Col-1-y2)+"|",youID,sendport); if(id == 0)//吃掉了黑棋將軍 { send("success|紅棋贏",youID,sendport); isPlay = false; JOptionPane.showConfirmDialog(null, "紅棋勝利", "恭喜您,您贏了!", JOptionPane.OK_OPTION); return; } else if(id == 16)//吃掉了紅棋大帥 { send("success|黑棋贏",youID,sendport); isPlay = false; JOptionPane.showConfirmDialog(null, "黑棋勝利", "恭喜您,您贏了!", JOptionPane.OK_OPTION); return; } isFirst = true; isPlay = false; } else//表示不能吃棋,重新下棋 { JOptionPane.showConfirmDialog(null, "提示", "對不起,移動棋子失敗,請重新選擇目標!", JOptionPane.ERROR_MESSAGE); isFirst = false; } } else if(id != -1 && chess[id].owner == player)//第二次又選擇了自己的棋子,那么就將第二次選擇的棋子當做第一次選擇的棋子 { firstChess = chess[id]; x1 = x2; y1 = y2; isFirst = false; } else//第二次選擇的棋子是空,那么就是單純的移動棋子 { secondChess = null; if(IsMoveChess(firstChess,x2,y2))//可以移動-吃棋 { int idx1 = map[x1][y1]; map[x1][y1] = -1; map[x2][y2] = idx1;// chess[id] = null; firstChess.SetPos(x2, y2); send("move|"+String.valueOf(idx1)+"|"+String.valueOf(Row-1-x2)+"|"+String.valueOf(Col-1-y2)+"|",youID,sendport); System.out.println("第二次選中棋子為空:目標-》"+(Row-1-x2)+" "+(Col-1-y2)); repaint(); isFirst = true; isPlay = false; } } } } } }); } public boolean IsMoveChess(Chess chess,int x,int y)//判斷是否可以移動棋子----移動棋子的規則 { if(chess.chessName.equals("將") || chess.chessName.equals("帥"))//只能走一步 { int x0 = chess.point.x; int y0 = chess.point.y; if(x >= 8 && x <= 10 && y >= 4 && y <= 6) {// int x0 = chess.point.x;// int y0 = chess.point.y; if(Math.abs(x - x0) > 1 || Math.abs(y - y0) > 1) return false; else if(Math.abs(x - x0)*Math.abs(y - y0) != 0)//不能走斜線 return false; else return true; } if(this.chess[map[x][y]].chessName.equals("將") || this.chess[map[x][y]].chessName.equals("帥") && (y0 == y))//判斷兩個將領之間吃棋 { int min = x < x0? x : x0; int max = x > x0? x : x0; for(min = min+1; min < max; min++) { if(map[min][y] != -1) return false; } return true; } else return false; } else if(chess.chessName.equals("士") || chess.chessName.equals("仕"))//士也不能出田字格,且,士走斜線,每次只走一格 { if(x >= 8 && x <= 10 && y >= 4 && y <= 6) { int x0 = chess.point.x; int y0 = chess.point.y; if(Math.abs(x - x0) * Math.abs(y - y0) != 1) { return false; } else return true; } else//越界 return false; } else if(chess.chessName.equals("象") || chess.chessName.equals("相"))//相走田字,且不能過河 { if(x >= 6 && x != 11 && y >= 1 && y <= 9) { int x0 = chess.point.x; int y0 = chess.point.y; if(Math.abs(x - x0) * Math.abs(y - y0) != 4) { return false; } else if(Math.abs(x - x0) == 2 && Math.abs(y - y0) == 2) { int xm,ym;//求取中間值,防止中間有值不能走棋 xm = x > x0? x-1:x0-1; ym = y > y0? y-1:y0-1; if(map[xm][ym] != -1)//表示中間有棋 return false; return true; } else//防止1*4 == 4的情況出現 return false; } else return false; } else if(chess.chessName.equals("馬"))//馬走日,防止蹩腳的情況出現 { if(x >= 1 && x <=10 && y >= 1 && y <= 9) { int x0 = chess.point.x; int y0 = chess.point.y; if(Math.abs(x - x0) * Math.abs(y - y0) == 2)//判斷是否走日 { //判斷是否蹩腳 if(Math.abs(y - y0) == 2) { if(map[x0][y+1] != -1 && y < y0)//左邊 { return false; } if(map[x0][y-1] != -1 && y0 < y)//右邊 { return false; } return true; } else { if(map[x+1][y0] != -1 && x < x0)//上邊 { return false; } if(map[x-1][y0] != -1 && x > x0)//下邊 { return false; } return true; } } else return false; } else return false; } else if(chess.chessName.equals("車"))//車走直線 { if(x >= 1 && x <=10 && y >= 1 && y <= 9) { int x0 = chess.point.x; int y0 = chess.point.y; if(x == x0)//水平移動 { int i = y < y0 ? y : y0; int max = y > y0 ? y : y0; for(i = i+1; i < max; i++)//不判斷目標狀態,目標狀態能否走在外面判斷 { if(map[x][i] != -1) {// if(i == max && this.chess[map[x][i]].owner != chess.owner)// {// return true;// } return false; } } return true; } else if(y == y0)//垂直移動 { int i = x < x0 ? x : x0; int max = x > x0 ? x : x0; for(i = i+1; i < max; i++) { if(map[i][y] != -1) {// if(i == max && this.chess[map[i][y]].owner != chess.owner)// {// return true;// } return false; } } return true; } return false; } else return false;//越界 } else if(chess.chessName.equals("炮"))//跑隔山打牛,不隔山就走路,水平或者垂直移動 { if(x >= 1 && x <=10 && y >= 1 && y <= 9) { int x0 = chess.point.x; int y0 = chess.point.y; int countx = 0; int county = 0; if(x == x0)//水平移動 { int i = y < y0 ? y : y0; int max = y > y0 ? y : y0; for(i = i+1; i < max; i++) { if(map[x][i] != -1) { countx++; } } } else if(y == y0)//垂直移動 { int i = x < x0 ? x : x0; int max = x > x0 ? x : x0; for(i = i+1; i < max; i++) { if(map[i][y] != -1) { county++; } } } if(countx == 1 || county == 1)//說明中間有一個棋 {// if(this.chess[map[x][y]].owner != chess.owner)// {// return true;// }// else// return false; System.out.println("countx:"+countx); System.out.println("county:"+county); return true; } else if(countx == 0 && county == 0)//說明中間沒有棋 { if(map[x][y] == -1)//目標沒有棋 { return true; } else return false;// return true; } else return false; } else return false;//越界 } else if(chess.chessName.equals("兵") || chess.chessName.equals("卒"))//卒子在自己區域不能退,只能前進,每次只走一步 { if(x < 7 && x >= 1 && y >= 1 && y <= 9) { int x0 = chess.point.x; int y0 = chess.point.y; if(x == x0 && Math.abs(y-y0) == 1)//橫向只走一步,判斷是否在河的這邊還是那邊 { //如果是河的這邊就不能走橫向 if(x == 6) return false; else return true; } if(y == y0 && x - x0 == -1)//縱向只走一步,且必須向前走 { return true; } return false; } else return false; } return false; } public Point ReSetID(int x, int y)//重置id,將id轉化成可辨識的坐標信息 { int posx = (y+height/2)/height; int posy = (x+width/2)/width; return new Point(posx,posy); } public void init_map()//初始化棋盤 { for(int i = 0; i < Row; i++) { for(int j = 0; j < Col; j++) { map[i][j] = -1;//將棋盤初始化為-1,表示沒有棋子id } } } public void paint(Graphics g)//自己畫棋盤 { super.paint(g); g.clearRect(0,0,this.getWidth(),this.getHeight()); //畫棋盤 int a = 1; int b = 8; int c = 5;//兩軍中間的分界線 for(int j = 1; j < Row-1; j++)//畫橫線 { g.drawLine(a*width, j*height, (Col-2)*width, j*height); } for(int i = 1; i < Col-1; i++)//畫豎線 { g.drawLine(i*width, a*height, i*width, (Row-2)*height); if(i == 4) { g.drawLine(i*width, a*height, (i+2)*width, (a+2)*height); g.drawLine(i*width, b*height, (i+2)*width, (b+2)*height); } if(i == 6) { g.drawLine(i*width, a*height, (i-2)*width, (a+2)*height); g.drawLine(i*width, b*height, (i-2)*width, (b+2)*height); } } g.drawRect(0, 0, (Col-1)*width, (Row-1)*height); g.setColor(Color.GRAY); g.fillRect(a*width, c*height,(Col-2-a)*width, height); g.setFont(new Font("黑體",Font.BOLD,20)); g.setColor(Color.white); g.drawString("楚 河 漢 界", 3*width, (c+1)*height-10); g.setColor(Color.black); //畫棋子 for(int i = 0; i < chess.length; i++) { if(chess[i] != null) { chess[i].paint(g, this); } } if(firstChess != null) { firstChess.paintSeclected(g); } if(secondChess != null) { secondChess.paintSeclected(g); } } public void send(String str,InetAddress ip,int port) //發送數據報 { DatagramSocket s = null; try{ s = new DatagramSocket();//創建一個數據報套接字 byte data[] = new byte[100]; data = str.getBytes(); DatagramPacket pocket = new DatagramPacket(data,data.length,ip,port);//將數據報的信息放入自尋址包中,自尋址信息包括數據,數據長度,目標ip地址,目標端口號 s.send(pocket);//發送自尋址包 System.out.println("發送信息:"+str); }catch(IOException ex) { ex.printStackTrace(); }finally { if(s != null) s.close(); } } public void startgame(InetAddress ip, int otherport, int myport)//游戲正式開始的起點入口 { youID = ip; this.sendport = otherport; this.receiveport = myport; try{ myID = InetAddress.getLocalHost(); }catch(UnknownHostException ex) { ex.printStackTrace(); } send("play|",youID,sendport);//發送邀請,等待目標ip的回應----開啟一個線程,不斷監聽端口,檢查是否有消息,是否建立連接成功 Thread t = new Thread(this); t.start(); } public void FirstPaintChess()//第一次畫棋盤---將每個棋盤上的棋子對象擺放完好,設置各自的初始屬性 { //原本把黑棋放上面,紅棋放下面,但是為了顯示效果,凡是玩家玩,都把玩家的花色放下面 init_map();//如果再玩一局就要先清空棋盤,然后再重置棋子,否則上一局某些位置上面的id會遺留下來 paintChess(); if(player == BLACKCHESS) { ReverseChess(); } repaint(); } public void ReverseChess()//轉置,將坐標改變,以便于下棋者下棋 { //先改變坐標// for(int i = 0; i < 32; i++)// {// if(chess[i] != null)// chess[i].ReversePos();// } //改變map地圖id for(int i = 0; i < 32; i++) { if(chess[i] != null) { chess[i].ReversePos(); int xx = chess[i].point.x; int yy = chess[i].point.y; map[xx][yy] = i; } } } public void paintChess()//畫棋盤顯示,上面黑棋,下面紅棋 { //黑方 chess[0] = new Chess("將",BLACKCHESS,new Point(1,5)); map[1][5] = 0; chess[1] = new Chess("士",BLACKCHESS,new Point(1,4)); map[1][4] = 1; chess[2] = new Chess("士",BLACKCHESS,new Point(1,6)); map[1][6] = 2; chess[3] = new Chess("象",BLACKCHESS,new Point(1,3)); map[1][3] = 3; chess[4] = new Chess("象",BLACKCHESS,new Point(1,7)); map[1][7] = 4; chess[5] = new Chess("馬",BLACKCHESS,new Point(1,2)); map[1][2] = 5; chess[6] = new Chess("馬",BLACKCHESS,new Point(1,8)); map[1][8] = 6; chess[7] = new Chess("車",BLACKCHESS,new Point(1,1)); map[1][1] = 7; chess[8] = new Chess("車",BLACKCHESS,new Point(1,9)); map[1][9] = 8; chess[9] = new Chess("炮",BLACKCHESS,new Point(3,2)); map[3][2] = 9; chess[10] = new Chess("炮",BLACKCHESS,new Point(3,8)); map[3][8] = 10; for(int i = 11,j = 1; i < 16; i++,j+=2) { chess[i] = new Chess("卒",BLACKCHESS,new Point(4,j)); map[4][j] = i; } //畫紅棋 chess[16] = new Chess("帥",REDCHESS,new Point(10,5)); map[10][5] = 16; chess[17] = new Chess("仕",REDCHESS,new Point(10,4)); map[10][4] = 17; chess[18] = new Chess("仕",REDCHESS,new Point(10,6)); map[10][6] = 18; chess[19] = new Chess("相",REDCHESS,new Point(10,3)); map[10][3] = 19; chess[20] = new Chess("相",REDCHESS,new Point(10,7)); map[10][7] = 20; chess[21] = new Chess("馬",REDCHESS,new Point(10,2)); map[10][2] = 21; chess[22] = new Chess("馬",REDCHESS,new Point(10,8)); map[10][8] = 22; chess[23] = new Chess("車",REDCHESS,new Point(10,1)); map[10][1] = 23; chess[24] = new Chess("車",REDCHESS,new Point(10,9)); map[10][9] = 24; chess[25] = new Chess("炮",REDCHESS,new Point(8,2)); map[8][2] = 25; chess[26] = new Chess("炮",REDCHESS,new Point(8,8)); map[8][8] = 26; for(int i = 27, j = 1; i < 32; i++, j+=2) { chess[i] = new Chess("兵",REDCHESS,new Point(7,j)); map[7][j] = i; } } @Override public void run() { DatagramSocket sock = null; try { sock = new DatagramSocket(receiveport);//打開監聽窗口 byte data[] = new byte[100]; DatagramPacket pocket = new DatagramPacket(data,data.length); while(flag) { sock.receive(pocket);//接收數據 //讀取接收信息 String str = new String(data); String s[] = new String[6]; s = str.split("\\|");//將數據信息按照|進行分割 if(s[0].equals("play"))//表示此時這個對象是一個被邀請的對象,將被邀請的對象設置為黑棋 { player = BLACKCHESS;//被邀請者設為黑棋 send("connect|",youID,sendport); //開始畫棋盤 FirstPaintChess(); isPlay = false;//因為是紅棋先走,所以黑棋此時不能下棋 } else if(s[0].equals("connect"))//表示此時的對象是游戲發出者對象,并且已經和被邀請對象建立連接 { player = REDCHESS;//游戲發出者設為紅棋對象 FirstPaintChess(); isPlay = true;//因為此時是紅棋,而紅旗先走,所以紅棋此時可以下棋 } else if(s[0].equals("lose"))//對方認輸 { JOptionPane.showConfirmDialog(null, "認輸", "對方棋手認輸!", JOptionPane.OK_OPTION); isPlay = false; } else if(s[0].equals("success"))//對方贏了 { if(s[1].equals("黑棋贏")) { JOptionPane.showConfirmDialog(null, "輸了", "黑棋贏了!您輸了!", JOptionPane.OK_OPTION); } else if(s[1].equals("紅棋贏")) { JOptionPane.showConfirmDialog(null, "輸了", "紅棋贏了!您輸了!", JOptionPane.OK_OPTION); } isPlay = false; } else if(s[0].equals("move"))//對方走棋 { int indx = Integer.parseInt(s[1]); System.out.println("indx->"+indx); int posx = Integer.parseInt(s[2]); System.out.println("posx->"+posx); int posy = Integer.parseInt(s[3]); System.out.println("posy->"+posy); int x = chess[indx].point.x; int y = chess[indx].point.y; map[x][y] = -1; chess[indx].point.x = posx; chess[indx].point.y = posy; if(map[posx][posy] != -1) { chess[map[posx][posy]] = null; } map[posx][posy] = indx; repaint(); isPlay = true; } else if(s[0].equals("quit"))//對方退出 { JOptionPane.showConfirmDialog(null, "提示", "對方離開,游戲結束!", JOptionPane.OK_OPTION); isPlay = false; flag = false;//退出線程 } } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(sock != null) { sock.close(); } } }}
3.ChessFrame類:
package internet_chess;import java.awt.BorderLayout;import java.awt.Container;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Rectangle;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.net.InetAddress;import java.net.UnknownHostException;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;public class ChessFrame extends JFrame{ private JButton start = new JButton("開始"); private JButton end = new JButton("結束"); private JButton lose = new JButton("認輸"); private JPanel paneUp = new JPanel(); private ChessPanel chesspanel = new ChessPanel(); private JPanel paneDown = new JPanel(); private JLabel IPlabel = new JLabel("IP:"); private JLabel otherPortlabel = new JLabel("目標端口"); private JLabel imageicon = new JLabel(); private JTextField ip_address = new JTextField("127.0.0.1"); private JTextField otherPort = new JTextField("9999"); private InetAddress myID;//自己id地址 private InetAddress youID;//目標ID地址 private int sendport;//發送端口 private int receiveport = 8888;//接收端口 public ChessFrame()//構造函數 { paneDown.setLayout(new FlowLayout()); IPlabel.setBounds(10, 10, 40, 20); ip_address.setBounds(new Rectangle(60,10,50,20)); paneDown.add(IPlabel); paneDown.add(ip_address); paneDown.add(otherPortlabel); paneDown.add(otherPort); paneDown.add(start); paneDown.add(lose); paneDown.add(end); lose.setEnabled(false); imageicon.setBounds(new Rectangle(300,0,100,100)); imageicon.setIcon(new ImageIcon("F:/Image/chess/0.png"));//標簽加載圖片 paneUp.add(imageicon,BorderLayout.CENTER); Container con = this.getContentPane(); con.add(paneUp,BorderLayout.NORTH); con.add(chesspanel,BorderLayout.CENTER); con.add(paneDown,BorderLayout.SOUTH); this.setTitle("8888網絡象棋"); this.setSize(new Dimension(600,700)); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); start.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try { String ip = ip_address.getText();//獲取當前目標ip地址 sendport = Integer.parseInt(otherPort.getText());//獲取目標連接端口 myID = InetAddress.getLocalHost();//獲取本地ip地址 youID = InetAddress.getByName(ip);//獲取目標ip地址 } catch (UnknownHostException e1) { e1.printStackTrace(); } chesspanel.startgame(youID,sendport,receiveport); lose.setEnabled(true); } }); end.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try{ chesspanel.send("quit|",youID,sendport);//向對方發送離開信息,同時斷開連接 System.exit(0); }catch(Exception ex) { ex.printStackTrace(); } } }); lose.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try{ chesspanel.send("lose|",youID,sendport);//向對方發送認輸信息 }catch(Exception ex) { ex.printStackTrace(); } } }); //加一個對方求和的按鈕 } public static void main(String[] args) { // TODO Auto-generated method stub new ChessFrame(); }}
“怎么用java實現簡單網絡象棋游戲”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。