“This is the fourth day of my participation in the First Challenge 2022. For details: First Challenge 2022”
❤️ Author’s home page: Xiao Xu Zhu
❤️ About the author: Hello everyone, I am Xiao Xu Zhu. Java field quality creator 🏆, CSDN blog expert 🏆, Huawei cloud enjoy expert 🏆, Nuggets of the year popular author 🏆, Ali Cloud expert blogger 🏆
❤️ technology live, the appreciation
❤️ like 👍 collect ⭐ look again, form a habit
preface
Gobang is one of the world Intelligence Games, which is a pure strategy board game played by two people. It is one of the world Intelligence Games. Usually, the two sides use black and white pieces respectively, placed on the intersection of straight and horizontal lines of the board.
Chess set and weiqi universal, originated in ancient China, one of the traditional black and white chess. It is mainly popular in the countries of Chinese and Chinese culture circle as well as some areas of Europe and America. It is the oldest chess game in the world.
Easy to use, suitable for all ages, and fun, engaging; Not only can enhance thinking ability, improve intelligence, and rich in philosophy, conducive to moral cultivation.
Using Java language, using Swing technology for interface processing, design ideas with object-oriented thought.
The main requirements
1. Each side holds a chess piece of the same color.
2. Empty board opening.
Black first, white, alternate down time, each time only a son.
4, the chess piece is placed on the blank point of the board. After the chess piece is made up, it shall not move to other points, nor be removed from the board or picked up and dropped elsewhere.
5. The first black piece can be placed at any intersection on the board.
It is the right of both parties to take turns, but either party is allowed to give up the right, and the one who forms the first 5 sub-links wins.
The main design
1, because it is a two-person game, non-stand-alone version, so there are multiple clients to communicate with each other, then need to use socket technology
2, design the socket server, used to maintain the socket client connection
3, design socket client, used to achieve the logic and effect of backgammon
4. The client must be able to set the IP address for connecting to the server
5. After client 1 creates the game, client 2 can choose client 1 to play online
6. Rules of the game:
- Each side holds a piece of the same color.
- Empty checkerboard opening.
- Black first, after the white, alternating down, each time can only be a son.
- A piece is placed on a blank spot on the board. After a piece is made up, it may not move to any other point or be removed from the board or picked up for another place.
- The first piece of black can be placed at any intersection of the board.
- It is the right of both parties to take turns, but either party is allowed to give up the right, and the first one to form a five-piece tie wins.
Screenshot function
Server startup
Client 1 starts
Client 2 starts
Against the effect
Code implementation
The server startup class
public class ServerRunner extends Frame implements ActionListener {
JButton clearMsgButton = new JButton("Empty");
JButton serverStatusButton = new JButton("State");
JButton closeServerButton = new JButton("Closed");
Panel buttonPanel = new Panel();
ServerMsgPanel serverMsgPanel = new ServerMsgPanel();
ServerSocket serverSocket;
int clientAccessNumber = 1;
/* bind the client socket to the output stream */
Hashtable clientDataHash = new Hashtable(50);
/** * bind the client socket to the client name */
Hashtable clientNameHash = new Hashtable(50);
/** * Bind game creator and game participant */
Hashtable chessPeerHash = new Hashtable(50);
public ServerRunner(a) {
super("Online game fighting platform server control platform");
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(); }}/** * Create server * with the specified port and panel@param port
* @param serverMsgPanel
* @throws IOException
*/
public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException {
// Client socket
Socket clientSocket;
// Set the current host
this.serverMsgPanel = serverMsgPanel;
try {
serverSocket = new ServerSocket(port);
serverMsgPanel.msgTextArea.setText("Server startup :"
+ InetAddress.getLocalHost() + ":"
+ serverSocket.getLocalPort() + "\n");
while (true) {
// Listen for information on the client socket
clientSocket = serverSocket.accept();
serverMsgPanel.msgTextArea.append("Connected User :" +
"YiShen" + clientAccessNumber +"\n" + clientSocket + "\n");
// Set up the client output stream
DataOutputStream outputData = new DataOutputStream(clientSocket.getOutputStream());
// Bind the client socket to the output stream
clientDataHash.put(clientSocket, outputData);
// Bind the client socket to the client name
clientNameHash.put(clientSocket, ("YiShen" + clientAccessNumber++));
// Create and run a server-side thread
ServerThread thread = newServerThread(clientSocket, clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel); thread.start(); }}catch(IOException ex) { ex.printStackTrace(); }}@Override
public void actionPerformed(ActionEvent e) {
// Clear the server information
if (e.getSource() == clearMsgButton) {
serverMsgPanel.msgTextArea.setText("");
}
// Displays server information
if (e.getSource() == serverStatusButton) {
try {
serverMsgPanel.msgTextArea.append("User Information:" + "YiShen"
+ (clientAccessNumber - 1) + "\n Server information :"
+ InetAddress.getLocalHost() + ":"
+ serverSocket.getLocalPort() + "\n");
} catch(Exception ee) { ee.printStackTrace(); }}}public static void main(String[] args) {
newServerRunner(); }}Copy the code
Client startup class
/ * * *@Author: Mr_OO
* @Date: 2019/12/22 9:05 * Client */
public class ClientChess extends Frame implements ActionListener.KeyListener {
/** * client socket */
public Socket clientSocket;
/** * Data input stream */
public DataInputStream inputStream;
/** * Data output stream */
public DataOutputStream outputStream;
/** * User name */
public String chessClientName = null;
/** * Host address */
public String host = null;
/** * Host port */
public int port = 1234;
/**
* 是否在聊天
*/
public boolean isOnChat = false;
/** * is playing chess */
public boolean isOnChess = false;
/** * Whether the game is in progress */
public boolean isGameConnected = false;
/** * Is the game creator */
public boolean isCreator = false;
/** * whether to join the game */
public boolean isParticipant = false;
/** * User list area */
public UserList userListPad = new UserList();
/** * User chat area */
protected UserChat userChatPad = new UserChat();
/** * User operation area */
public UserController userControlPad = new UserController();
/** * User input field */
protected UserInput userInputPad = new UserInput();
/** * chess */
ChessBoard chessBoard = new ChessBoard();
/** * Panel area */
private Panel southPanel = new Panel();
private Panel centerPanel = new Panel();
private Panel eastPanel = new Panel();
/** * create interface */
public ClientChess(a) {
super("Backgammon client");
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) {
/ / chat
if (isOnChat) {
// Close the client socket
try {
clientSocket.close();
}
catch (Exception ed){}
}
if (isOnChess || isGameConnected) {
/ / to play chess
try {
// Close the chess-playing port
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();
}
/** * Connect to the server with the specified IP address and port *@param serverIP
* @param serverPort
* @return
* @throws Exception
*/
public boolean connectToServer(String serverIP, int serverPort) throws Exception {
try {
// Create a client socket
clientSocket = new Socket(serverIP, serverPort);
// Create an input stream
inputStream = new DataInputStream(clientSocket.getInputStream());
// Create an output stream
outputStream = new DataOutputStream(clientSocket.getOutputStream());
// Create a client thread
ClientThread clientThread = new ClientThread(this);
// Start the thread and wait for chat messages
clientThread.start();
isOnChat = true;
return true;
} catch (IOException ex) {
userChatPad.chatTextArea.setText("Sorry, unable to connect!! \n");
}
return false;
}
/** * Client event handling *@param e
*/
@Override
public void actionPerformed(ActionEvent e) {
// Connect to host button click event
if (e.getSource() == userControlPad.connectButton) {
// Get the host address
host = chessBoard.host = userControlPad.ipInputted.getText();
try {
// Set the client interface status when the host is successfully connected
if (connectToServer(host, port)) {
userChatPad.chatTextArea.setText("");
userControlPad.connectButton.setEnabled(false);
userControlPad.createButton.setEnabled(true);
userControlPad.joinButton.setEnabled(true);
chessBoard.statusText.setText("Connection successful. please wait!!"); }}catch (Exception ei) {
userChatPad.chatTextArea.setText("Sorry, cannot connect!! \n"); }}// Leave the game button click event
if (e.getSource() == userControlPad.exitButton) {
// If the user is in chat state
if (isOnChat) {
try {
// Close the client socket
clientSocket.close();
}
catch (Exception ed){}
}
// If the user is in the game state
if (isOnChess || isGameConnected) {
try {
// Close the game port
chessBoard.chessSocket.close();
}
catch (Exception ee){}
}
System.exit(0);
}
// Add the game button click event
if (e.getSource() == userControlPad.joinButton) {
// Get the game to join
String selectedUser = userListPad.userList.getSelectedItem();
// If the user to join is not selected, or the selected user is already in the game, a prompt message will be given
if (selectedUser == null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName)) {
chessBoard.statusText.setText("Must select a user!");
} else {
// Perform the action of joining the game
try {
// If the game socket is not connected
if(! isGameConnected) {// If the connection to the host succeeds
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 {
// If the game port is connected
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("Cannot connect: \n"+ ee); }}}// Create the game button click event
if (e.getSource() == userControlPad.createButton) {
try {
// If the game port is disconnected
if(! isGameConnected) {if (chessBoard.connectServer(chessBoard.host, chessBoard.port)) {
// If the connection to the host succeeds
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 {
// If the game port is connected
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, can't connect: \n"+ ec); }}// Exit the game button click event
if (e.getSource() == userControlPad.cancelButton) {
/ / in the game
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("Please select create room or join the game!!");
} if(! isOnChess) {// Not in the game
userControlPad.createButton.setEnabled(true);
userControlPad.joinButton.setEnabled(true);
userControlPad.cancelButton.setEnabled(false);
chessBoard.statusText.setText("Please select create room or join the game!!");
}
isParticipant = isCreator = false; }}@Override
public void keyPressed(KeyEvent e) {
TextField inputwords = (TextField) e.getSource();
// Handle the return key event
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
// Send a message to everyone
if (userInputPad.userChoice.getSelectedItem().equals("All Users")) {
try {
// Send a message
outputStream.writeUTF(inputwords.getText());
inputwords.setText("");
} catch (Exception ea) {
userChatPad.chatTextArea.setText("Sorry, cannot connect to server! \n");
userListPad.userList.removeAll();
userInputPad.userChoice.removeAll();
inputwords.setText("");
userControlPad.connectButton.setEnabled(true); }}else {
// Send a message to the designated person
try {
outputStream.writeUTF("/" + userInputPad.userChoice.getSelectedItem()
+ "" + inputwords.getText());
inputwords.setText("");
} catch (Exception ea) {
userChatPad.chatTextArea.setText("Sorry, cannot connect to server! \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) {
newClientChess(); }}Copy the code
Chessboard gobang core algorithm class
public class ChessBoard extends Panel implements MouseListener.ActionListener {
public int dis = 30;
// Whether the mouse works
public boolean isMouseEnabled = false;
// Whether to win
public boolean isWon = false;
// The x-coordinate position of the piece
public int chessX_POS = -1;
// The y position of the chessman
public int chessY_POS = -1;
// The color of the pieces
public int chessColor = 1;
// Black's x-position array
public int chessBlack_XPOS[] = new int[200];
// Black's y-position array
public int chessBlack_YPOS[] = new int[200];
// White's x position array
public int chessWhite_XPOS[] = new int[200];
// White's y-position array
public int chessWhite_YPOS[] = new int[200];
// Number of black moves
public int chessBlackCount = 0;
// The number of white moves
public int chessWhiteCount = 0;
// The number of black wins
public int chessBlackVicTimes = 0;
// White wins
public int chessWhiteVicTimes = 0;
/ / set of interfaces
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("Please connect to server first!!");
public ChessThread chessThread = new ChessThread(this);
public ChessBoard(a) {
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);
}
/** * Connect to host *@param ServerIP
* @param ServerPort
* @return
* @throws Exception
*/
public boolean connectServer(String ServerIP, int ServerPort) throws Exception {
try {
// Get the host port
chessSocket = new Socket(ServerIP, ServerPort);
// get the input stream
inputData = new DataInputStream(chessSocket.getInputStream());
// get the output stream
outputData = new DataOutputStream(chessSocket.getOutputStream());
chessThread.start();
return true;
} catch (IOException ex) {
statusText.setText("Sorry, connection failed!! \n");
}
return false;
}
/** * Sets the board state for victory *@param vicChessColor
*/
public void setVicStatus(int vicChessColor) {
// Clear the board
this.removeAll();
// Set black's position to zero
for (int i = 0; i <= chessBlackCount; i++) {
chessBlack_XPOS[i] = 0;
chessBlack_YPOS[i] = 0;
}
// Sets white's position to zero
for (int i = 0; i <= chessWhiteCount; i++) {
chessWhite_XPOS[i] = 0;
chessWhite_YPOS[i] = 0;
}
// Clear the board of black
chessBlackCount = 0;
// Clear the board of white pieces
chessWhiteCount = 0;
add(statusText);
statusText.setBounds(40.5.200.24);
/ / black
if (vicChessColor == 1) {
chessBlackVicTimes++;
statusText.setText("Congratulations to the Black team!! Black vs. white. "" + chessBlackVicTimes + ":" + chessWhiteVicTimes
+ ".game restart, waiting for white...");
/ / white
} else if (vicChessColor == -1) {
chessWhiteVicTimes++;
statusText.setText("Congratulations Bai Fangsheng!! Black vs. white. "" + chessBlackVicTimes + ":" + chessWhiteVicTimes
+ ".game restart, waiting for black..."); }}/** * get the position of the specified piece *@param xPos
* @param yPos
* @param chessColor
*/
public void setLocation(int xPos, int yPos, int chessColor) {
// When the pieces are black
if (chessColor == 1) {
chessBlack_XPOS[chessBlackCount] = xPos * dis;
chessBlack_YPOS[chessBlackCount] = yPos * dis;
chessBlackCount++;
// When the pieces are white
} else if (chessColor == -1) { chessWhite_XPOS[chessWhiteCount] = xPos * dis; chessWhite_YPOS[chessWhiteCount] = yPos * dis; chessWhiteCount++; }}/** * Gobang core algorithm *@param xPos
* @param yPos
* @param chessColor
* @return* /
public boolean checkVicStatus(int xPos, int yPos, int chessColor) {
// Join the number of pieces
int chessLinkedCount = 1;
// Used to compare whether to continue traversing the adjacent grids of a piece
int chessLinkedCompare = 1;
// The index position of the piece to be compared in the array
int chessToCompareIndex = 0;
// The position of the adjacent grid
int closeGrid = 1;
/ / black
if (chessColor == 1) {
// If the piece itself is counted, the initial number of connections is 1
chessLinkedCount = 1;
// Each pair of the following for loops is a set, because the chess can be played in the middle rather than at both ends
// Iterate over 4 adjacent grids
// Check whether the 4 pieces to the right of the current piece are all black
for (closeGrid = 1; closeGrid <= 4; closeGrid++) {
// Traverses all black pieces on the board
for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) {
if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex])
&& ((yPos * dis) == chessBlack_YPOS[chessToCompareIndex])) {
// The number of connections is increased by 1
chessLinkedCount = chessLinkedCount + 1;
// When the fifth son is connected, victory
if (chessLinkedCount == 5) {
return true; }}}if (chessLinkedCount == (chessLinkedCompare + 1)) {
chessLinkedCompare++;
// If there is a piece in the middle that is not black, it will enter this branch
} else {
break; }}// Check whether the 4 pieces to the left of the current chess piece are all black
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; }}// The connection count is reset when entering a new set of for loops
chessLinkedCount = 1;
chessLinkedCompare = 1;
// Check whether the top 4 pieces are black
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; }}// Check whether the bottom 4 pieces of the current chess are black
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++) {
// Check whether all 4 pieces in the upper left direction of the current chess piece are black
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++) {
// Check whether all 4 pieces in the lower right direction of the current chess piece are black
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;
// Check whether all 4 pieces in the upper right direction of the current chess piece are black
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; }}// Check whether all 4 pieces in the lower left direction of the current chess piece are black
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; }}// The case of white
} else if (chessColor == -1) {
chessLinkedCount = 1;
// Check whether the 4 pieces to the right of the current piece are all white
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; }}// Check whether the 4 pieces to the left of the current chess piece are all white
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;
// Check whether the top 4 pieces of the current game are all white
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; }}// Check whether the bottom 4 pieces of the current chess are all white
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;
// Check whether all 4 pieces in the upper left direction of the current chess piece are white
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; }}// Check whether all 4 pieces in the lower right direction of the current chess piece are white
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;
// Check whether all 4 pieces in the upper right direction of the current chess piece are white
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; }}// Check whether all 4 pieces in the lower left direction of the current chess piece are white
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;
}
/** * draw the checkerboard */
@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);
}
/** * draw a chess piece *@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);
/ / black
if (chessColor == 1 && isMouseEnabled) {
// Set the position of the chess pieces
setLocation(xPos, yPos, chessColor);
// Get the current state of the situation
isWon = checkVicStatus(xPos, yPos, chessColor);
// Non-victory state
if (isWon == false) {
chessThread.sendMessage("/" + chessPeerName + " /chess "
+ xPos + "" + yPos + "" + chessColor);
// Add the pieces to the board
this.add(chessBlack);
// Set the checker boundary
chessBlack.setBounds(xPos * dis -4, yPos * dis -3.30.30);
statusText.setText("Black" + chessBlackCount + ")" + xPos + "" + yPos + "Turn to white.");
// Make the mouse unavailable
isMouseEnabled = false;
// Win state
} else {
chessThread.sendMessage("/" + chessPeerName + " /chess "
+ xPos + "" + yPos + "" + chessColor);
this.add(chessBlack);
chessBlack.setBounds(xPos * dis -4, yPos * dis -3.30.30);
// Call the victory method, passing in the argument black wins
setVicStatus(1);
isMouseEnabled = false;
}
/ / white
} 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("White" + chessWhiteCount + ")" + xPos + "" + yPos + "Black's turn.");
isMouseEnabled = false;
} else {
chessThread.sendMessage("/" + chessPeerName + " /chess "
+ xPos + "" + yPos + "" + chessColor);
this.add(chessWhite);
chessWhite.setBounds(xPos * dis-4 , yPos * dis -3.30.30);
// Call the victory method, passing in white
setVicStatus(-1);
isMouseEnabled = false; }}}/** * draw network checkerboard *@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("Black" + chessBlackCount + ")" + xPos + "" + yPos + "Turn to white.");
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("White" + chessWhiteCount + ")" + xPos + "" + yPos + "Black's turn.");
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; }}}/** * capture chess events *@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);
// No action is performed when the chess position is incorrect
if (chessX_POS / dis < 2 || chessY_POS / dis < 2
|| chessX_POS / dis > 19 || chessY_POS / dis > 19) {}else {
/ / draw piecespaintChessPoint(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) {}}Copy the code
conclusion
Through the “gobang” game implementation, let me have a further understanding of swing related knowledge, the Language of Java has a deeper understanding than before.
Basic Java syntax, such as data types, operators, program flow control, and arrays, is better understood. Java is the core of the core object oriented thought, for this concept, finally realized some.
The source code for
Can pay attention to the blogger, private chat blogger access