Java+Swing實現(xiàn)經(jīng)典五子棋游戲
前言
五子棋是世界智力運動會競技項目之一,是一種兩人對弈的純策略型棋類游戲,是世界智力運動會競技項目之一,通常雙方分別使用黑白兩色的棋子,下在棋盤直線與橫線的交叉點上,先形成5子連線者獲勝。
棋具與圍棋通用,起源于中國上古時代的傳統(tǒng)黑白棋種之一。主要流行于華人和漢字文化圈的國家以及歐美一些地區(qū),是世界上最古老的棋。
容易上手,老少皆宜,而且趣味橫生,引人入勝;不僅能增強思維能力,提高智力,而且富含哲理,有助于修身養(yǎng)性。
用java語言實現(xiàn),采用了swing技術(shù)進行了界面化處理,設(shè)計思路用了面向?qū)ο笏枷搿?/p>
主要需求
1、對局雙方各執(zhí)一色棋子。
2、空棋盤開局。
3、黑先、白后,交替下子,每次只能下一子。
4、棋子下在棋盤的空白點上,棋子下定后,不得向其它點移動,不得從棋盤上拿掉或拿起另落別處。
5、黑方的第一枚棋子可下在棋盤任意交叉點上。
6、輪流下子是雙方的權(quán)利,但允許任何一方放棄下子權(quán),先形成5子連線者獲勝。
主要設(shè)計
1、由于是兩人的游戲,非單機版,所以要有多個客戶端相互通信,這時就要用到socket 技術(shù)
2、設(shè)計socket服務(wù)端,用來維護socket客戶端連接
3、設(shè)計socket客戶端,用來實現(xiàn)五子棋邏輯和效果
4、客戶端要能設(shè)置連接服務(wù)端的IP,用來連接服務(wù)端
5、客戶端1創(chuàng)建游戲后,客戶端2可以選擇客戶端1進行聯(lián)機對戰(zhàn)
6、游戲規(guī)則:
- 對局雙方各執(zhí)一色棋子。
- 空棋盤開局。
- 黑先、白后,交替下子,每次只能下一子。
- 棋子下在棋盤的空白點上,棋子下定后,不得向其它點移動,不得從棋盤上拿掉或拿起另落別處。
- 黑方的第一枚棋子可下在棋盤任意交叉點上。
- 輪流下子是雙方的權(quán)利,但允許任何一方放棄下子權(quán),先形成5子連線者獲勝。
功能截圖
服務(wù)端啟動
客戶端1啟動
客戶端2啟動
對戰(zhàn)效果
代碼實現(xiàn)
服務(wù)端啟動類
public class ServerRunner extends Frame implements ActionListener { JButton clearMsgButton = new JButton("清空"); JButton serverStatusButton = new JButton("狀態(tài)"); JButton closeServerButton = new JButton("關(guān)閉"); Panel buttonPanel = new Panel(); ServerMsgPanel serverMsgPanel = new ServerMsgPanel(); ServerSocket serverSocket; int clientAccessNumber = 1; /** * 將客戶端套接口和輸出流綁定 */ Hashtable clientDataHash = new Hashtable(50); /** * 將客戶端套接口和客戶名綁定 */ Hashtable clientNameHash = new Hashtable(50); /** * 將游戲創(chuàng)建者和游戲加入者綁定 */ Hashtable chessPeerHash = new Hashtable(50); public ServerRunner() { super("網(wǎng)絡(luò)游戲?qū)?zhàn)平臺服務(wù)器控制平臺"); setBackground(Color.PINK); buttonPanel.setLayout(new FlowLayout()); clearMsgButton.setSize(50, 30); buttonPanel.add(clearMsgButton); clearMsgButton.addActionListener(this); serverStatusButton.setSize(50, 30); buttonPanel.add(serverStatusButton); serverStatusButton.addActionListener(this); closeServerButton.setSize(50, 30); buttonPanel.add(closeServerButton); closeServerButton.addActionListener(this); add(serverMsgPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); pack(); setVisible(true); setSize(600, 440); setResizable(false); validate(); try { createServer(1234, serverMsgPanel); } catch (Exception e) { e.printStackTrace(); } } /** * 用指定端口和面板創(chuàng)建服務(wù)器 * @param port * @param serverMsgPanel * @throws IOException */ public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException { // 客戶端套接口 Socket clientSocket; // 設(shè)定當(dāng)前主機 this.serverMsgPanel = serverMsgPanel; try { serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText("服務(wù)器啟動:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n"); while (true) { // 監(jiān)聽客戶端套接口的信息 clientSocket = serverSocket.accept(); serverMsgPanel.msgTextArea.append("已連接用戶:" + "毅慎" + clientAccessNumber +"\n" + clientSocket + "\n"); // 建立客戶端輸出流 DataOutputStream outputData = new DataOutputStream(clientSocket.getOutputStream()); // 將客戶端套接口和輸出流綁定 clientDataHash.put(clientSocket, outputData); // 將客戶端套接口和客戶名綁定 clientNameHash.put(clientSocket, ("毅慎" + clientAccessNumber++)); // 創(chuàng)建并運行服務(wù)器端線程 ServerThread thread = new ServerThread(clientSocket, clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel); thread.start(); } } catch (IOException ex) { ex.printStackTrace(); } } @Override public void actionPerformed(ActionEvent e) { // 清空服務(wù)器信息 if (e.getSource() == clearMsgButton) { serverMsgPanel.msgTextArea.setText(""); } // 顯示服務(wù)器信息 if (e.getSource() == serverStatusButton) { try { serverMsgPanel.msgTextArea.append("用戶信息:" + "毅慎" + (clientAccessNumber - 1) + "\n服務(wù)器信息:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n"); } catch (Exception ee) { ee.printStackTrace(); } } } public static void main(String[] args) { new ServerRunner(); } }
客戶端啟動類
/** * @Author: Mr_OO * @Date: 2019/12/22 9:05 * 客戶端 */ public class ClientChess extends Frame implements ActionListener, KeyListener { /** * 客戶端套接口 */ public Socket clientSocket; /** * 數(shù)據(jù)輸入流 */ public DataInputStream inputStream; /** * 數(shù)據(jù)輸出流 */ public DataOutputStream outputStream; /** * 用戶名 */ public String chessClientName = null; /** * 主機地址 */ public String host = null; /** * 主機端口 */ public int port = 1234; /** * 是否在聊天 */ public boolean isOnChat = false; /** * 是否在下棋 */ public boolean isOnChess = false; /** * 游戲是否進行中 */ public boolean isGameConnected = false; /** * 是否為游戲創(chuàng)建者 */ public boolean isCreator = false; /** * 是否為游戲加入者 */ public boolean isParticipant = false; /** * 用戶列表區(qū) */ public UserList userListPad = new UserList(); /** * 用戶聊天區(qū) */ protected UserChat userChatPad = new UserChat(); /** * 用戶操作區(qū) */ public UserController userControlPad = new UserController(); /** * 用戶輸入?yún)^(qū) */ protected UserInput userInputPad = new UserInput(); /** * 下棋區(qū) */ ChessBoard chessBoard = new ChessBoard(); /** * 面板區(qū) */ private Panel southPanel = new Panel(); private Panel centerPanel = new Panel(); private Panel eastPanel = new Panel(); /** * 構(gòu)造方法,創(chuàng)建界面 */ public ClientChess() { super("五子棋客戶端"); setLayout(new BorderLayout()); host = userControlPad.ipInputted.getText(); eastPanel.setLayout(new BorderLayout()); eastPanel.add(userListPad, BorderLayout.NORTH); eastPanel.add(userChatPad, BorderLayout.CENTER); eastPanel.setBackground(new Color(238, 154, 73)); userInputPad.contentInputted.addKeyListener(this); chessBoard.host = (userControlPad.ipInputted.getText()); centerPanel.add(chessBoard, BorderLayout.CENTER); centerPanel.add(userInputPad, BorderLayout.SOUTH); centerPanel.setBackground(new Color(238, 154, 73)); 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(PINK); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // 聊天中 if (isOnChat) { // 關(guān)閉客戶端套接口 try { clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // 下棋中 try { // 關(guān)閉下棋端口 chessBoard.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } }); add(eastPanel, BorderLayout.EAST); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); pack(); setSize(1000, 700); setVisible(true); setResizable(false); this.validate(); } /** * 按指定的IP地址和端口連接到服務(wù)器 * @param serverIP * @param serverPort * @return * @throws Exception */ public boolean connectToServer(String serverIP, int serverPort) throws Exception { try { // 創(chuàng)建客戶端套接口 clientSocket = new Socket(serverIP, serverPort); // 創(chuàng)建輸入流 inputStream = new DataInputStream(clientSocket.getInputStream()); // 創(chuàng)建輸出流 outputStream = new DataOutputStream(clientSocket.getOutputStream()); // 創(chuàng)建客戶端線程 ClientThread clientThread = new ClientThread(this); // 啟動線程,等待聊天信息 clientThread.start(); isOnChat = true; return true; } catch (IOException ex) { userChatPad.chatTextArea.setText("Sorry,無法連接!!!\n"); } return false; } /** * 客戶端事件處理 * @param e */ @Override public void actionPerformed(ActionEvent e) { // 連接到主機按鈕單擊事件 if (e.getSource() == userControlPad.connectButton) { // 取得主機地址 host = chessBoard.host = userControlPad.ipInputted.getText(); try { // 成功連接到主機時,設(shè)置客戶端相應(yīng)的界面狀態(tài) if (connectToServer(host, port)) { userChatPad.chatTextArea.setText(""); userControlPad.connectButton.setEnabled(false); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); chessBoard.statusText.setText("連接成功,請等待!!!"); } } catch (Exception ei) { userChatPad.chatTextArea.setText("Sorry,不能連接!!!\n"); } } // 離開游戲按鈕單擊事件 if (e.getSource() == userControlPad.exitButton) { // 若用戶處于聊天狀態(tài)中 if (isOnChat) { try { // 關(guān)閉客戶端套接口 clientSocket.close(); } catch (Exception ed){} } // 若用戶處于游戲狀態(tài)中 if (isOnChess || isGameConnected) { try { // 關(guān)閉游戲端口 chessBoard.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } // 加入游戲按鈕單擊事件 if (e.getSource() == userControlPad.joinButton) { // 取得要加入的游戲 String selectedUser = userListPad.userList.getSelectedItem(); // 若未選中要加入的用戶,或選中的用戶已經(jīng)在游戲,則給出提示信息 if (selectedUser == null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) { chessBoard.statusText.setText("必須選擇一個用戶!"); } else { // 執(zhí)行加入游戲的操作 try { // 若游戲套接口未連接 if (!isGameConnected) { // 若連接到主機成功 if (chessBoard.connectServer(chessBoard.host, chessBoard.port)) { isGameConnected = true; isOnChess = true; isParticipant = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); chessBoard.chessThread.sendMessage("/joingame " + userListPad.userList.getSelectedItem() + " " + chessClientName); } } else { // 若游戲端口連接中 isOnChess = true; isParticipant = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); chessBoard.chessThread.sendMessage("/joingame " + 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); } } } // 創(chuàng)建游戲按鈕單擊事件 if (e.getSource() == userControlPad.createButton) { try { // 若游戲端口未連接 if (!isGameConnected) { if (chessBoard.connectServer(chessBoard.host, chessBoard.port)) { // 若連接到主機成功 isGameConnected = true; isOnChess = true; isCreator = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); chessBoard.chessThread.sendMessage("/creatgame " + "[inchess]" + chessClientName); } } else { // 若游戲端口連接中 isOnChess = true; isCreator = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); chessBoard.chessThread.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("Sorry,不能連接: \n" + ec); } } // 退出游戲按鈕單擊事件 if (e.getSource() == userControlPad.cancelButton) { // 游戲中 if (isOnChess) { chessBoard.chessThread.sendMessage("/giveup " + chessClientName); chessBoard.setVicStatus(-1 * chessBoard.chessColor); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); chessBoard.statusText.setText("請選擇創(chuàng)建房間或加入游戲!!!"); } if (!isOnChess) { // 非游戲中 userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); chessBoard.statusText.setText("請選擇創(chuàng)建房間或加入游戲!!!"); } isParticipant = isCreator = false; } } @Override public void keyPressed(KeyEvent e) { TextField inputwords = (TextField) e.getSource(); // 處理回車按鍵事件 if (e.getKeyCode() == KeyEvent.VK_ENTER) { // 給所有人發(fā)信息 if (userInputPad.userChoice.getSelectedItem().equals("所有用戶")) { try { // 發(fā)送信息 outputStream.writeUTF(inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea.setText("Sorry,不能連接到服務(wù)器!\n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } else { // 給指定人發(fā)信息 try { outputStream.writeUTF("/" + userInputPad.userChoice.getSelectedItem() + " " + inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea.setText("Sorry,不能連接到服務(wù)器!\n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } } } @Override public void keyTyped(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) {} public static void main(String[] args) { new ClientChess(); } }
棋盤五子棋核心算法類
public class ChessBoard extends Panel implements MouseListener, ActionListener { public int dis = 30; // 鼠標(biāo)是否能使用 public boolean isMouseEnabled = false; // 是否勝利 public boolean isWon = false; // 棋子的x軸坐標(biāo)位 public int chessX_POS = -1; // 棋子的y軸坐標(biāo)位 public int chessY_POS = -1; // 棋子的顏色 public int chessColor = 1; // 黑棋x軸坐標(biāo)位數(shù)組 public int chessBlack_XPOS[] = new int[200]; // 黑棋y軸坐標(biāo)位數(shù)組 public int chessBlack_YPOS[] = new int[200]; // 白棋x軸坐標(biāo)位數(shù)組 public int chessWhite_XPOS[] = new int[200]; // 白棋y軸坐標(biāo)位數(shù)組 public int chessWhite_YPOS[] = new int[200]; // 黑棋數(shù)量 public int chessBlackCount = 0; // 白棋數(shù)量 public int chessWhiteCount = 0; // 黑棋獲勝次數(shù) public int chessBlackVicTimes = 0; // 白棋獲勝次數(shù) public int chessWhiteVicTimes = 0; // 套接口 public Socket chessSocket; protected DataInputStream inputData; protected DataOutputStream outputData; public String chessSelfName = null; public String chessPeerName = null; public String host = null; public int port = 1234; public TextField statusText = new TextField("請先連接服務(wù)器?。?!"); public ChessThread chessThread = new ChessThread(this); public ChessBoard() { setSize(600, 600); setLayout(null); setBackground(new Color(205, 133, 63)); addMouseListener(this); add(statusText); statusText.setBounds(new Rectangle(80, 5, 440, 24)); statusText.setEditable(false); } /** * 連接到主機 * @param ServerIP * @param ServerPort * @return * @throws Exception */ 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()); chessThread.start(); return true; } catch (IOException ex) { statusText.setText("sorry,連接失敗!!! \n"); } return false; } /** * 設(shè)定勝利時的棋盤狀態(tài) * @param vicChessColor */ public void setVicStatus(int vicChessColor) { // 清空棋盤 this.removeAll(); // 將黑棋的位置設(shè)置到零點 for (int i = 0; i <= chessBlackCount; i++) { chessBlack_XPOS[i] = 0; chessBlack_YPOS[i] = 0; } // 將白棋的位置設(shè)置到零點 for (int i = 0; i <= chessWhiteCount; i++) { chessWhite_XPOS[i] = 0; chessWhite_YPOS[i] = 0; } // 清空棋盤上的黑棋數(shù) chessBlackCount = 0; // 清空棋盤上的白棋數(shù) chessWhiteCount = 0; add(statusText); statusText.setBounds(40, 5, 200, 24); // 黑棋勝 if (vicChessColor == 1) { chessBlackVicTimes++; statusText.setText("恭喜黑方勝!??!黑VS白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes + ".游戲重啟,等待白方..."); // 白棋勝 } else if (vicChessColor == -1) { chessWhiteVicTimes++; statusText.setText("恭喜白方勝?。?!黑VS白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes + ".游戲重啟,等待黑方..."); } } /** * 取得指定棋子的位置 * @param xPos * @param yPos * @param chessColor */ public void setLocation(int xPos, int yPos, int chessColor) { // 棋子為黑棋時 if (chessColor == 1) { chessBlack_XPOS[chessBlackCount] = xPos * dis; chessBlack_YPOS[chessBlackCount] = yPos * dis; chessBlackCount++; // 棋子為白棋時 } else if (chessColor == -1) { chessWhite_XPOS[chessWhiteCount] = xPos * dis; chessWhite_YPOS[chessWhiteCount] = yPos * dis; chessWhiteCount++; } } /** * 五子棋核心算法 * @param xPos * @param yPos * @param chessColor * @return */ public boolean checkVicStatus(int xPos, int yPos, int chessColor) { // 連接棋子數(shù) int chessLinkedCount = 1; // 用于比較是否要繼續(xù)遍歷一個棋子的相鄰網(wǎng)格 int chessLinkedCompare = 1; // 要比較的棋子在數(shù)組中的索引位置 int chessToCompareIndex = 0; // 相鄰網(wǎng)格的位置 int closeGrid = 1; // 黑棋時 if (chessColor == 1) { // 將該棋子自身算入的話,初始連接數(shù)為1 chessLinkedCount = 1; //以下每對for循環(huán)語句為一組,因為下棋的位置能位于中間而非兩端 // 遍歷相鄰4個網(wǎng)格 // 判斷當(dāng)前下的棋子的右邊4個棋子是否都為黑棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { // 遍歷棋盤上所有黑棋子 for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos * dis) == chessBlack_YPOS[chessToCompareIndex])) { // 連接數(shù)加1 chessLinkedCount = chessLinkedCount + 1; // 五子相連時,勝利 if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; // 若中間有一個棋子非黑棋,則會進入此分支,此時無需再遍歷 } else { break; } } // 判斷當(dāng)前下的棋子的左邊4個棋子是否都為黑棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && (yPos * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 進入新的一組for循環(huán)時要將連接數(shù)等重置 chessLinkedCount = 1; chessLinkedCompare = 1; // 判斷當(dāng)前下的棋子的上邊4個棋子是否都為黑棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 判斷當(dāng)前下的棋子的下邊4個棋子是否都為黑棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { 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++) { // 判斷當(dāng)前下的棋子的左上方向4個棋子是否都為黑棋 if (((xPos - closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { 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++) { // 判斷當(dāng)前下的棋子的右下方向4個棋子是否都為黑棋 if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; // 判斷當(dāng)前下的棋子的右上方向4個棋子是否都為黑棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 判斷當(dāng)前下的棋子的左下方向4個棋子是否都為黑棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 白棋的情況 } else if (chessColor == -1) { chessLinkedCount = 1; // 判斷當(dāng)前下的棋子的右邊4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && (yPos * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 判斷當(dāng)前下的棋子的左邊4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && (yPos * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; // 判斷當(dāng)前下的棋子的上邊4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 判斷當(dāng)前下的棋子的下邊4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; // 判斷當(dāng)前下的棋子的左上方向4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 判斷當(dāng)前下的棋子的右下方向4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; // 判斷當(dāng)前下的棋子的右上方向4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // 判斷當(dāng)前下的棋子的左下方向4個棋子是否都為白棋 for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5) { return (true); } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } } return false; } /** * 畫棋盤 */ @Override public void paint(Graphics g) { for (int i = 40; i <= 580; i = i + 30) { g.drawLine(40, i, 580, i); } for (int j = 40; j <= 580; j = j + 30) { g.drawLine(j, 40, j, 580); } g.fillOval(127, 127, 8, 8); g.fillOval(487, 127, 8, 8); g.fillOval(127, 487, 8, 8); g.fillOval(487, 487, 8, 8); g.fillOval(307, 307, 8, 8); } /** * 畫棋子 * @param xPos * @param yPos * @param chessColor */ public void paintChessPoint(int xPos, int yPos, int chessColor) { ChessBlack chessBlack = new ChessBlack(this); ChessWhite chessWhite = new ChessWhite(this); // 黑棋 if (chessColor == 1 && isMouseEnabled) { // 設(shè)置棋子的位置 setLocation(xPos, yPos, chessColor); // 取得當(dāng)前局面狀態(tài) isWon = checkVicStatus(xPos, yPos, chessColor); // 非勝利狀態(tài) if (isWon == false) { chessThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); // 將棋子添加到棋盤中 this.add(chessBlack); // 設(shè)置棋子邊界 chessBlack.setBounds(xPos * dis -4, yPos * dis -3, 30, 30); statusText.setText("黑(第" + chessBlackCount + "步)" + xPos + " " + yPos + ",輪到白方."); // 將鼠標(biāo)設(shè)為不可用 isMouseEnabled = false; // 勝利狀態(tài) } else { chessThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(chessBlack); chessBlack.setBounds(xPos * dis -4, yPos * dis -3, 30, 30); // 調(diào)用勝利方法,傳入?yún)?shù)為黑棋勝利 setVicStatus(1); isMouseEnabled = false; } // 白棋 } else if (chessColor == -1 && isMouseEnabled) { setLocation(xPos, yPos, chessColor); isWon = checkVicStatus(xPos, yPos, chessColor); if (isWon == false) { chessThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(chessWhite); chessWhite.setBounds(xPos * dis -4, yPos * dis-3 , 30, 30); statusText.setText("白(第" + chessWhiteCount + "步)" + xPos + " " + yPos + ",輪到黑方."); isMouseEnabled = false; } else { chessThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(chessWhite); chessWhite.setBounds(xPos * dis-4 , yPos * dis -3, 30, 30); // 調(diào)用勝利方法,傳入?yún)?shù)為白棋 setVicStatus(-1); isMouseEnabled = false; } } } /** * 畫網(wǎng)絡(luò)棋盤 * @param xPos * @param yPos * @param chessColor */ public void paintNetChessPoint(int xPos, int yPos, int chessColor) { ChessBlack chessBlack = new ChessBlack(this); ChessWhite chessWhite = new ChessWhite(this); setLocation(xPos, yPos, chessColor); if (chessColor == 1) { isWon = checkVicStatus(xPos, yPos, chessColor); if (isWon == false) { this.add(chessBlack); chessBlack.setBounds(xPos * dis-4 , yPos * dis -3, 30, 30); statusText.setText("黑(第" + chessBlackCount + "步)" + xPos + " " + yPos + ",輪到白方."); isMouseEnabled = true; } else { chessThread.sendMessage("/" + chessPeerName + " /victory " + chessColor); this.add(chessBlack); chessBlack.setBounds(xPos * dis -4, yPos * dis-3, 30, 30); setVicStatus(1); isMouseEnabled = true; } } else if (chessColor == -1) { isWon = checkVicStatus(xPos, yPos, chessColor); if (isWon == false) { this.add(chessWhite); chessWhite.setBounds(xPos * dis-4, yPos * dis-3, 30, 30); statusText.setText("白(第" + chessWhiteCount + "步)" + xPos + " " + yPos + ",輪到黑方."); isMouseEnabled = true; } else { chessThread.sendMessage("/" + chessPeerName + " /victory " + chessColor); this.add(chessWhite); chessWhite.setBounds(xPos * dis-4, yPos * dis-3, 30, 30); setVicStatus(-1); isMouseEnabled = true; } } } /** * 捕獲下棋事件 * @param e */ @Override public void mousePressed(MouseEvent e) { if (e.getModifiers() == InputEvent.BUTTON1_MASK) { chessX_POS = e.getX(); System.out.println(chessX_POS); chessY_POS = e.getY(); System.out.println(chessY_POS); int a = (chessX_POS) / dis, b = (chessY_POS) / dis; System.out.println("a="+a); System.out.println("b="+b); // 下棋位置不正確時,不執(zhí)行任何操作 if (chessX_POS / dis < 2 || chessY_POS / dis < 2 || chessX_POS / dis > 19 || chessY_POS / dis > 19) { } else { // 畫棋子 paintChessPoint(a, b, chessColor); } } } @Override public void actionPerformed(ActionEvent e) {} @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} }
總結(jié)
通過此次的《五子棋》游戲?qū)崿F(xiàn),讓我對swing的相關(guān)知識有了進一步的了解,對java這門語言也有了比以前更深刻的認識。
java的一些基本語法,比如數(shù)據(jù)類型、運算符、程序流程控制和數(shù)組等,理解更加透徹。java最核心的核心就是面向?qū)ο笏枷?,對于這一個概念,終于悟到了一些。
以上就是Java+Swing實現(xiàn)經(jīng)典五子棋游戲的詳細內(nèi)容,更多關(guān)于Java Swing五子棋的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringBoot定時任務(wù)多線程實現(xiàn)示例
在真實的Java開發(fā)環(huán)境中,我們經(jīng)常會需要用到定時任務(wù)來幫助我們完成一些特殊的任務(wù),本文主要介紹了SpringBoot定時任務(wù)多線程實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12Java在ElasticSearch中使用LocalDatetime類型
最近在開發(fā)一個搜索功能的需求的時候,遇到了LocalDatetime類型不能保存到ElasticSearch中的問題,這篇文章主要介紹了Java在ElasticSearch中使用LocalDatetime類型2023-10-10SpringBoot中@ConditionalOnProperty注解的使用方法詳解
這篇文章主要介紹了SpringBoot中@ConditionalOnProperty注解的使用方法詳解,在開發(fā)基于SpringBoot框架的項目時,會用到下面的條件注解,有時會有需要控制配置類是否生效或注入到Spring上下文中的場景,可以使用@ConditionalOnProperty注解來控制,需要的朋友可以參考下2024-01-01