JAVA 实现《五子棋》游戏|CSDN创作打卡
前言
五子棋是世界智力運(yùn)動(dòng)會(huì)競(jìng)技項(xiàng)目之一,是一種兩人對(duì)弈的純策略型棋類游戲,是世界智力運(yùn)動(dòng)會(huì)競(jìng)技項(xiàng)目之一,通常雙方分別使用黑白兩色的棋子,下在棋盤直線與橫線的交叉點(diǎn)上,先形成5子連線者獲勝。
棋具與圍棋通用,起源于中國(guó)上古時(shí)代的傳統(tǒng)黑白棋種之一。主要流行于華人和漢字文化圈的國(guó)家以及歐美一些地區(qū),是世界上最古老的棋。
容易上手,老少皆宜,而且趣味橫生,引人入勝;不僅能增強(qiáng)思維能力,提高智力,而且富含哲理,有助于修身養(yǎng)性。
用java語(yǔ)言實(shí)現(xiàn),采用了swing技術(shù)進(jìn)行了界面化處理,設(shè)計(jì)思路用了面向?qū)ο笏枷搿?/p>
主要需求
1、對(duì)局雙方各執(zhí)一色棋子。
2、空棋盤開(kāi)局。
3、黑先、白后,交替下子,每次只能下一子。
4、棋子下在棋盤的空白點(diǎn)上,棋子下定后,不得向其它點(diǎn)移動(dòng),不得從棋盤上拿掉或拿起另落別處。
5、黑方的第一枚棋子可下在棋盤任意交叉點(diǎn)上。
6、輪流下子是雙方的權(quán)利,但允許任何一方放棄下子權(quán),先形成5子連線者獲勝。
主要設(shè)計(jì)
1、由于是兩人的游戲,非單機(jī)版,所以要有多個(gè)客戶端相互通信,這時(shí)就要用到socket 技術(shù)
2、設(shè)計(jì)socket服務(wù)端,用來(lái)維護(hù)socket客戶端連接
3、設(shè)計(jì)socket客戶端,用來(lái)實(shí)現(xiàn)五子棋邏輯和效果
4、客戶端要能設(shè)置連接服務(wù)端的IP,用來(lái)連接服務(wù)端
5、客戶端1創(chuàng)建游戲后,客戶端2可以選擇客戶端1進(jìn)行聯(lián)機(jī)對(duì)戰(zhàn)
6、游戲規(guī)則:
功能截圖
服務(wù)端啟動(dòng)
客戶端1啟動(dòng)
客戶端2啟動(dòng)
對(duì)戰(zhàn)效果
代碼實(shí)現(xiàn)
服務(wù)端啟動(dòng)類
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)平臺(tái)服務(wù)器控制平臺(tái)");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() {@Overridepublic 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)前主機(jī)this.serverMsgPanel = serverMsgPanel;try {serverSocket = new ServerSocket(port);serverMsgPanel.msgTextArea.setText("服務(wù)器啟動(dòng):"+ InetAddress.getLocalHost() + ":"+ serverSocket.getLocalPort() + "\n");while (true) {// 監(jiān)聽(tīng)客戶端套接口的信息 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)建并運(yùn)行服務(wù)器端線程 ServerThread thread = new ServerThread(clientSocket,clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel);thread.start();}} catch (IOException ex) {ex.printStackTrace();}}@Overridepublic 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();}}客戶端啟動(dòng)類
/*** @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;/*** 主機(jī)地址 */public String host = null;/*** 主機(jī)端口*/public int port = 1234;/*** 是否在聊天*/public boolean isOnChat = false;/*** 是否在下棋*/public boolean isOnChess = false;/*** 游戲是否進(jìn)行中*/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() {@Overridepublic 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);// 啟動(dòng)線程,等待聊天信息 clientThread.start();isOnChat = true;return true;} catch (IOException ex) {userChatPad.chatTextArea.setText("Sorry,無(wú)法連接!!!\n");}return false;}/*** 客戶端事件處理* @param e*/@Overridepublic void actionPerformed(ActionEvent e) {// 連接到主機(jī)按鈕單擊事件if (e.getSource() == userControlPad.connectButton) {// 取得主機(jī)地址host = chessBoard.host = userControlPad.ipInputted.getText();try {// 成功連接到主機(jī)時(shí),設(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("連接成功,請(qǐng)等待!!!");}} catch (Exception ei) {userChatPad.chatTextArea.setText("Sorry,不能連接!!!\n");}}// 離開(kāi)游戲按鈕單擊事件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("必須選擇一個(gè)用戶!");} else {// 執(zhí)行加入游戲的操作 try {// 若游戲套接口未連接if (!isGameConnected) {// 若連接到主機(jī)成功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)) {// 若連接到主機(jī)成功 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("請(qǐng)選擇創(chuàng)建房間或加入游戲!!!");} if (!isOnChess) {// 非游戲中 userControlPad.createButton.setEnabled(true);userControlPad.joinButton.setEnabled(true);userControlPad.cancelButton.setEnabled(false);chessBoard.statusText.setText("請(qǐng)選擇創(chuàng)建房間或加入游戲!!!");}isParticipant = isCreator = false;}}@Overridepublic 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);}}}}@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic 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("請(qǐng)先連接服務(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);}/*** 連接到主機(jī)* @param ServerIP* @param ServerPort* @return* @throws Exception*/public boolean connectServer(String ServerIP, int ServerPort) throws Exception {try {// 取得主機(jī)端口 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è)定勝利時(shí)的棋盤狀態(tài)* @param vicChessColor*/public void setVicStatus(int vicChessColor) {// 清空棋盤 this.removeAll();// 將黑棋的位置設(shè)置到零點(diǎn) for (int i = 0; i <= chessBlackCount; i++) {chessBlack_XPOS[i] = 0;chessBlack_YPOS[i] = 0;}// 將白棋的位置設(shè)置到零點(diǎn) 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) {// 棋子為黑棋時(shí)if (chessColor == 1) {chessBlack_XPOS[chessBlackCount] = xPos * dis;chessBlack_YPOS[chessBlackCount] = yPos * dis;chessBlackCount++;// 棋子為白棋時(shí)} 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ù)遍歷一個(gè)棋子的相鄰網(wǎng)格 int chessLinkedCompare = 1;// 要比較的棋子在數(shù)組中的索引位置int chessToCompareIndex = 0;// 相鄰網(wǎng)格的位置int closeGrid = 1;// 黑棋時(shí)if (chessColor == 1) {// 將該棋子自身算入的話,初始連接數(shù)為1chessLinkedCount = 1;//以下每對(duì)for循環(huán)語(yǔ)句為一組,因?yàn)橄缕宓奈恢媚芪挥谥虚g而非兩端// 遍歷相鄰4個(gè)網(wǎng)格// 判斷當(dāng)前下的棋子的右邊4個(gè)棋子是否都為黑棋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;// 五子相連時(shí),勝利 if (chessLinkedCount == 5) {return true;}}}if (chessLinkedCount == (chessLinkedCompare + 1)) {chessLinkedCompare++;// 若中間有一個(gè)棋子非黑棋,則會(huì)進(jìn)入此分支,此時(shí)無(wú)需再遍歷} else {break;}}// 判斷當(dāng)前下的棋子的左邊4個(gè)棋子是否都為黑棋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;}}// 進(jìn)入新的一組for循環(huán)時(shí)要將連接數(shù)等重置 chessLinkedCount = 1;chessLinkedCompare = 1;// 判斷當(dāng)前下的棋子的上邊4個(gè)棋子是否都為黑棋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個(gè)棋子是否都為黑棋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個(gè)棋子是否都為黑棋 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個(gè)棋子是否都為黑棋 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個(gè)棋子是否都為黑棋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個(gè)棋子是否都為黑棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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個(gè)棋子是否都為白棋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;}/*** 畫(huà)棋盤*/@Overridepublic 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);}/*** 畫(huà)棋子 * @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;}}}/*** 畫(huà)網(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*/@Overridepublic 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);// 下棋位置不正確時(shí),不執(zhí)行任何操作 if (chessX_POS / dis < 2 || chessY_POS / dis < 2|| chessX_POS / dis > 19 || chessY_POS / dis > 19) {} else {// 畫(huà)棋子paintChessPoint(a, b, chessColor);}}}@Overridepublic void actionPerformed(ActionEvent e) {}@Overridepublic void mouseClicked(MouseEvent e) {}@Overridepublic void mouseReleased(MouseEvent e) {}@Overridepublic void mouseEntered(MouseEvent e) {}@Overridepublic void mouseExited(MouseEvent e) {} }總結(jié)
通過(guò)此次的《五子棋》游戲?qū)崿F(xiàn),讓我對(duì)swing的相關(guān)知識(shí)有了進(jìn)一步的了解,對(duì)java這門語(yǔ)言也有了比以前更深刻的認(rèn)識(shí)。
java的一些基本語(yǔ)法,比如數(shù)據(jù)類型、運(yùn)算符、程序流程控制和數(shù)組等,理解更加透徹。java最核心的核心就是面向?qū)ο笏枷?#xff0c;對(duì)于這一個(gè)概念,終于悟到了一些。
源碼獲取
源碼下載地址:傳送門------->
可關(guān)注博主后,私聊博主免費(fèi)獲取
需要技術(shù)指導(dǎo),寫項(xiàng)目程序,等更多服務(wù)請(qǐng)聯(lián)系博主
今天是持續(xù)寫作的第 3 / 100 天。
可以關(guān)注我,點(diǎn)贊我、評(píng)論我、收藏我啦。
總結(jié)
以上是生活随笔為你收集整理的JAVA 实现《五子棋》游戏|CSDN创作打卡的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: centos 软件安装的几种方式及安装包
- 下一篇: Ansible篇-CentOS7安装AW