“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Let me go through the process of registering, logging in, and playing a demo. (Originally, I wanted to record a GIF, but it was too big, hundreds of megabytes, so I wanted to record a video, but the Nuggets haven’t developed the ability to do that yet, so I uploaded it to Bilibili.) The code is available at the end of this article

www.bilibili.com/video/BV1hU…

This is also a little big, more than 40 megabits, can be loaded out

🎯 1. User registration class

The class name is register.java

So here we’re using the JFrame window. A JFrame is a component that can be displayed on its own. A window usually contains a title, an icon, action buttons (close, minimize, maximize), and the ability to add a menu bar, toolbar, and so on to the window. Multiple Windows can be created in a process and can be displayed, hidden, or destroyed when appropriate.

The main code for the class that controls user registration

Just put the main code here, otherwise it’s too long to read

public class Register extends JFrame{

/* * User registration */
final JLabel welcomeRegisterLabel = new JLabel("Welcome to register happy Gobang!");
final JLabel userLabel = new JLabel("Username:");
final JTextField userjt = new JTextField(14);
final JLabel passwordLabel = new JLabel(Password:);
final JPasswordField passwordjp = new JPasswordField(14);
final JLabel confirmPasswordLabel = new JLabel(Confirm password:);
final JPasswordField confirmPasswordjp = new JPasswordField(14);
final JLabel yanzhengmajl = new JLabel("Verification code:");
final JTextField yanzhengmajt = new JTextField("Please enter the verification code.".7);
final JLabel yanzhengmaUpdate = new JLabel("Can't see? In a");
final JButton register = new JButton("-");
final JLabel back = new JLabel("Return");
final JLabel tipUserAlreadyRegistered = new JLabel("The account has been registered!");
final JLabel tipUserNameEmpty = new JLabel("User name empty!");
final JLabel tipUserNameLessThan5Char = new JLabel("Account number less than 5 characters!");
final JLabel tipPasswordEmpty = new JLabel("The password cannot be empty!");
final JLabel tipPasswordLessThan6Char = new JLabel("Password less than 6 characters!");
final JLabel tipPasswordInconfirmity = new JLabel("Two passwords inconsistent!");
final JLabel tipConfirmPasswordqualified = new JLabel("Repeat the password correctly!");
final JLabel tipyanzhengmaerror = new JLabel("Incorrect verification code input!");
final DrawYZM drawyzm = new DrawYZM();
final Random r = new Random();
static String userName = new String();
static String password = new String();
final FileOperation read = new FileOperation();
String repeatPassword = new String();
String yanzhengma = new String();
String yzm = new String();
int flagUserName = 0;
int flagPassword = 0;
int flagConfirmedPassword = 0;
int flagyanzhengma = 0;
char[] YZM = new char[62]; {for(int i = 0; i < 26; i++) {
                YZM[i] = (char) ('A' + i);
        }
        for(int i = 26; i< 52; i++) {
                YZM[i] = (char) ('a' + i - 26);
        }
        for(char i = 52; i < 62; i++) {
                YZM[i] = (char) (i - 4);
        }
}
SpringLayout springLayout = new SpringLayout();// Use the spring layout manager


}
Copy the code

Verification code class required for registration

class DrawYZM extends JPanel{
        /* * Verify code class */
        public void paint(Graphics g) {
                setBounds(269.269.100.60);
                int R = r.nextInt(255);
                int G = r.nextInt(255);
                int B = r.nextInt(255);
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
            int n = 0;
            yzm = "";
                for(int i = 0; i < 4; i++) {
                        n = r.nextInt(62);
                        yzm += YZM[n];
                        int flag = r.nextInt(2);
                        Color color = new Color(r.nextInt(200) + 20, r.nextInt(200) + 20, r.nextInt(200) + 20);
                        g2.setColor(color);
                        Graphics2D g2d = (Graphics2D)g;
                        AffineTransform trans = new AffineTransform();// Rotate the text by the specified Angle
                        if(flag == 0) {
                                trans.rotate(- r.nextInt(45) * 3.14 / 180.275 + i * 25.307);
                        }else {
                                trans.rotate(r.nextInt(45) * 3.14 / 180.275 + i * 25.307);
                        }
                        g2d.setTransform(trans);
                        g2.setFont(new Font(Microsoft Yahei.1.24));
                        g2.drawString(YZM[n] + "".277 + i * 22.307); }}}Copy the code

🍺 II. File operations

The class name is fileOperation.java

First we need to create the Excel file

This includes number, username, password, score, level, number of wins, total, password remembered, automatic login, and registration time

public void creatExcel(String path) {
        String data[] = { "Num"."userName"."password"."points"."class"."winNum"."totalNum"."RememberPassword"."AutoLogin"."date"};
        try {  
    File file = new File(path);
    WritableWorkbook book = Workbook.createWorkbook(file); 
    WritableSheet sheet = book.createSheet("User Information".0); 
    for(int i = 0; i < data.length; i++) {// Write the information to the XLS file
        Label label = new Label(i, 0, data[i]);
        sheet.addCell(label);
    }
    book.write();  
    book.close();  

} catch(Exception e) { System.out.println(e); }}Copy the code

The following method is used to determine whether an account exists

public boolean readData(String path, String userName) {
        File file = new File(path);
        if(! file.exists()) {// If the file does not exist
                creatExcel("user.xls");// Create the file
        }
        Workbook workbook = null;
        Sheet sheet = null;
        Cell cell = null;
        boolean flag = false;
        try {
                workbook = Workbook.getWorkbook(file);
                sheet = workbook.getSheet(0);
                for(int i = 0; i < sheet.getRows(); i ++) {
                        cell = sheet.getCell(1, i);
                        String content = cell.getContents();// Get the content
                        if(content.equals(userName)) {
                                flag = true;
                                break;
                        }
                }
                workbook.close();
        }catch(Exception e) {
                e.printStackTrace();
        }
        return flag;
}
Copy the code

The user writes information to a file

public void writeData(String path, String userName, String keyword, String data) {
		File file = new File(path);// Create file object
		if(! file.exists()) {// If the file does not exist
			creatExcel("user.xls");// Create the file
		}
	    Workbook workbook = null;  
        WritableWorkbook wtbook = null;  
        WritableSheet wtsheet = null;  
        WritableCell wtcell = null; 
        int flagx = 0; 
        int flagy = 0;
        try {
            workbook = Workbook.getWorkbook(file);  
            wtbook = Workbook.createWorkbook(file, workbook);  
            wtsheet = wtbook.getSheet(0);// Get the first form
            for(int i = 0; i < wtsheet.getColumns(); i++) {/ / lookup columns
            	wtcell = wtsheet.getWritableCell(i, 0);
            	if(wtcell.getType() == CellType.LABEL) {
            		String cell = ((Label)wtcell).getContents();
		            if(cell.equals(keyword)) {// Locate the line of the keyword
		            	flagx = i;
		            	break; }}}if(keyword.equals("userName")) {// If the user name is written
            	flagy = wtsheet.getRows();
            }else {// Write something else
            	for(int i = 0; i < wtsheet.getRows(); i++) {/ / line
            		wtcell = wtsheet.getWritableCell(1, i);
	        		String cell = ((Label)wtcell).getContents();
	        		if(cell.equals(userName)) {
	        			flagy = i;
	        			break;
	        		}
	            }
            }
	        Label label = new Label(flagx, flagy, data);
	        wtsheet.addCell(label);
	        wtsheet.addCell(new Label(0, flagy, String.valueOf((wtsheet.getRows() - 1))));
	        
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                wtbook.write();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            try {  
                wtbook.close();  
            } catch(WriteException | IOException e) { e.printStackTrace(); } workbook.close(); }}Copy the code

The information about the corresponding user is returned

public String backData(String path, String userName, String keyword) {
        File file = new File(path);
        if(! file.exists()) {// If the file does not exist
                creatExcel("user.xls");// Create the file
        }
        Workbook workbook = null;
        Sheet sheet = null;
        Cell cell = null;
        int flagx = 0; 
        int flagy = 0;
        try {
                workbook = Workbook.getWorkbook(file);
                sheet = workbook.getSheet(0);
                for(int i = 0; i < sheet.getColumns(); i++) {// Find the row where the user name is
                        cell = sheet.getCell(i, 0);
                        String s = cell.getContents();

                        if(s.equals(keyword)) {
                                flagx = i;
                                break; }}for(int i = 0; i < sheet.getRows(); i++) {
                        cell = sheet.getCell(1, i);
                        String s = cell.getContents();
                        if(s.equals(userName)) {
                                flagy = i;
                                break;
                        }
                }
                workbook.close();
        }catch(Exception e) {
                e.printStackTrace();
        }
        try {
                cell = Workbook.getWorkbook(file).getSheet(0).getCell(flagx, flagy);
        }catch(Exception e) {
                e.printStackTrace();
        }
        String s = cell.getContents();
        return s;
}
Copy the code

✨ 3. Board page class

Board page class name: chessboard.java

Adds an event listener for the color selection

whiteChessLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
                if(chessboardEmpty == 0) {// You can select the color only when the board is empty
                    whiteChessjr.setSelected(true); }}}); blackChessLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
                if(chessboardEmpty == 0) {// You can select the color only when the board is empty
                    blackChessjr.setSelected(true); }}});Copy the code

Add an event listener for the New office button

newRound.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                for(int i = 0; i < map.length; i++) {// Set the map array to 0
                        for(int j = 0; j < map[i].length; j++) {
                                map[i][j] = 0;
                                mapflag[i][j] = 0; }}for(int j = 0; j < 225; j++) {// Set the array of tokens to 0
                        imapflag[j] = 0;
                        jmapflag[j] = 0;
                }
                flag = 0;// Set the following table to 0
                winFLAG = 0;// Set the win/lose flag to 0
                playerColor = -1;// Set the player color mark to -1
                computerColor = -1;// The color of the computer is -1
                chessboardEmpty = 0;// The board mark is empty
                player = 1;// Players play chess first
                computer = 0;// After the computer down
                newchessX = 0;// Set the new chess mark to 0
                newchessY = 0;
                depth = 0; repaint(); }});Copy the code

Add an event listener for the contrite

back.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

                if(flag - 1> =0) {// When there are pieces on the board, click once to lose two pieces on the board, one is your own, the other is the computer
                        for(int i = flag - 1; i > flag - 3; i--) {
                                map[imapflag[i]][jmapflag[i]] = 0;
                                mapflag[imapflag[i]][jmapflag[i]] = 0;
                                imapflag[i] = 0;// Store the coordinates in the array of tokens
                                jmapflag[i] = 0;
                        }
                        flag = flag - 2;// Indicates that each pair on the board loses one piece
                        winFLAG = 0;
                        if(flag - 1> =0) {
                                newchessX = imapflag[flag - 1];
                                newchessY = jmapflag[flag - 1];
                        }
                        if(flag == 0) {// The board is empty
                                chessboardEmpty = 0;// The board is empty
                                playerColor = -1;// Set the color of player and computer chess pieces to 0
                                computerColor = -1;
                                depth = 0;
                        }
                        repaint();
                }else{; }}});Copy the code

The return button adds an event listener

returnback.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                dispose();
                newMain(); }});Copy the code

Exit the button event listener

exit.addActionListener(new ActionListener() {// Click the Exit button to exit the program
        public void actionPerformed(ActionEvent e) {
                System.exit(0); }});Copy the code

Mouse into the checkerboard area, used to display the prompt box, indicating that click can be played in which area

addMouseMotionListener(new MouseMotionListener() {
        public void mouseMoved(MouseEvent e) {
                // TODO automatically generates method stubs
                x = e.getX();
                y = e.getY();
                if(x >= 247 && x <= 951 && y >=77 && y <= 781) {// If the mouse click on the point in the board or the edge of a point
                        double m = (x - 270.0) /47.0;// Determine which intersection point is closest to the click location
                        double n = (y - 100.0) /47.0;
                        int p = (x - 270) /47;
                        int q = (y - 100) /47;
                        int i, j;
                        if(m - p >= 0.5 || m - p <= -0.5) {
                                i = p + 1;
                        }else {
                                i = p;
                        }
                        if(n - q >= 0.5 || n - q <= -0.5) {
                                j = q + 1;
                        }else {
                                j = q;
                        }
                        if(i >=0 && i <= 15 && j >= 0 && j <= 15) {// The identified area is within the board
                                if(mapflag[i][j] == 0 && winFLAG == 0 && player == 1) {// There are no chess pieces in this place, and there is no win yet
                                        promptBoxFlag[i][j] = 1; repaint(); }}}}public void mouseDragged(MouseEvent e) {}});Copy the code

Computer chess function

	private void tuntoComputer(a) {// The computer plays chess
		// TODO automatically generates method stubs
		if(depth >= 7) {
			depth = 6;
		}
		position = Algorithm.evalute(map, depth, computerColor);// Call the valuation function
		map[position[0]][position[1]] = computerColor;
		imapflag[flag] = position[0];// Store the coordinates in the array of tokens
		jmapflag[flag] = position[1];
		newchessX = position[0];// The new chess mark records coordinates
		newchessY = position[1];
		int a = Math.max(Math.abs(position[0] - 7), Math.abs(position[1] - 7));// Calculate the maximum distance from the point to the center
		depth = Math.max(depth, a);// Update the depth value continuously
		flag ++;
		chessboardEmpty = 1;// The board is marked with pieces
		player = 1;// Set the player chess mark to 0
		computer = 0;// The computer chess mark is 1
		judgeFlag = 1;
		repaint();
	}
Copy the code

Drawing board

    for(int i = 0; i < 15; i++) {/ / horizontal
            g2.drawLine(261, i * 47 + 63.919, i * 47 + 63);
    }
    for(int j = 0; j < 15; j++) {/ / vertical lines
            g2.drawLine(j * 47 + 261.64, j * 47 + 261.721);
    }
Copy the code

Draw the pieces

for(int i = 0; i < map.length; i++) {
        for(int j = 0; j < map[i].length; j++) {
                / / white
                if(map[i][j] == 1) {
                        g2.drawImage(white, i * 47 + 241, j * 47 + 43.40.40.this);
                        mapflag[i][j] = 1;// Mark the position to indicate that there is already a chess piece in the place
                }
                / / black
                if(map[i][j] == 2) {
                        g2.drawImage(black, i * 47 + 241, j * 47 + 43.40.40.this);
                        mapflag[i][j] = 1; }}}Copy the code

Determine if the pieces are connected in five

if(judgeFlag == 1) {
        judge();
        judgeFlag = 0;
}
Copy the code

Draws red dot marker for new chess pieces

if(chessboardEmpty ! =0) {
        g2.setColor(Color.red);
    g2.fillOval(newchessX * 47 + 254, newchessY * 47 + 55.15.15);
}
Copy the code

Draws the mouse movement box

for(int i = 0; i < 15; i++) {
        for(int j = 0; j < 15; j++) {
                if(promptBoxFlag[i][j] == 1) {
                        g2.setColor(Color.RED);
                        g2.setStroke(new BasicStroke(2.5 f));// Set the line size
                        g2.drawLine(238 + i * 47.40 + j * 47.248 + i * 47.40 + j * 47);// Upper left horizontal line
                        g2.drawLine(275 + i * 47.40 + j * 47.285 + i * 47.40 + j * 47);// Upper right horizontal line
                        g2.drawLine(238 + i * 47.40 + j * 47.238 + i * 47.50 + j * 47);// Upper left vertical line
                        g2.drawLine(285 + i * 47.40 + j * 47.285 + i * 47.50 + j * 47);// Upper right vertical line
                        g2.drawLine(238 + i * 47.77 + j * 47.238 + i * 47.87 + j * 47);// Bottom left vertical line
                        g2.drawLine(285 + i * 47.77 + j * 47.285 + i * 47.87 + j * 47);// Bottom right vertical line
                        g2.drawLine(238 + i * 47.87 + j * 47.248 + i * 47.87 + j * 47);// Lower left horizontal line
                        g2.drawLine(275 + i * 47.87 + j * 47.285 + i * 47.87 + j * 47);// Bottom right horizontal line
                        promptBoxFlag[i][j] = 0; }}}for(int i = 0; i < 5; i++) {// Top right star
        g2.drawImage(happy, 711 + i * 47.20.40.40.null);
}
Copy the code

Fixed an issue where the win/lose sign was not displayed the first time

g2.drawImage(win, 0.0.1.1.null);
g2.drawImage(lose, 0.0.1.1.null);

if(winFLAG == 0 && player == 0) {// Call the computer to play chess
        tuntoComputer();
}
Copy the code

Sets whether dropdown boxes and radio buttons on the board that are not empty cannot be selected

Sets the available status of the chess color checkbox

if(chessboardEmpty == 1) {// The board is not empty
        difficulityClass.setEnabled(false);// Set the drop-down box to be unavailable
        if(whiteChessjr.isSelected()) {// The white piece checkbox is selected
                blackChessjr.setEnabled(false);
                whiteChessjr.setEnabled(true);
        }else {// The black piece checkbox is selected
                blackChessjr.setEnabled(true);
                whiteChessjr.setEnabled(false); }}else {// The board is empty
        blackChessjr.setEnabled(true);// Release two radio boxes
        whiteChessjr.setEnabled(true);
        difficulityClass.setEnabled(true);// Release the drop-down box
}
Copy the code

Redraw integrals, levels, win rates

classNum = (int) ((int)(pointsNum /100 * 0.4 + gamewinNum * 0.4 + gameNum * 0.2) * 0.8);
sunNum = (int) (classNum / 100);
moonNum = (int)(classNum - sunNum * 100) / 50;
starNum = (int)(classNum - sunNum * 100 - moonNum * 50) / 10;
for(t = 0; t < sunNum; t++) {// Paint the sun
        g2.drawImage(sun, 75 + t * 30.538.30.30.null);
}
for(t = sunNum ; t < moonNum + sunNum; t++) {// Paint the moon
        g2.drawImage(moon, 75 + t * 30.540.25.25.null);
}
if(moonNum > 0 || sunNum > 0) {// Paint stars
        for(t = moonNum + sunNum ; t < starNum + moonNum + sunNum; t ++) {
            g2.drawImage(star, 75 + t * 30.540.25.25.null); }}else {
        for(t = moonNum ; t < starNum + 1; t ++) {
            g2.drawImage(star, 75 + t * 30.538.30.30.null); }}Copy the code

Determine if the pieces are connected in five

public void judge(a) {
        for(t = newchessX,s = newchessY,count = 0; t >=0 && s >= 0 && count <= 4; t--,s--,count++) {
                comeX = t;
                comeY = s;
        }
        for(t = newchessX, s = newchessY, count = 0; t <=14 && s >= 0 && count <= 4; t++, s--, count++) {
                toX = t;
                toY = s;
        }
        if(winFLAG == 0) {
                for(int ch = 1; ch <=2; ch++) {
                        CHESSCOLOR = ch;
                        // Judge the horizontal pieces
                        for(s = (newchessX - 4) > =0 ? (newchessX - 4) : 0 ; s <= newchessX; s++) {// Indicates that the player wins
                            t = newchessY;
                                if(map[s][t] == CHESSCOLOR && s < 11) {// Count the number of rows
                                        if(map[s + 1][t] == CHESSCOLOR) {
                                                if(map[s + 2][t] == CHESSCOLOR) {
                                                        if(map[s + 3][t] == CHESSCOLOR) {
                                                                if(map[s + 4][t] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 1;
                                                                        if(CHESSCOLOR == 1) {/ / white
                                                                                winFLAG = 1;
                                                                        }else {/ / black
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG ! =0) {// If one side wins, it will quit
                                break;
                        }
                // Determine the listed pieces
                        for(t = (newchessY - 4) > =0 ? (newchessY - 4) : 0 ; t <= newchessY; t ++) {
                                s = newchessX;
                                if(map[s][t] == CHESSCOLOR && t < 11) {// Count the number of pieces in the column
                                        if(map[s][t + 1] == CHESSCOLOR) {
                                                if(map[s][t + 2] == CHESSCOLOR) {
                                                        if(map[s][t + 3] == CHESSCOLOR) {
                                                                if(map[s][t + 4] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 2;
                                                                        if(CHESSCOLOR == 1) {/ / white
                                                                                winFLAG = 1;
                                                                        }else {/ / black
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG ! =0) {// If one side wins, it will quit
                                break;
                        }
                // Determine the top left to bottom right pieces
                        for(s = comeX, t = comeY; s <= newchessX && t <= newchessY; s ++, t++) {
                                if(map[s][t] == CHESSCOLOR && s < 11 && t < 11) {// Count the number of slant pieces
                                        if(map[s + 1][t + 1] == CHESSCOLOR) {
                                                if(map[s + 2][t + 2] == CHESSCOLOR) {
                                                        if(map[s + 3][t + 3] == CHESSCOLOR) {
                                                                if(map[s + 4][t + 4] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 3;
                                                                        if(CHESSCOLOR == 1) {/ / white
                                                                                winFLAG = 1;
                                                                        }else {/ / black
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG ! =0) {// If one side wins, it will quit
                                break;
                        }
                // Determine the upper right to lower left pieces
                        for(s = toX, t = toY; s >= newchessX && t <= newchessY; s --, t++) {
                                if(map[s][t] == CHESSCOLOR && s >= 4 && t < 11) {// Count the number of diagonal pieces
                                        if(map[s - 1][t + 1] == CHESSCOLOR) {
                                                if(map[s - 2][t + 2] == CHESSCOLOR) {
                                                        if(map[s - 3][t + 3] == CHESSCOLOR) {
                                                                if(map[s - 4][t + 4] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 4;
                                                                        if(CHESSCOLOR == 1) {/ / white
                                                                                winFLAG = 1;
                                                                        }else {/ / black
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG ! =0) {// If one side wins, it will quit
                                break; }}}}Copy the code

💌 4. Main function main.java

Basic layout Settings

setTitle("Happy Gobang");
setBounds(200.200.500.500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
SpringLayout springLayout = new SpringLayout();// Use the spring layout manager
Container c = getContentPane();// Create a container
c.setBackground(new Color(255.218.185));
c.setLayout(springLayout);

userjt.setFont(new Font(Microsoft Yahei.0.18 ));
userjt.setText(Register.userName);
passwordjt.setFont(new Font(Microsoft Yahei.0.18));
passwordjt.setText(Register.password);
logoLabel.setFont(new Font(Microsoft Yahei.1.48));
logoLabel.setForeground(Color.pink);
ImageIcon logoimage = new ImageIcon(Main.class.getResource("/image/logo5.jpg"));
logoimage.setImage(logoimage.getImage().getScaledInstance(260.130, Image.SCALE_DEFAULT));
logo.setIcon(logoimage);
userLabel.setFont(new Font(Microsoft Yahei.1.20));
passwordLabel.setFont(new Font(Microsoft Yahei.1.20));
rememberPasswordjl.setFont(new Font(Microsoft Yahei.0.14));
rememberPasswordjl.setForeground(Color.gray);
automaticLoginjl.setFont(new Font(Microsoft Yahei.0.14));
automaticLoginjl.setForeground(Color.gray);
loginButton.setFont(new Font(Microsoft Yahei.1.16));
registerLabel.setFont(new Font(Microsoft Yahei.1.13));
registerLabel.setForeground(Color.gray);
promptPasswordFalse.setFont(new Font(Microsoft Yahei.0.13));
promptPasswordFalse.setForeground(Color.red);
promptUserNameEmpty.setFont(new Font(Microsoft Yahei.0.13));
promptUserNameEmpty.setForeground(Color.red);
prompPasswordEmpty.setFont(new Font(Microsoft Yahei.0.13));
prompPasswordEmpty.setForeground(Color.red);
promptRegister.setFont(new Font(Microsoft Yahei.0.13));
promptRegister.setForeground(Color.red);
rememberPasswordjcb.setBackground(new Color(255.218.185));
automaticLoginjcb.setBackground(new Color(255.218.185));
Copy the code

Home page icon

c.add(logo);// Home icon
springLayout.putConstraint(springLayout.NORTH, logo, 40, springLayout.NORTH, c);
springLayout.putConstraint(springLayout.WEST, logo, 115, springLayout.WEST, c);
    c.add(logoLabel);// Title "Happy Gobang"
    springLayout.putConstraint(springLayout.NORTH, logoLabel, 100, springLayout.NORTH, c);
    springLayout.putConstraint(springLayout.WEST, logoLabel, 120, springLayout.WEST, c);
    logoLabel.setVisible(false);
Copy the code

The user name

c.add(userLabel);/ / user name
springLayout.putConstraint(springLayout.NORTH, userLabel, 35, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, userLabel, 110, springLayout.WEST, c);
c.add(userjt);
springLayout.putConstraint(springLayout.NORTH, userjt, 35, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, userjt, 10, springLayout.EAST, userLabel);
Copy the code

password

c.add(passwordLabel);/ / password
springLayout.putConstraint(springLayout.NORTH, passwordLabel, 10, springLayout.SOUTH, userLabel);
springLayout.putConstraint(springLayout.WEST, passwordLabel, 110, springLayout.WEST, c);
c.add(passwordjt);
springLayout.putConstraint(springLayout.NORTH, passwordjt, 10, springLayout.SOUTH, userjt);
springLayout.putConstraint(springLayout.WEST, passwordjt, 10, springLayout.EAST, passwordLabel);
Copy the code

Check box

c.add(rememberPasswordjcb);/ / check box
springLayout.putConstraint(springLayout.NORTH, rememberPasswordjcb, 10, springLayout.SOUTH, passwordLabel);
springLayout.putConstraint(springLayout.WEST, rememberPasswordjcb, 175, springLayout.WEST, c);
c.add(rememberPasswordjl);
springLayout.putConstraint(springLayout.NORTH, rememberPasswordjl, 10, springLayout.SOUTH, passwordjt);
springLayout.putConstraint(springLayout.WEST, rememberPasswordjl, 5, springLayout.EAST, rememberPasswordjcb);
c.add(automaticLoginjcb);
springLayout.putConstraint(springLayout.NORTH, automaticLoginjcb, 10, springLayout.SOUTH, passwordjt);
springLayout.putConstraint(springLayout.WEST, automaticLoginjcb, 30, springLayout.EAST, rememberPasswordjl);
c.add(automaticLoginjl);
springLayout.putConstraint(springLayout.NORTH, automaticLoginjl, 10, springLayout.SOUTH, passwordjt);
springLayout.putConstraint(springLayout.WEST, automaticLoginjl, 5, springLayout.EAST, automaticLoginjcb);
Copy the code

Login and registration buttons

c.add(loginButton);// The login button
springLayout.putConstraint(springLayout.NORTH, loginButton, 20, springLayout.SOUTH, rememberPasswordjl);
springLayout.putConstraint(springLayout.WEST, loginButton, 110, springLayout.WEST, c);
c.add(registerLabel);// Register button
springLayout.putConstraint(springLayout.NORTH, registerLabel, 5, springLayout.SOUTH, loginButton);
springLayout.putConstraint(springLayout.WEST, registerLabel, 320, springLayout.WEST, c);
Copy the code

The account is not registered

c.add(promptRegister);// The account is not registered
promptRegister.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, promptRegister, 41, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, promptRegister, 5, springLayout.EAST, userjt);
c.add(promptUserNameEmpty);// Please enter the account number
promptUserNameEmpty.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, promptUserNameEmpty, 41, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, promptUserNameEmpty, 5, springLayout.EAST, userjt);
Copy the code

Password error message

c.add(promptPasswordFalse);
promptPasswordFalse.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, promptPasswordFalse, 20, springLayout.SOUTH, promptRegister);
springLayout.putConstraint(springLayout.WEST, promptPasswordFalse, 5, springLayout.EAST, passwordjt);
Copy the code

The password is empty

c.add(prompPasswordEmpty);
prompPasswordEmpty.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, prompPasswordEmpty, 20, springLayout.SOUTH, promptRegister);
springLayout.putConstraint(springLayout.WEST, prompPasswordEmpty, 5, springLayout.EAST, passwordjt);
Copy the code

Set the text box mouse click event

userjt.addMouseListener(new MouseAdapter() {/ / text boxes
        public void mouseClicked(MouseEvent e) {
                userjt.setText(""); }}); passwordjt.addMouseListener(new MouseAdapter() {/ / the password box
        public void mouseClicked(MouseEvent e) {
                passwordjt.setText(""); }});Copy the code

Set the login button click event

loginButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                String userName = userjt.getText().trim();// Obtain the account and password entered by the user
                String Password = new String(passwordjt.getPassword()).trim();
                // Determine the account and password
            if(userName.length() ! =0) {// The user name is not empty
                promptUserNameEmpty.setVisible(false);// Close the account and the display is empty
                if(Password.length() ! =0) {// The password is not empty
                        if(f.readData("user.xls", userName) && Password.equals(f.backData("user.xls", userName, "password"))) {// The user entered the correct account and password
                                        promptRegister.setVisible(false);// Hide the prompt
                                        promptPasswordFalse.setVisible(false);
                                        prompPasswordEmpty.setVisible(false);
                                        loginButton.setText("Landing... ");
                                        new Chessboard();// Go to the gobang board page
                                        dispose();// Destroy the current page
                                }
                        else if( f.readData("user.xls", userName) && ! Password.equals(f.backData("user.xls", userName, "password"))) {// The user entered an incorrect password
                                        promptPasswordFalse.setVisible(true);// A password error message is displayed
                                        promptRegister.setVisible(false);
                                        prompPasswordEmpty.setVisible(false);
                                        passwordjt.setText("");// The password box is cleared
                                        passwordjt.requestFocus();// Move the cursor to the password box
                                }else {// The account has not been registered
                                        promptRegister.setVisible(true);
                                promptPasswordFalse.setVisible(false);
                                        prompPasswordEmpty.setVisible(false); }}else {// The password is empty
                        if(userName.equals("admin")) {// The user name has been registered, prompting for a password
                                prompPasswordEmpty.setVisible(true);
                                promptUserNameEmpty.setVisible(false);
                                promptRegister.setVisible(false);
                                promptPasswordFalse.setVisible(false);
                        }else {// User name is not registered
                                prompPasswordEmpty.setVisible(false);
                                promptUserNameEmpty.setVisible(false);
                                promptRegister.setVisible(true);
                                promptPasswordFalse.setVisible(false); }}}else {// The user name is empty
                promptUserNameEmpty.setVisible(true);// You are prompted to enter the account
                promptRegister.setVisible(false);
                promptPasswordFalse.setVisible(false);
                prompPasswordEmpty.setVisible(false);
                passwordjt.setText("");// Leave the password box blank
                if(Password.length() == 0) {// The password is empty
                        prompPasswordEmpty.setVisible(true);
                        promptRegister.setVisible(false);
                        promptPasswordFalse.setVisible(false); }}}});Copy the code

Register tag listeners

registerLabel.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
dispose();
                new Register();
        }
        public void mouseEntered(MouseEvent e) {
                registerLabel.setForeground(Color.red);;
        }
        public void mouseExited(MouseEvent e) {
            registerLabel.setForeground(Color.black);
        }
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}});Copy the code

🎖 5. Algorithm. Java

Count the left pieces

for(int i = X - 1; i >=0; i--) {
        if(map[i][Y] == color) {
                upcount[0] + +; }else if(map[i][Y] ! =0&& map[i][Y] ! = color) {// Indicates that there are pieces of the opposing party
                upflag[0] = -1;
                break;
        }else {// Is null
                upflag[0] = 1;
                if(i - 1> =0 && map[i][Y] == 0) {
                        upflag[0] = 2;// Indicates two Spaces
                }else {
                        break;
                }
                if(i - 2> =0 && map[i][Y] == 0) {
                        upflag[0] = 3;// Indicates three Spaces
                }else {
                        break;
                }
                break; }}Copy the code

Count the number of pieces on the right

for(int j = X + 1; j <= 14; j++) {
        if(map[j][Y] == color) {
                downcount[0] + +; }else if(map[j][Y] ! =0&& map[j][Y] ! = color) { downflag[0] = -1;
                break;
        }else {// Is null
                downflag[0] = 1;
                if(j + 1< =14 && map[j][Y] == 0) {
                        downflag[0] = 2;
                }else {
                        break;
                }
                if(j + 2< =14 && map[j][Y] == 0) {
                        downflag[0] = 3;
                }else {
                        break;
                }
                break; }}Copy the code

The calculation direction is upward

for(int i = Y - 1; i >= 0; i--) {
        if(map[X][i] == color) {
                upcount[1] + +; }else if(map[X][i] ! =0&& map[X][i] ! = color) {// Indicates that the dot is the opponent's piece
                upflag[1] = -1;
                break;
        }else {// Is null
                upflag[1] = 1;
                if(i - 1> =0 && map[X][i] == 0) {
                        upflag[1] = 2;
                }else {
                        break;
                }
                if(i - 2> =0 && map[X][i] == 0) {
                    upflag[1] = 3;
                }else {
                        break;
                }
                break; }}Copy the code

The direction of calculation is downward

for(int j = Y + 1; j <= 14; j++) {
        if(map[X][j] == color) {
                downcount[1] + +; }else if(map[X][j] ! =0&& map[X][j] ! = color) {// Indicates that the dot is the opponent's piece
                downflag[1] = -1;
                break;
        }else {// Is null
                downflag[1] = 1;
                if(j + 1> =0 && map[X][j] == 0) {
                        downflag[1] = 2;
                }else {
                        break;
                }
                if(j + 2> =0 && map[X][j] == 0) {
                    downflag[1] = 3;
                }else {
                        break;
                }
                break; }}Copy the code

Calculated incline

int i = 0;
int j = 0;
for(i = X - 1, j = Y - 1; i >= 0 && j >= 0; i--, j--) {
        if(map[i][j] == color) {
                upcount[2] + +; }else if(map[i][j] ! =0&& map[i][j] ! = color) { upflag[2] = -1;
                break;
        }else {/ / is empty
                upflag[2] = 1;
                if(i - 1> =0 && j - 1> =0 && map[i][j] == 0) {
                        upflag[2] = 2;
                }else {
                        break;
                }
                if(i - 2> =0 && j - 2> =0 && map[i][j] == 0) {
                        upflag[2] = 3;
                }else {
                        break;
                }
                break; }}Copy the code

Calculate slope down

for(i = X + 1, j = Y + 1; i <= 14 && j <= 14; i++, j++) {
        if(map[i][j] == color) {
                downcount[2] + +; }else if(map[i][j] ! =0&& map[i][j] ! = color) { downflag[2] = -1;
                break;
        }else {/ / is empty
                downflag[2] = 1;
                if(i + 1< =14 && j + 1< =14 && map[i][j] == 0) {
                        downflag[2] = 2;
                }else {
                        break;
                }
                if(i + 2< =14 && j + 2< =14 && map[i][j] == 0) {
                        downflag[2] = 3;
                }else {
                        break;
                }
                break; }}Copy the code

Valuation algorithm that returns an array for recording coordinates

public static int[] evalute(int map[][], int depth, int computerColor) {
        int maxscore = 0;
        Random r = new Random();
        int pos[][] = new int[10] [2]; {for(int i = 0; i < pos.length; i++) {
                        for(int j = 0; j < pos[i].length; j++) {
                                pos[i][j] = 0; }}}int FLAG = 0;
        int score[][] = new int[15] [15]; {// Initialize the score array
                for(int i = 0; i < 15; i++) {
                        for(int j = 0; j < 15; j++) {
                                score[i][j] = 0; }}}int position[] = new int[] {0.0};// Initialize the array of position coordinates
        for(int i = 6 - depth; i <= 8 + depth && i <= 14; i++) {// Search the abscissa
                for(int j = 6 - depth; j <= 8 + depth && j <= 14; j++) {// Search the ordinate
                        if(map[i][j] == 0) {// Indicates that the point is empty on the board
                                score[i][j] = countScore(map, i, j, computerColor);
                                if(maxscore < score[i][j]) {
                                        maxscore = score[i][j];// Record the current maximum score on the board}}}}for(int i = 6 - depth; i <= 8 + depth && i <= 14; i++) {
                for(int j = 6 - depth; j <= 8 + depth && j <= 14; j++) {
                        if(score[i][j] == maxscore) {
                                pos[FLAG][0] = i;
                                pos[FLAG++][1] = j; }}}int m = r.nextInt(FLAG);
        position[0] = pos[m][0];
        position[1] = pos[m][1];
        return position;
}
Copy the code

Project directory

Java file

Other Documents required

Image:

The jar package: JXL. Jar

Code download:

【 Java Gobang games 】

Related articles:

The output of a Java program | Java exercises 】 【 first (resolution)

The output of a Java program | Java exercises 】 【 a second (resolution)

The output of a Java program | Java exercises 】 【 a third (resolution)

The output of a Java program | Java exercises 】 【 4 sets (including parsing)

The output of a Java program | Java exercises 】 【 5 sets (including parsing)

The output of the Java program Java exercises 】 【 | 6 sets (including parsing)

The output of a Java program | Java exercises 】 【 7 sets (including parsing)

The output of a Java program | Java exercises 】 【 8 sets (including parsing)

I have been writing a tech blog for a long time and this is one of my tech articles/tutorials. Hope you like it! Here is a summary of all my original and work source code: GitHub, Gitee

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support