本篇內(nèi)容介紹了“怎么用java實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)象棋游戲”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
十余年的牟定網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開(kāi)發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。全網(wǎng)整合營(yíng)銷推廣的優(yōu)勢(shì)是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整牟定建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無(wú)論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。成都創(chuàng)新互聯(lián)公司從事“牟定網(wǎng)站設(shè)計(jì)”,“牟定網(wǎng)站推廣”以來(lái),每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。本文實(shí)例為大家分享了java實(shí)現(xiàn)網(wǎng)絡(luò)象棋游戲的具體代碼,供大家參考,具體內(nèi)容如下
游戲規(guī)則:
1.將/帥:不能出田字格,不能走斜線,只能前進(jìn)后退向左向右,每次只走一格;
2.士/仕:不能出田字格,只能走斜線,每次只走一格;
3.象/相:只能走田字格,中間防止蹩腳,不能有棋;
4.馬:只能走日,(這個(gè)比較麻煩,且看下圖標(biāo)識(shí))
5.車:車只能走直線,這個(gè)很好理解,不細(xì)說(shuō)了;
6.炮:
情況一:純走路—->中間和目的地都不能有棋 情況二:吃棋—–>中間要有一顆棋,目標(biāo)也有棋,且是敵方的棋,畢竟不能自己吃自己哈
7.卒/兵:
河這邊:只能前進(jìn)不能后退,不能橫著走?。?! 河對(duì)面:可以前進(jìn),可以橫著走,不能后退!??!
面板設(shè)計(jì)
看上去一定很挫!哈哈,別急,聽(tīng)我細(xì)細(xì)道來(lái)! 一般的界面設(shè)計(jì)我們都知道橫縱坐標(biāo)是這樣的:
但是我選擇背道而行,不是因?yàn)閯e的,是為了更好的去讓初學(xué)者理解,我們把原本的x坐標(biāo)看成數(shù)組的列(col),把y坐標(biāo)看成我們數(shù)組的行(row),這樣是不是更好理解一點(diǎn)呢,當(dāng)然了我就是這么理解的,哈哈,接下來(lái)的游戲代碼編程我們會(huì)把橫坐標(biāo)用y*width,縱坐標(biāo)用x*height你們應(yīng)該就能理解為什么了,因?yàn)閤是數(shù)組的行,也就是坐標(biāo)縱坐標(biāo)(y)的體現(xiàn),同理數(shù)組中的y也是如此。
數(shù)據(jù)傳輸:這里我們采用UDP協(xié)議來(lái)進(jìn)行通訊,所以你們也要先去了解一下UDP協(xié)議的一些基本方法,這里就不細(xì)講了。
通訊協(xié)議:這里我們自定義通訊協(xié)議?。?“play|”——–以此開(kāi)頭代表一端發(fā)出了游戲邀請(qǐng),等待另一端的回應(yīng); “connect|”——-以此開(kāi)頭代表另一端收到邀請(qǐng)并且同意建立連接通訊!如果邀請(qǐng)者受到這條消息就代表通訊建立成功,可以開(kāi)始游戲了; “move|”——以此開(kāi)頭代表移動(dòng)數(shù)據(jù)傳輸,如果一端移動(dòng)了棋子,那么另一端也要收到信息,重新繪制界面; “l(fā)ose|”——–以此開(kāi)頭代表一方認(rèn)輸,如果有一方認(rèn)輸就會(huì)向另一方發(fā)送該信息; “quit|”——-以此開(kāi)頭代表一方退出游戲,任意一方離開(kāi)都會(huì)向?qū)Ψ桨l(fā)送該信息,以提示對(duì)方; “success|”—–以此開(kāi)頭代表勝利,某一方勝利就向?qū)Ψ桨l(fā)出信息,通知對(duì)方; “regret|”——以此開(kāi)頭表示悔棋,這個(gè)不用講了吧,大家都明白,但是本次編程中我沒(méi)有把這個(gè)加進(jìn)去,這個(gè)你們可以自己根據(jù)自己需要去添加。 (肯定有人問(wèn)我這個(gè)協(xié)議是誰(shuí)定義的,啊哈哈,讓你們失望了,這是我自己定義的,這個(gè)通訊協(xié)議只適用于你們寫(xiě)的這個(gè)代碼,和使用這個(gè)代碼的兩個(gè)人通訊使用,所以協(xié)議如何自己可以定義的哦)
代碼實(shí)現(xiàn)
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;//當(dāng)前棋子對(duì)象的名字 public int owner;//當(dāng)前棋子對(duì)象的所有者--黑方還是紅方 public Point point;//當(dāng)前棋子對(duì)象的位置 public Image chessImage;//當(dāng)前棋子對(duì)象的圖像 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)//獲取每一個(gè)棋子對(duì)象名字,所有者,位置,和圖片信息 { 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)//畫(huà)棋子 { g.drawImage(chessImage, point.y*width-width/2, point.x*height-height/2, width, height, (ImageObserver)i); } protected void paintSeclected(Graphics g)//畫(huà)鼠標(biāo)選擇了以后的棋子對(duì)象的邊框 { g.drawRect(point.y*width-width/2, point.x*height-height/2, width, height); } public void SetPos(int x, int y)//重新設(shè)置移動(dòng)以后的棋子對(duì)象的位置坐標(biāo) { point.x = x; point.y = y; } public void ReversePos()//將該對(duì)象的位置坐標(biāo)逆置輸出,用于方便顯示信息情況 { 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];//創(chuàng)建了32個(gè)棋子對(duì)象 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;//設(shè)置當(dāng)前玩家對(duì)象 private boolean isFirst = false;//判斷是否是第一次點(diǎn)擊的棋子,以此分開(kāi)兩次點(diǎn)擊棋子的碰撞矛盾 private int x1,y1,x2,y2;//用來(lái)保存第一次第二次選中的坐標(biāo)的 private boolean flag = true;//用來(lái)控制線程的運(yùn)行 private boolean isPlay = false; private Chess firstChess = null; private Chess secondChess = null;//設(shè)置第一次點(diǎn)擊的棋子和第二次選中的棋子對(duì)象 private InetAddress myID;//自己id地址 private InetAddress youID;//目標(biāo)ID地址 private int sendport;//發(fā)送端口 private int receiveport = 8888;//接收端口 public ChessPanel()//構(gòu)造函數(shù) { init_map();//初始化棋盤(pán) //給這個(gè)面板添加鼠標(biāo)監(jiān)聽(tīng)機(jī)制 this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if(isPlay == true)//判斷是否該本方下棋 { SelectChess(e.getPoint());//選擇要移動(dòng)的棋子 repaint(); } } public void SelectChess(Point pos) { int x = pos.x; int y = pos.y;//獲取此時(shí)此刻鼠標(biāo)點(diǎn)擊的位置坐標(biāo) System.out.println("選擇要移動(dòng)的棋子坐標(biāo):x->"+x+" y->"+y); if(x > 0 && x < (Col-1)*width && y > 0 && y < (Row-1)*height)//判斷鼠標(biāo)是否在合理的范圍,不在就直接退出 { Point point = ReSetID(x,y); if(isFirst)//判斷是否是第一次選中的棋子 { x1 = point.x; y1 = point.y; //判斷第一次選中的棋子是不是自己的棋子或者是不是無(wú)效棋子,不是就失敗 int id = map[x1][y1]; if(id != -1 && chess[id].owner == player) { isFirst = false; firstChess = chess[id]; System.out.println("id->"+id); } else//第一次選擇的棋子無(wú)效 { JOptionPane.showConfirmDialog(null, "提示", "第一次選棋無(wú)效!請(qǐng)重新選擇!", JOptionPane.OK_OPTION); isFirst = true; } } else//第二次選中的棋子 { x2 = point.x; y2 = point.y; int id = map[x2][y2]; if(id != -1 && chess[id].owner != player)//第二次選擇了敵方棋子,將敵方棋子保存起來(lái) { isFirst = true; secondChess = chess[id]; //開(kāi)始判斷是否可以移動(dòng)棋子,如果可以就將棋子移動(dòng),并發(fā)信息給對(duì)方我們已經(jīng)移動(dòng)的棋子信息 //判斷是否可以移動(dòng)棋子 if(IsMoveChess(firstChess,x2,y2))//可以移動(dòng)-吃棋 { 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, "提示", "對(duì)不起,移動(dòng)棋子失敗,請(qǐng)重新選擇目標(biāo)!", JOptionPane.ERROR_MESSAGE); isFirst = false; } } else if(id != -1 && chess[id].owner == player)//第二次又選擇了自己的棋子,那么就將第二次選擇的棋子當(dāng)做第一次選擇的棋子 { firstChess = chess[id]; x1 = x2; y1 = y2; isFirst = false; } else//第二次選擇的棋子是空,那么就是單純的移動(dòng)棋子 { secondChess = null; if(IsMoveChess(firstChess,x2,y2))//可以移動(dòng)-吃棋 { 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("第二次選中棋子為空:目標(biāo)-》"+(Row-1-x2)+" "+(Col-1-y2)); repaint(); isFirst = true; isPlay = false; } } } } } }); } public boolean IsMoveChess(Chess chess,int x,int y)//判斷是否可以移動(dòng)棋子----移動(dòng)棋子的規(guī)則 { 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))//判斷兩個(gè)將領(lǐng)之間吃棋 { 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("相"))//相走田字,且不能過(guò)河 { 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的情況出現(xiàn) return false; } else return false; } else if(chess.chessName.equals("馬"))//馬走日,防止蹩腳的情況出現(xiàn) { 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)//水平移動(dòng) { int i = y < y0 ? y : y0; int max = y > y0 ? y : y0; for(i = i+1; i < max; i++)//不判斷目標(biāo)狀態(tài),目標(biāo)狀態(tà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)//垂直移動(dòng) { 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("炮"))//跑隔山打牛,不隔山就走路,水平或者垂直移動(dòng) { 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)//水平移動(dòng) { 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)//垂直移動(dòng) { 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)//說(shuō)明中間有一個(gè)棋 {// 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)//說(shuō)明中間沒(méi)有棋 { if(map[x][y] == -1)//目標(biāo)沒(méi)有棋 { return true; } else return false;// return true; } else return false; } else return false;//越界 } else if(chess.chessName.equals("兵") || chess.chessName.equals("卒"))//卒子在自己區(qū)域不能退,只能前進(jìn),每次只走一步 { 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轉(zhuǎn)化成可辨識(shí)的坐標(biāo)信息 { int posx = (y+height/2)/height; int posy = (x+width/2)/width; return new Point(posx,posy); } public void init_map()//初始化棋盤(pán) { for(int i = 0; i < Row; i++) { for(int j = 0; j < Col; j++) { map[i][j] = -1;//將棋盤(pán)初始化為-1,表示沒(méi)有棋子id } } } public void paint(Graphics g)//自己畫(huà)棋盤(pán) { super.paint(g); g.clearRect(0,0,this.getWidth(),this.getHeight()); //畫(huà)棋盤(pán) int a = 1; int b = 8; int c = 5;//兩軍中間的分界線 for(int j = 1; j < Row-1; j++)//畫(huà)橫線 { g.drawLine(a*width, j*height, (Col-2)*width, j*height); } for(int i = 1; i < Col-1; i++)//畫(huà)豎線 { 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); //畫(huà)棋子 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) //發(fā)送數(shù)據(jù)報(bào) { DatagramSocket s = null; try{ s = new DatagramSocket();//創(chuàng)建一個(gè)數(shù)據(jù)報(bào)套接字 byte data[] = new byte[100]; data = str.getBytes(); DatagramPacket pocket = new DatagramPacket(data,data.length,ip,port);//將數(shù)據(jù)報(bào)的信息放入自尋址包中,自尋址信息包括數(shù)據(jù),數(shù)據(jù)長(zhǎng)度,目標(biāo)ip地址,目標(biāo)端口號(hào) s.send(pocket);//發(fā)送自尋址包 System.out.println("發(fā)送信息:"+str); }catch(IOException ex) { ex.printStackTrace(); }finally { if(s != null) s.close(); } } public void startgame(InetAddress ip, int otherport, int myport)//游戲正式開(kāi)始的起點(diǎn)入口 { youID = ip; this.sendport = otherport; this.receiveport = myport; try{ myID = InetAddress.getLocalHost(); }catch(UnknownHostException ex) { ex.printStackTrace(); } send("play|",youID,sendport);//發(fā)送邀請(qǐng),等待目標(biāo)ip的回應(yīng)----開(kāi)啟一個(gè)線程,不斷監(jiān)聽(tīng)端口,檢查是否有消息,是否建立連接成功 Thread t = new Thread(this); t.start(); } public void FirstPaintChess()//第一次畫(huà)棋盤(pán)---將每個(gè)棋盤(pán)上的棋子對(duì)象擺放完好,設(shè)置各自的初始屬性 { //原本把黑棋放上面,紅棋放下面,但是為了顯示效果,凡是玩家玩,都把玩家的花色放下面 init_map();//如果再玩一局就要先清空棋盤(pán),然后再重置棋子,否則上一局某些位置上面的id會(huì)遺留下來(lái) paintChess(); if(player == BLACKCHESS) { ReverseChess(); } repaint(); } public void ReverseChess()//轉(zhuǎn)置,將坐標(biāo)改變,以便于下棋者下棋 { //先改變坐標(biāo)// 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()//畫(huà)棋盤(pán)顯示,上面黑棋,下面紅棋 { //黑方 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; } //畫(huà)紅棋 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);//打開(kāi)監(jiān)聽(tīng)窗口 byte data[] = new byte[100]; DatagramPacket pocket = new DatagramPacket(data,data.length); while(flag) { sock.receive(pocket);//接收數(shù)據(jù) //讀取接收信息 String str = new String(data); String s[] = new String[6]; s = str.split("\\|");//將數(shù)據(jù)信息按照|進(jìn)行分割 if(s[0].equals("play"))//表示此時(shí)這個(gè)對(duì)象是一個(gè)被邀請(qǐng)的對(duì)象,將被邀請(qǐng)的對(duì)象設(shè)置為黑棋 { player = BLACKCHESS;//被邀請(qǐng)者設(shè)為黑棋 send("connect|",youID,sendport); //開(kāi)始畫(huà)棋盤(pán) FirstPaintChess(); isPlay = false;//因?yàn)槭羌t棋先走,所以黑棋此時(shí)不能下棋 } else if(s[0].equals("connect"))//表示此時(shí)的對(duì)象是游戲發(fā)出者對(duì)象,并且已經(jīng)和被邀請(qǐng)對(duì)象建立連接 { player = REDCHESS;//游戲發(fā)出者設(shè)為紅棋對(duì)象 FirstPaintChess(); isPlay = true;//因?yàn)榇藭r(shí)是紅棋,而紅旗先走,所以紅棋此時(shí)可以下棋 } else if(s[0].equals("lose"))//對(duì)方認(rèn)輸 { JOptionPane.showConfirmDialog(null, "認(rèn)輸", "對(duì)方棋手認(rèn)輸!", JOptionPane.OK_OPTION); isPlay = false; } else if(s[0].equals("success"))//對(duì)方贏了 { 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"))//對(duì)方走棋 { 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"))//對(duì)方退出 { JOptionPane.showConfirmDialog(null, "提示", "對(duì)方離開(kāi),游戲結(jié)束!", 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("開(kāi)始"); private JButton end = new JButton("結(jié)束"); private JButton lose = new JButton("認(rèn)輸"); 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("目標(biāo)端口"); 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;//目標(biāo)ID地址 private int sendport;//發(fā)送端口 private int receiveport = 8888;//接收端口 public ChessFrame()//構(gòu)造函數(shù) { 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"));//標(biāo)簽加載圖片 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網(wǎng)絡(luò)象棋"); 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();//獲取當(dāng)前目標(biāo)ip地址 sendport = Integer.parseInt(otherPort.getText());//獲取目標(biāo)連接端口 myID = InetAddress.getLocalHost();//獲取本地ip地址 youID = InetAddress.getByName(ip);//獲取目標(biāo)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);//向?qū)Ψ桨l(fā)送離開(kāi)信息,同時(shí)斷開(kāi)連接 System.exit(0); }catch(Exception ex) { ex.printStackTrace(); } } }); lose.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try{ chesspanel.send("lose|",youID,sendport);//向?qū)Ψ桨l(fā)送認(rèn)輸信息 }catch(Exception ex) { ex.printStackTrace(); } } }); //加一個(gè)對(duì)方求和的按鈕 } public static void main(String[] args) { // TODO Auto-generated method stub new ChessFrame(); }}
“怎么用java實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)象棋游戲”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
文章名稱:怎么用java實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)象棋游戲-創(chuàng)新互聯(lián)
鏈接地址:http://jinyejixie.com/article16/dsgddg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、品牌網(wǎng)站建設(shè)、網(wǎng)站營(yíng)銷、企業(yè)網(wǎng)站制作、電子商務(wù)、服務(wù)器托管
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容