您好,登錄后才能下訂單哦!
這篇文章主要介紹了Java實現五子棋網絡版的方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
具體內容如下
需求分析:
對于網絡五子棋而言,在普通五子棋的基礎上需要添加以下功能:
1.擁有服務器端和客戶端,用戶通過客戶端登錄服務器后可與其他登錄的用戶進行對弈
2.服務器支持多組用戶同時進行對弈
3.用戶可以在服務器上創建新游戲或加入已創建的游戲
4.用戶在下棋的時候可以進行聊天交流
由上可以知道需要實現的功能:
·提供服務器和客戶端的功能
·服務器將監聽客戶端的登錄情況并允許多個客戶端進行登錄
·用戶通過客戶端可以登錄服務器,之后可以看到服務器當前在線的其他用戶,并與他們進行聊天等
·用戶登錄服務器后,可以創建新的五子棋游戲或加入已創建的五子棋游戲
·用戶通過客戶端可以像普通五子棋那樣與其他用戶對弈
根據功能將網絡五子棋分為4個模塊:即用戶面板模塊、棋盤面板模塊、五子棋服務器模塊、五子棋客戶端模塊
下面我們開始進行編譯用戶面板模塊:
1.開發用戶列表面板
import java.awt.*; /** * Created by Administrator on 2016/11/21. */ //初始狀態下將添加10個名稱為“無用戶“的信息到列表中,說明服務器最多支持10個用戶同時在線 //該列表被添加到面板中,使用“BorderLayout”布局格式 public class UserListPad extends Panel{ public List userList=new List(10); public UserListPad(){ setLayout(new BorderLayout()); for(int i=0;i<10;i++){ userList.add(i+"."+"無用戶"); } add(userList,BorderLayout.CENTER); } }
2.開發用戶聊天面板
import javax.swing.*; import java.awt.*; /** * Created by Administrator on 2016/11/21. */ //聊天面板為一個TextArea視圖控件,擁有一個垂直方向的滾動條。 //該TextArea被添加到面板中,使用“BorderLayout”布局格式。 public class UserChatPad extends JPanel{ public JTextArea chatTextArea=new JTextArea("命令區域",18,20); public UserChatPad(){ setLayout(new BorderLayout()); chatTextArea.setAutoscrolls(true); chatTextArea.setLineWrap(true); add(chatTextArea,BorderLayout.CENTER); } }
3.開發用戶輸入面板
import javax.swing.*; import java.awt.*; /** * Created by Administrator on 2016/11/21. */ //面板包含兩個視圖控件 //contentInpitted為TextField控件,用戶可以在其中輸入聊天信息 public class UserInputPad extends JPanel{ public JTextField contentInputted = new JTextField("",26); public JComboBox userChoice = new JComboBox(); public UserInputPad(){ setLayout(new FlowLayout(FlowLayout.LEFT)); for(int i=0;i<50;i++){ userChoice.addItem(i+"."+"無用戶"); } userChoice.setSize(60,24); add(userChoice); add(contentInputted); } }
4.開發用戶操作面板
import javax.swing.*; import java.awt.*; /** * Created by Administrator on 2016/11/21. */ public class UserControlPad extends JPanel { public JLabel ipLabel = new JLabel("IP",JLabel.LEFT); public JTextField ipInputted = new JTextField("localhost",10); public JButton connectButton = new JButton("連接到服務器"); public JButton createButton = new JButton("創建游戲"); public JButton joinButton = new JButton("加入游戲"); public JButton cancelButton = new JButton("放棄游戲"); public JButton exitButton = new JButton("退出游戲"); public UserControlPad(){ setLayout(new FlowLayout(FlowLayout.LEFT)); setBackground(Color.LIGHT_GRAY); add(ipLabel); add(ipInputted); add(connectButton); add(createButton); add(joinButton); add(cancelButton); add(exitButton); } }
下面開始開發棋盤面板模塊
1.開發黑棋類
import java.awt.*; /** * Created by Administrator on 2016/11/21. */ public class FIRPointBlack extends Canvas { FIRPad padBelonged; // 黑棋所屬的棋盤 public FIRPointBlack(FIRPad padBelonged) { setSize(20, 20); // 設置棋子大小 this.padBelonged = padBelonged; } public void paint(Graphics g) { // 畫棋子 g.setColor(Color.black); g.fillOval(0, 0, 14, 14); } }
2.開發白棋類
import java.awt.*; /** * Created by Administrator on 2016/11/21. */ public class FIRPointWhite extends Canvas{ FIRPad padBelonged; // 白棋所屬的棋盤 public FIRPointWhite(FIRPad padBelonged) { setSize(20, 20); this.padBelonged = padBelonged; } public void paint(Graphics g) { // 畫棋子 g.setColor(Color.white); g.fillOval(0, 0, 14, 14); } }
3.開發棋盤面板
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.JTextField; /** * Created by Administrator on 2016/11/21. */ public class FIRPad extends Panel implements MouseListener,ActionListener{ // 鼠標是否能使用 public boolean isMouseEnabled = false; // 是否勝利 public boolean isWinned = false; // 是否在下棋中 public boolean isGaming = false; // 棋子的x軸坐標位 public int chessX_POS = -1; // 棋子的y軸坐標位 public int chessY_POS = -1; // 棋子的顏色 public int chessColor = 1; // 黑棋x軸坐標位數組 public int chessBlack_XPOS[] = new int[200]; // 黑棋y軸坐標位數組 public int chessBlack_YPOS[] = new int[200]; // 白棋x軸坐標位數組 public int chessWhite_XPOS[] = new int[200]; // 白棋y軸坐標位數組 public int chessWhite_YPOS[] = new int[200]; // 黑棋數量 public int chessBlackCount = 0; // 白棋數量 public int chessWhiteCount = 0; // 黑棋獲勝次數 public int chessBlackVicTimes = 0; // 白棋獲勝次數 public int chessWhiteVicTimes = 0; // 套接口 public Socket chessSocket; public DataInputStream inputData; public DataOutputStream outputData; public String chessSelfName = null; public String chessPeerName = null; public String host = null; public int port = 4331; public TextField statusText = new TextField("請連接服務器!"); public FIRThread firThread = new FIRThread(this); public FIRPad() { setSize(440, 440); setLayout(null); setBackground(Color.LIGHT_GRAY); addMouseListener(this); add(statusText); statusText.setBounds(new Rectangle(40, 5, 360, 24)); statusText.setEditable(false); } // 連接到主機 public boolean connectServer(String ServerIP, int ServerPort) throws Exception { try { // 取得主機端口 chessSocket = new Socket(ServerIP, ServerPort); // 取得輸入流 inputData = new DataInputStream(chessSocket.getInputStream()); // 取得輸出流 outputData = new DataOutputStream(chessSocket.getOutputStream()); firThread.start(); return true; } catch (IOException ex) { statusText.setText("連接失敗! \n"); } return false; } // 設定勝利時的棋盤狀態 public void setVicStatus(int vicChessColor) { // 清空棋盤 this.removeAll(); // 將黑棋的位置設置到零點 for (int i = 0; i <= chessBlackCount; i++) { chessBlack_XPOS[i] = 0; chessBlack_YPOS[i] = 0; } // 將白棋的位置設置到零點 for (int i = 0; i <= chessWhiteCount; i++) { chessWhite_XPOS[i] = 0; chessWhite_YPOS[i] = 0; } // 清空棋盤上的黑棋數 chessBlackCount = 0; // 清空棋盤上的白棋數 chessWhiteCount = 0; add(statusText); statusText.setBounds(40, 5, 360, 24); if (vicChessColor == 1) { // 黑棋勝 chessBlackVicTimes++; statusText.setText("黑方勝,黑:白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes + ",游戲重啟,等待白方..."); } else if (vicChessColor == -1) { // 白棋勝 chessWhiteVicTimes++; statusText.setText("白方勝,黑:白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes + ",游戲重啟,等待黑方..."); } } // 取得指定棋子的位置 public void setLocation(int xPos, int yPos, int chessColor) { if (chessColor == 1) { // 棋子為黑棋時 chessBlack_XPOS[chessBlackCount] = xPos * 20; chessBlack_YPOS[chessBlackCount] = yPos * 20; chessBlackCount++; } else if (chessColor == -1) { // 棋子為白棋時 chessWhite_XPOS[chessWhiteCount] = xPos * 20; chessWhite_YPOS[chessWhiteCount] = yPos * 20; chessWhiteCount++; } } // 判斷當前狀態是否為勝利狀態 public boolean checkVicStatus(int xPos, int yPos, int chessColor) { int chessLinkedCount = 1; // 連接棋子數 int chessLinkedCompare = 1; // 用于比較是否要繼續遍歷一個棋子的相鄰網格 int chessToCompareIndex = 0; // 要比較的棋子在數組中的索引位置 int closeGrid = 1; // 相鄰網格的位置 if (chessColor == 1) { // 黑棋時 chessLinkedCount = 1; // 將該棋子自身算入的話,初始連接數為1 //以下每對for循環語句為一組,因為下期的位置能位于中間而非兩端 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { // 遍歷相鄰4個網格 for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { // 遍歷棋盤上所有黑棋子 if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos * 20) == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的右邊4個棋子是否都為黑棋 chessLinkedCount = chessLinkedCount + 1; // 連接數加1 if (chessLinkedCount == 5) { // 五子相連時,勝利 return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else {// 若中間有一個棋子非黑棋,則會進入此分支,此時無需再遍歷 break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && (yPos * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的左邊4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 進入新的一組for循環時要將連接數等重置 chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的上邊4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的下邊4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的左上方向4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的右下方向4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的右上方向4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // 判斷當前下的棋子的左下方向4個棋子是否都為黑棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } } else if (chessColor == -1) { // 白棋時 chessLinkedCount = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && (yPos * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的右邊4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && (yPos * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的左邊4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的上邊4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的下邊4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的左上方向4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的右下方向4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的右上方向4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// 判斷當前下的棋子的左下方向4個棋子是否都為白棋 chessLinkedCount++; if (chessLinkedCount == 5) { return (true); } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } } 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 paintFirPoint(int xPos, int yPos, int chessColor) { FIRPointBlack firPBlack = new FIRPointBlack(this); FIRPointWhite firPWhite = new FIRPointWhite(this); if (chessColor == 1 && isMouseEnabled) { // 黑棋 // 設置棋子的位置 setLocation(xPos, yPos, chessColor); // 取得當前局面狀態 isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { // 非勝利狀態 firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPBlack); // 將棋子添加到棋盤中 firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); // 設置棋子邊界 statusText.setText("黑(第" + chessBlackCount + "步)" + xPos + " " + yPos + ",輪到白方."); isMouseEnabled = false; // 將鼠標設為不可用 } else { // 勝利狀態 firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPBlack); firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(1); // 調用勝利方法,傳入參數為黑棋勝利 isMouseEnabled = false; } } else if (chessColor == -1 && isMouseEnabled) { // 白棋 setLocation(xPos, yPos, chessColor); isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); statusText.setText("白(第" + chessWhiteCount + "步)" + xPos + " " + yPos + ",輪到黑方."); isMouseEnabled = false; } else { firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(-1); // 調用勝利方法,傳入參數為白棋 isMouseEnabled = false; } } } // 畫網絡棋盤 public void paintNetFirPoint(int xPos, int yPos, int chessColor) { FIRPointBlack firPBlack = new FIRPointBlack(this); FIRPointWhite firPWhite = new FIRPointWhite(this); setLocation(xPos, yPos, chessColor); if (chessColor == 1) { isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { this.add(firPBlack); firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); statusText.setText("黑(第" + chessBlackCount + "步)" + xPos + " " + yPos + ",輪到白方."); isMouseEnabled = true; } else { firThread.sendMessage("/" + chessPeerName + " /victory " + chessColor);//djr this.add(firPBlack); firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(1); isMouseEnabled = true; } } else if (chessColor == -1) { isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); statusText.setText("白(第" + chessWhiteCount + "步)" + xPos + " " + yPos + ",輪到黑方."); isMouseEnabled = true; } else { firThread.sendMessage("/" + chessPeerName + " /victory " + chessColor); this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(-1); isMouseEnabled = true; } } } // 捕獲下棋事件 public void mousePressed(MouseEvent e) { if (e.getModifiers() == InputEvent.BUTTON1_MASK) { chessX_POS = (int) e.getX(); chessY_POS = (int) e.getY(); int a = (chessX_POS + 10) / 20, b = (chessY_POS + 10) / 20; if (chessX_POS / 20 < 2 || chessY_POS / 20 < 2 || chessX_POS / 20 > 19 || chessY_POS / 20 > 19) { // 下棋位置不正確時,不執行任何操作 } else { paintFirPoint(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){} }
4.開發棋盤線程
import java.util.StringTokenizer; import java.io.IOException; /** * Created by Administrator on 2016/11/21. */ public class FIRThread extends Thread{ FIRPad currPad; // 當前線程的棋盤 public FIRThread(FIRPad currPad) { this.currPad = currPad; } // 處理取得的信息 public void dealWithMsg(String msgReceived) { if (msgReceived.startsWith("/chess ")) { // 收到的信息為下棋 StringTokenizer userMsgToken = new StringTokenizer(msgReceived, " "); // 表示棋子信息的數組、0索引為:x坐標;1索引位:y坐標;2索引位:棋子顏色 String[] chessInfo = { "-1", "-1", "0" }; int i = 0; // 標志位 String chessInfoToken; while (userMsgToken.hasMoreTokens()) { chessInfoToken = (String) userMsgToken.nextToken(" "); if (i >= 1 && i <= 3) { chessInfo[i - 1] = chessInfoToken; } i++; } currPad.paintNetFirPoint(Integer.parseInt(chessInfo[0]), Integer .parseInt(chessInfo[1]), Integer.parseInt(chessInfo[2])); } else if (msgReceived.startsWith("/yourname ")) { // 收到的信息為改名 currPad.chessSelfName = msgReceived.substring(10); } else if (msgReceived.equals("/error")) { // 收到的為錯誤信息 currPad.statusText.setText("用戶不存在,請重新加入!"); } } // 發送信息 public void sendMessage(String sndMessage) { try { currPad.outputData.writeUTF(sndMessage); } catch (Exception ea) { ea.printStackTrace();; } } public void run() { String msgReceived = ""; try { while (true) { // 等待信息輸入 msgReceived = currPad.inputData.readUTF(); dealWithMsg(msgReceived); } } catch (IOException es){} } }
下面開始開發服務器模塊
1.開發服務器信息面板
import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextArea; import javax.swing.JLabel; /** * Created by Administrator on 2016/11/21. */ public class ServerMsgPanel extends Panel { public TextArea msgTextArea = new TextArea("", 22, 50, TextArea.SCROLLBARS_VERTICAL_ONLY); public JLabel statusLabel = new JLabel("當前連接數:", Label.LEFT); public Panel msgPanel = new Panel(); public Panel statusPanel = new Panel(); public ServerMsgPanel() { setSize(350, 300); setBackground(Color.LIGHT_GRAY); setLayout(new BorderLayout()); msgPanel.setLayout(new FlowLayout()); msgPanel.setSize(210, 210); statusPanel.setLayout(new BorderLayout()); statusPanel.setSize(210, 50); msgPanel.add(msgTextArea); statusPanel.add(statusLabel, BorderLayout.WEST); add(msgPanel, BorderLayout.CENTER); add(statusPanel, BorderLayout.NORTH); } }
2.開發服務器進程
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; /** * Created by Administrator on 2016/11/21. */ public class FIRServerThread extends Thread{ Socket clientSocket; // 保存客戶端套接口信息 Hashtable clientDataHash; // 保存客戶端端口與輸出流對應的Hash Hashtable clientNameHash; // 保存客戶端套接口和客戶名對應的Hash Hashtable chessPeerHash; // 保存游戲創建者和游戲加入者對應的Hash ServerMsgPanel serverMsgPanel; boolean isClientClosed = false; public FIRServerThread(Socket clientSocket, Hashtable clientDataHash, Hashtable clientNameHash, Hashtable chessPeerHash, ServerMsgPanel server) { this.clientSocket = clientSocket; this.clientDataHash = clientDataHash; this.clientNameHash = clientNameHash; this.chessPeerHash = chessPeerHash; this.serverMsgPanel = server; } public void dealWithMsg(String msgReceived) { String clientName; String peerName; if (msgReceived.startsWith("/")) { if (msgReceived.equals("/list")) { // 收到的信息為更新用戶列表 Feedback(getUserList()); } else if (msgReceived.startsWith("/creatgame [inchess]")) { // 收到的信息為創建游戲 String gameCreaterName = msgReceived.substring(20); //取得服務器名 synchronized (clientNameHash) { // 將用戶端口放到用戶列表中 clientNameHash.put(clientSocket, msgReceived.substring(11)); } synchronized (chessPeerHash) { // 將主機設置為等待狀態 chessPeerHash.put(gameCreaterName, "wait"); } Feedback("/yourname " + clientNameHash.get(clientSocket)); sendGamePeerMsg(gameCreaterName, "/OK"); sendPublicMsg(getUserList()); } else if (msgReceived.startsWith("/joingame ")) { // 收到的信息為加入游戲時 StringTokenizer userTokens = new StringTokenizer(msgReceived, " "); String userToken; String gameCreatorName; String gamePaticipantName; String[] playerNames = { "0", "0" }; int nameIndex = 0; while (userTokens.hasMoreTokens()) { userToken = (String) userTokens.nextToken(" "); if (nameIndex >= 1 && nameIndex <= 2) { playerNames[nameIndex - 1] = userToken; // 取得游戲者命 } nameIndex++; } gameCreatorName = playerNames[0]; gamePaticipantName = playerNames[1]; if (chessPeerHash.containsKey(gameCreatorName) && chessPeerHash.get(gameCreatorName).equals("wait")) { // 游戲已創建 synchronized (clientNameHash) { // 增加游戲加入者的套接口與名稱的對應 clientNameHash.put(clientSocket, ("[inchess]" + gamePaticipantName)); } synchronized (chessPeerHash) { // 增加或修改游戲創建者與游戲加入者的名稱的對應 chessPeerHash.put(gameCreatorName, gamePaticipantName); } sendPublicMsg(getUserList()); // 發送信息給游戲加入者 sendGamePeerMsg(gamePaticipantName, ("/peer " + "[inchess]" + gameCreatorName)); // 發送游戲給游戲創建者 sendGamePeerMsg(gameCreatorName, ("/peer " + "[inchess]" + gamePaticipantName)); } else { // 若游戲未創建則拒絕加入游戲 sendGamePeerMsg(gamePaticipantName, "/reject"); try { closeClient(); } catch (Exception ez) { ez.printStackTrace(); } } } else if (msgReceived.startsWith("/[inchess]")) { // 收到的信息為游戲中時 int firstLocation = 0, lastLocation; lastLocation = msgReceived.indexOf(" ", 0); peerName = msgReceived.substring((firstLocation + 1), lastLocation); msgReceived = msgReceived.substring((lastLocation + 1)); if (sendGamePeerMsg(peerName, msgReceived)) { Feedback("/error"); } } else if (msgReceived.startsWith("/giveup ")) { // 收到的信息為放棄游戲時 String chessClientName = msgReceived.substring(8); if (chessPeerHash.containsKey(chessClientName) && !((String) chessPeerHash.get(chessClientName)) .equals("wait")) { // 勝利方為游戲加入者,發送勝利信息 sendGamePeerMsg((String) chessPeerHash.get(chessClientName), "/youwin"); synchronized (chessPeerHash) { // 刪除退出游戲的用戶 chessPeerHash.remove(chessClientName); } } if (chessPeerHash.containsValue(chessClientName)) { // 勝利方為游戲創建者,發送勝利信息 sendGamePeerMsg((String) getHashKey(chessPeerHash, chessClientName), "/youwin"); synchronized (chessPeerHash) {// 刪除退出游戲的用戶 chessPeerHash.remove((String) getHashKey(chessPeerHash, chessClientName)); } } } else { // 收到的信息為其它信息時 int lastLocation = msgReceived.indexOf(" ", 0); if (lastLocation == -1) { Feedback("無效命令"); return; } } } else { msgReceived = clientNameHash.get(clientSocket) + ">" + msgReceived; serverMsgPanel.msgTextArea.append(msgReceived + "\n"); sendPublicMsg(msgReceived); serverMsgPanel.msgTextArea.setCaretPosition(serverMsgPanel.msgTextArea.getText() .length()); } } // 發送公開信息 public void sendPublicMsg(String publicMsg) { synchronized (clientDataHash) { for (Enumeration enu = clientDataHash.elements(); enu .hasMoreElements();) { DataOutputStream outputData = (DataOutputStream) enu.nextElement(); try { outputData.writeUTF(publicMsg); } catch (IOException es) { es.printStackTrace(); } } } } // 發送信息給指定的游戲中的用戶 public boolean sendGamePeerMsg(String gamePeerTarget, String gamePeerMsg) { for (Enumeration enu = clientDataHash.keys(); enu.hasMoreElements();) { // 遍歷以取得游戲中的用戶的套接口 Socket userClient = (Socket) enu.nextElement(); if (gamePeerTarget.equals((String) clientNameHash.get(userClient)) && !gamePeerTarget.equals((String) clientNameHash .get(clientSocket))) { // 找到要發送信息的用戶時 synchronized (clientDataHash) { // 建立輸出流 DataOutputStream peerOutData = (DataOutputStream) clientDataHash .get(userClient); try { // 發送信息 peerOutData.writeUTF(gamePeerMsg); } catch (IOException es) { es.printStackTrace(); } } return false; } } return true; } // 發送反饋信息給連接到主機的人 public void Feedback(String feedBackMsg) { synchronized (clientDataHash) { DataOutputStream outputData = (DataOutputStream) clientDataHash .get(clientSocket); try { outputData.writeUTF(feedBackMsg); } catch (Exception eb) { eb.printStackTrace(); } } } // 取得用戶列表 public String getUserList() { String userList = "/userlist"; for (Enumeration enu = clientNameHash.elements(); enu.hasMoreElements();) { userList = userList + " " + (String) enu.nextElement(); } return userList; } // 根據value值從Hashtable中取得相應的key public Object getHashKey(Hashtable targetHash, Object hashValue) { Object hashKey; for (Enumeration enu = targetHash.keys(); enu.hasMoreElements();) { hashKey = (Object) enu.nextElement(); if (hashValue.equals((Object) targetHash.get(hashKey))) return hashKey; } return null; } // 剛連接到主機時執行的方法 public void sendInitMsg() { sendPublicMsg(getUserList()); Feedback("/yourname " + (String) clientNameHash.get(clientSocket)); Feedback("Java 五子棋客戶端"); Feedback("/list --更新用戶列表"); Feedback("/<username> <talk> --私聊"); Feedback("注意:命令必須對所有用戶發送"); } public void closeClient() { serverMsgPanel.msgTextArea.append("用戶斷開連接:" + clientSocket + "\n"); synchronized (chessPeerHash) { //如果是游戲客戶端主機 if (chessPeerHash.containsKey(clientNameHash.get(clientSocket))) { chessPeerHash.remove((String) clientNameHash.get(clientSocket)); } if (chessPeerHash.containsValue(clientNameHash.get(clientSocket))) { chessPeerHash.put((String) getHashKey(chessPeerHash, (String) clientNameHash.get(clientSocket)), "tobeclosed"); } } synchronized (clientDataHash) { // 刪除客戶數據 clientDataHash.remove(clientSocket); } synchronized (clientNameHash) { // 刪除客戶數據 clientNameHash.remove(clientSocket); } sendPublicMsg(getUserList()); serverMsgPanel.statusLabel.setText("當前連接數:" + clientDataHash.size()); try { clientSocket.close(); } catch (IOException exx) { exx.printStackTrace(); } isClientClosed = true; } public void run() { DataInputStream inputData; synchronized (clientDataHash) { serverMsgPanel.statusLabel.setText("當前連接數:" + clientDataHash.size()); } try { // 等待連接到主機的信息 inputData = new DataInputStream(clientSocket.getInputStream()); sendInitMsg(); while (true) { String message = inputData.readUTF(); dealWithMsg(message); } } catch (IOException esx){} finally { if (!isClientClosed) { closeClient(); } } } }
3.開發服務器端
import java.io.*; import java.net.*; import java.awt.*; import java.util.*; import java.awt.event.*; import javax.swing.JButton; /** * Created by Administrator on 2016/11/21. */ public class FIRServer extends Frame implements ActionListener{ JButton clearMsgButton = new JButton("清空列表"); JButton serverStatusButton = new JButton("服務器狀態"); JButton closeServerButton = new JButton("關閉服務器"); Panel buttonPanel = new Panel(); ServerMsgPanel serverMsgPanel = new ServerMsgPanel(); ServerSocket serverSocket; Hashtable clientDataHash = new Hashtable(50); //將客戶端套接口和輸出流綁定 Hashtable clientNameHash = new Hashtable(50); //將客戶端套接口和客戶名綁定 Hashtable chessPeerHash = new Hashtable(50); //將游戲創建者和游戲加入者綁定 public FIRServer() { super("Java 五子棋服務器"); setBackground(Color.LIGHT_GRAY); buttonPanel.setLayout(new FlowLayout()); clearMsgButton.setSize(60, 25); buttonPanel.add(clearMsgButton); clearMsgButton.addActionListener(this); serverStatusButton.setSize(75, 25); buttonPanel.add(serverStatusButton); serverStatusButton.addActionListener(this); closeServerButton.setSize(75, 25); buttonPanel.add(closeServerButton); closeServerButton.addActionListener(this); add(serverMsgPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); pack(); setVisible(true); setSize(400, 300); setResizable(false); validate(); try { createServer(4331, serverMsgPanel); } catch (Exception e) { e.printStackTrace(); } } // 用指定端口和面板創建服務器 public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException { Socket clientSocket; // 客戶端套接口 long clientAccessNumber = 1; // 連接到主機的客戶數量 this.serverMsgPanel = serverMsgPanel; // 設定當前主機 try { serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText("服務器啟動于:" + InetAddress.getLocalHost() + ":" //djr + serverSocket.getLocalPort() + "\n"); while (true) { // 監聽客戶端套接口的信息 clientSocket = serverSocket.accept(); serverMsgPanel.msgTextArea.append("已連接用戶:" + clientSocket + "\n"); // 建立客戶端輸出流 DataOutputStream outputData = new DataOutputStream(clientSocket .getOutputStream()); // 將客戶端套接口和輸出流綁定 clientDataHash.put(clientSocket, outputData); // 將客戶端套接口和客戶名綁定 clientNameHash .put(clientSocket, ("新玩家" + clientAccessNumber++)); // 創建并運行服務器端線程 FIRServerThread thread = new FIRServerThread(clientSocket, clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel); thread.start(); } } catch (IOException ex) { ex.printStackTrace(); } } public void actionPerformed(ActionEvent e) { if (e.getSource() == clearMsgButton) { // 清空服務器信息 serverMsgPanel.msgTextArea.setText(""); } if (e.getSource() == serverStatusButton) { // 顯示服務器信息 try { serverMsgPanel.msgTextArea.append("服務器信息:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n"); } catch (Exception ee) { ee.printStackTrace(); } } if (e.getSource() == closeServerButton) { // 關閉服務器 System.exit(0); } } public static void main(String args[]) { FIRServer firServer = new FIRServer(); } }
下面開始編寫客戶端模塊
1.開發客戶端
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.JFrame; import djr.chess.gui.UserChatPad; import djr.chess.gui.UserControlPad; import djr.chess.gui.UserInputPad; import djr.chess.gui.UserListPad; import djr.chess.pad.FIRPad; /** * Created by Administrator on 2016/11/21. */ public class FIRClient extends Frame implements ActionListener,KeyListener { // 客戶端套接口 Socket clientSocket; // 數據輸入流 DataInputStream inputStream; // 數據輸出流 DataOutputStream outputStream; // 用戶名 String chessClientName = null; // 主機地址 String host = null; // 主機端口 int port = 4331; // 是否在聊天 boolean isOnChat = false; // 是否在下棋 boolean isOnChess = false; // 游戲是否進行中 boolean isGameConnected = false; // 是否為游戲創建者 boolean isCreator = false; // 是否為游戲加入者 boolean isParticipant = false; // 用戶列表區 UserListPad userListPad = new UserListPad(); // 用戶聊天區 UserChatPad userChatPad = new UserChatPad(); // 用戶操作區 UserControlPad userControlPad = new UserControlPad(); // 用戶輸入區 UserInputPad userInputPad = new UserInputPad(); // 下棋區 FIRPad firPad = new FIRPad(); // 面板區 Panel southPanel = new Panel(); Panel northPanel = new Panel(); Panel centerPanel = new Panel(); Panel eastPanel = new Panel(); // 構造方法,創建界面 public FIRClient() { super("Java 五子棋客戶端"); setLayout(new BorderLayout()); host = userControlPad.ipInputted.getText(); eastPanel.setLayout(new BorderLayout()); eastPanel.add(userListPad, BorderLayout.NORTH); eastPanel.add(userChatPad, BorderLayout.CENTER); eastPanel.setBackground(Color.LIGHT_GRAY); userInputPad.contentInputted.addKeyListener(this); firPad.host = userControlPad.ipInputted.getText(); centerPanel.add(firPad, BorderLayout.CENTER); centerPanel.add(userInputPad, BorderLayout.SOUTH); centerPanel.setBackground(Color.LIGHT_GRAY); userControlPad.connectButton.addActionListener(this); userControlPad.createButton.addActionListener(this); userControlPad.joinButton.addActionListener(this); userControlPad.cancelButton.addActionListener(this); userControlPad.exitButton.addActionListener(this); userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(false); southPanel.add(userControlPad, BorderLayout.CENTER); southPanel.setBackground(Color.LIGHT_GRAY); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (isOnChat) { // 聊天中 try { // 關閉客戶端套接口 clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // 下棋中 try { // 關閉下棋端口 firPad.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } }); add(eastPanel, BorderLayout.EAST); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); pack(); setSize(670, 560); setVisible(true); setResizable(false); this.validate(); } // 按指定的IP地址和端口連接到服務器 public boolean connectToServer(String serverIP, int serverPort) throws Exception { try { // 創建客戶端套接口 clientSocket = new Socket(serverIP, serverPort); // 創建輸入流 inputStream = new DataInputStream(clientSocket.getInputStream()); // 創建輸出流 outputStream = new DataOutputStream(clientSocket.getOutputStream()); // 創建客戶端線程 FIRClientThread clientthread = new FIRClientThread(this); // 啟動線程,等待聊天信息 clientthread.start(); isOnChat = true; return true; } catch (IOException ex) { userChatPad.chatTextArea .setText("不能連接!\n"); } return false; } // 客戶端事件處理 public void actionPerformed(ActionEvent e) { if (e.getSource() == userControlPad.connectButton) { // 連接到主機按鈕單擊事件 host = firPad.host = userControlPad.ipInputted.getText(); // 取得主機地址 try { if (connectToServer(host, port)) { // 成功連接到主機時,設置客戶端相應的界面狀態 userChatPad.chatTextArea.setText(""); userControlPad.connectButton.setEnabled(false); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); firPad.statusText.setText("連接成功,請等待!"); } } catch (Exception ei) { userChatPad.chatTextArea .setText("不能連接!\n"); } } if (e.getSource() == userControlPad.exitButton) { // 離開游戲按鈕單擊事件 if (isOnChat) { // 若用戶處于聊天狀態中 try { // 關閉客戶端套接口 clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // 若用戶處于游戲狀態中 try { // 關閉游戲端口 firPad.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } if (e.getSource() == userControlPad.joinButton) { // 加入游戲按鈕單擊事件 String selectedUser = (String)userListPad.userList.getSelectedItem(); // 取得要加入的游戲 if (selectedUser == null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) { // 若未選中要加入的用戶,或選中的用戶已經在游戲,則給出提示信息 firPad.statusText.setText("必須選擇一個用戶!"); } else { // 執行加入游戲的操作 try { if (!isGameConnected) { // 若游戲套接口未連接 if (firPad.connectServer(firPad.host, firPad.port)) { // 若連接到主機成功 isGameConnected = true; isOnChess = true; isParticipant = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/joingame " + (String)userListPad.userList.getSelectedItem() + " " + chessClientName); } } else { // 若游戲端口連接中 isOnChess = true; isParticipant = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/joingame " + (String)userListPad.userList.getSelectedItem() + " " + chessClientName); } } catch (Exception ee) { isGameConnected = false; isOnChess = false; isParticipant = false; userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); userChatPad.chatTextArea .setText("不能連接: \n" + ee); } } } if (e.getSource() == userControlPad.createButton) { // 創建游戲按鈕單擊事件 try { if (!isGameConnected) { // 若游戲端口未連接 if (firPad.connectServer(firPad.host, firPad.port)) { // 若連接到主機成功 isGameConnected = true; isOnChess = true; isCreator = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/creatgame " + "[inchess]" + chessClientName); } } else { // 若游戲端口連接中 isOnChess = true; isCreator = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/creatgame " + "[inchess]" + chessClientName); } } catch (Exception ec) { isGameConnected = false; isOnChess = false; isCreator = false; userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); ec.printStackTrace(); userChatPad.chatTextArea.setText("不能連接: \n" + ec); } } if (e.getSource() == userControlPad.cancelButton) { // 退出游戲按鈕單擊事件 if (isOnChess) { // 游戲中 firPad.firThread.sendMessage("/giveup " + chessClientName); firPad.setVicStatus(-1 * firPad.chessColor); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); firPad.statusText.setText("請創建或加入游戲!"); } if (!isOnChess) { // 非游戲中 userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); firPad.statusText.setText("請創建或加入游戲!"); } isParticipant = isCreator = false; } } public void keyPressed(KeyEvent e) { TextField inputwords = (TextField) e.getSource(); if (e.getKeyCode() == KeyEvent.VK_ENTER) { // 處理回車按鍵事件 if (userInputPad.userChoice.getSelectedItem().equals("所有用戶")) { // 給所有人發信息 try { // 發送信息 outputStream.writeUTF(inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea .setText("不能連接到服務器!\n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } else { // 給指定人發信息 try { outputStream.writeUTF("/" + userInputPad.userChoice.getSelectedItem() + " " + inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea .setText("不能連接到服務器!\n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public static void main(String args[]) { FIRClient chessClient = new FIRClient(); } }
2.開發客戶端線程
import java.io.IOException; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.ListModel; /** * Created by Administrator on 2016/11/21. */ public class FIRClientThread extends Thread{ public FIRClient firClient; public FIRClientThread(FIRClient firClient) { this.firClient = firClient; } public void dealWithMsg(String msgReceived) { if (msgReceived.startsWith("/userlist ")) { // 若取得的信息為用戶列表 StringTokenizer userToken = new StringTokenizer(msgReceived, " "); int userNumber = 0; // 清空客戶端用戶列表 firClient.userListPad.userList.removeAll(); // 清空客戶端用戶下拉框 firClient.userInputPad.userChoice.removeAll(); // 給客戶端用戶下拉框添加一個選項 firClient.userInputPad.userChoice.addItem("所有用戶"); while (userToken.hasMoreTokens()) { // 當收到的用戶信息列表中存在數據時 String user = (String) userToken.nextToken(" "); // 取得用戶信息 if (userNumber > 0 && !user.startsWith("[inchess]")) { // 用戶信息有效時 firClient.userListPad.userList.add(user);// 將用戶信息添加到用戶列表中 firClient.userInputPad.userChoice.addItem(user); // 將用戶信息添加到用戶下拉框中 } userNumber++; } firClient.userInputPad.userChoice.setSelectedIndex(0);// 下拉框默認選中所有人 } else if (msgReceived.startsWith("/yourname ")) { // 收到的信息為用戶本名時 firClient.chessClientName = msgReceived.substring(10); // 取得用戶本名 firClient.setTitle("Java 五子棋客戶端 " + "用戶名:" + firClient.chessClientName); // 設置程序Frame的標題 } else if (msgReceived.equals("/reject")) { // 收到的信息為拒絕用戶時 try { firClient.firPad.statusText.setText("不能加入游戲!"); firClient.userControlPad.cancelButton.setEnabled(false); firClient.userControlPad.joinButton.setEnabled(true); firClient.userControlPad.createButton.setEnabled(true); } catch (Exception ef) { firClient.userChatPad.chatTextArea .setText("Cannot close!"); } firClient.userControlPad.joinButton.setEnabled(true); } else if (msgReceived.startsWith("/peer ")) { // 收到信息為游戲中的等待時 firClient.firPad.chessPeerName = msgReceived.substring(6); if (firClient.isCreator) { // 若用戶為游戲建立者 firClient.firPad.chessColor = 1; // 設定其為黑棋先行 firClient.firPad.isMouseEnabled = true; firClient.firPad.statusText.setText("黑方下..."); } else if (firClient.isParticipant) { // 若用戶為游戲加入者 firClient.firPad.chessColor = -1; // 設定其為白棋后性 firClient.firPad.statusText.setText("游戲加入,等待對手."); } } else if (msgReceived.equals("/youwin")) { // 收到信息為勝利信息 firClient.isOnChess = false; firClient.firPad.setVicStatus(firClient.firPad.chessColor); firClient.firPad.statusText.setText("對手退出"); firClient.firPad.isMouseEnabled = false; } else if (msgReceived.equals("/OK")) { // 收到信息為成功創建游戲 firClient.firPad.statusText.setText("游戲創建等待對手"); } else if (msgReceived.equals("/error")) { // 收到信息錯誤 firClient.userChatPad.chatTextArea.append("錯誤,退出程序.\n"); } else { firClient.userChatPad.chatTextArea.append(msgReceived + "\n"); firClient.userChatPad.chatTextArea.setCaretPosition( firClient.userChatPad.chatTextArea.getText().length()); } } public void run() { String message = ""; try { while (true) { // 等待聊天信息,進入wait狀態 message = firClient.inputStream.readUTF(); dealWithMsg(message); } } catch (IOException es){} } }
至此,網絡版五子棋就算是開發完成了。關于這么多類和包的關系如下圖:
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Java實現五子棋網絡版的方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。