Gobang game designed by Java

Keywords: Java Programming REST

requirement:

1. Write Gobang game in java
2. The program has a simple and beautiful graphical interface, and the interface is mainly composed of board, title and buttons for game operation. In addition, the size of the game interface is immutable, the program will automatically obtain the size information of the computer screen, and calculate the appropriate position to display in the center. Considering the display of chessboard and background picture, in order to prevent the disorder of arrangement, this design method is adopted.
3. The title is at the top of the interface; the board of go with board of 19 * 19 is at the bottom left; the buttons include: "start game", "exit game" and "Game Description", 3 in total, on the right side of the board
4. When you click the mouse, the chess pieces will be displayed in the corresponding position, and the turn of the chess player will also be displayed (the black pieces are required to be played first)
5. You can save the chess game, that is, you can save the pieces you have played before
6. Be able to judge the outcome of the game, and pop up a window prompt. After one game, you can clear the board interface through the "start game" button to play the next game.

Design idea:
This program mainly uses the following three technologies: (1) Swing programming; (2) use of ImageIO class; (3) drawing of Graphics pictures
For such a Gobang game program. 1. First of all, we need to use java.Swing and java.awt Toolkits to design the user interface of the game and draw image graphics, such as making chessboard. 2. In addition, the ImageIO class is also used to import and display pictures as the background of the game interface. The background pictures can be designed by yourself.
3. After the main interface is made, we can add event monitoring, and use MouseListener, a class related to monitoring mouse, to generate chess pieces by clicking in the specified area and location for game playing. 4. Next, we can design the algorithm to determine the winner. 5. Then the realization of button function. 6. Finally, debugging and testing to see if there are any bugs in the program.
Specific classes and methods will be introduced in the following main program
Programming process
Import java.awt , java.io and javax.swing Toolkits, which contain all the categories used to create user interfaces, draw graphical images, import images, and monitor the mouse.

import java.awt.Color;       //The color class is used to color the game interface
import java.awt.Font;       //Font class provides classes and interfaces related to font.
import java.awt.Graphics;   //The Graphics class provides the base class to perform the actual operation functions of drawing, coloring and text output
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;   //Classes related to listening mouse
import java.awt.image.BufferedImage;   //Processing class of imported pictures
import java.io.File;       // Abstract representation of file and directory pathnames.
import java.io.IOException;     //Abnormal class
import javax.imageio.ImageIO;    //Show classes for pictures
import javax.swing.JFrame;         //Create a form and set its size, location and other properties
import javax.swing.JOptionPane;      //Dialog related classes

First, design the main window of the game

public class FiveChessFrame extends JFrame implements MouseListener, Runnable {

	// Obtain the width and height of the screen to calculate the appropriate position to center the game interface
	int width = Toolkit.getDefaultToolkit().getScreenSize().width;
	int height = Toolkit.getDefaultToolkit().getScreenSize().height;
	// First define the background picture as empty
	BufferedImage bgImage = null;
	//X and Y defined here are used to save the coordinates of the chess pieces
	int x = 0;
	int y = 0;
	
   /** Define a 19 * 19 two-dimensional array to represent the chessboard, where the data content 0: indicates that there is no chessboard at this point, 1: indicates that this point is a black one, 2: indicates that this point is a white one*/
	int[][] allChess = new int[19][19];
	// Identify whether black chess or white chess is the next step
	boolean isBlack = true;
	// Identify whether the current game can continue
	boolean canPlay = true;
	// Save the displayed prompt information, which is used to display above the checkerboard of the interface
	String message = "Black first";
	
	//Set the main window (position, size, center display and other properties) of the Gobang game interface
       public FiveChessFrame() {
	   this.setTitle("Gobang--Zeng Lei");
		this.setSize(500, 500);
		this.setLocation((width - 500) / 2, (height - 500) / 2);
		this.setResizable(false);
		// Set the closing method of the form to the default, and the program will end
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Add a mouse listener to the form
		this.addMouseListener(this);
		// Show the form
		this.setVisible(true);

	/**The following is to import the pre-designed image as the background of the game interface, which is applied to the io flow operation. The background image is imported from the disk to the program through the ImageIo class, and try IOException is used to catch exceptions.*/
		try {
			bgImage = ImageIO.read(new File("E:\\image\\128.jpg"));
		} catch (IOException e) {
				e.printStackTrace();
		}
		// Refresh the screen to prevent the game from starting without display
		this.repaint();
	}


Draw chessboard

public void paint(Graphics g) {
		// Draw background
		g.drawImage(bgImage, 1, 20, this);
		// Output title information
		g.setFont(new Font("Blackbody", Font.BOLD, 20));
		g.drawString("  : " + message, 130, 60);
		
       /**Draw the chessboard, draw the line of the chessboard in the chessboard area flowing out of the background picture, use a for loop to draw the line of the chessboard, sweep all 18 equal points, it is easy to calculate*/
		for (int i = 0; i < 19; i++) {
			g2.drawLine(10, 70 + 20 * i, 370, 70 + 20 * i);
			g2.drawLine(10 + 20 * i, 70, 10 + 20 * i, 430);
		}
   /** Using the fillOver method of Graphics class to mark the nine points on the go board (only one is shown, and the rest is similar), you can first obtain the coordinates of the points by monitoring with the mouse, and then draw*/
		g2.fillOval(68, 128, 4, 4);
	/**The following provides the program code to draw the chess pieces, that is, to judge the color of the chess pieces produced in what position through the mouse listener. Parameter pass 1 for black, 2 for white.*/
		for (int i = 0; i < 19; i++) {
			for (int j = 0; j < 19; j++) {
				if (allChess[i][j] == 1) {
					int tempX = i * 20 + 10;
					int tempY = j * 20 + 70;
					g2.fillOval(tempX - 7, tempY - 7, 14, 14);
				}
				if (allChess[i][j] == 2) {
					int tempX = i * 20 + 10;
					int tempY = j * 20 + 70;
					g2.setColor(Color.WHITE);
					g2.fillOval(tempX - 7, tempY - 7, 14, 14);
					g2.setColor(Color.BLACK);
					g2.drawOval(tempX - 7, tempY - 7, 14, 14);
				}
			}
		}
		g.drawImage(bi, 0, 0, this);
	}

Add mouse monitor

public void mousePressed(MouseEvent e) {
		if (canPlay == true) {
			x = e.getX();
			y = e.getY();
			if (x >= 10 && x <= 370 && y >= 70 && y <= 430) {
				x = (x - 10) / 20;
				y = (y - 70) / 20;
				if (allChess[x][y] == 0) {
				if (isBlack == true) {
						allChess[x][y] = 1;
						isBlack = false;
						message = "It's Bai Fang's turn";
					} else {
						allChess[x][y] = 2;
						isBlack = true;
						message = "Black Square";
					}
					// Judge whether this chess piece is connected with other chess pieces by 5, that is, judge whether the game is over
					boolean winFlag = this.checkWin();
					if (winFlag == true) {
						JOptionPane.showMessageDialog(this, "game over,"
								+ (allChess[x][y] == 1 ? "Black Square" : "Baifang") + "win victory!");
						canPlay = false;
					}
				} else {
					JOptionPane.showMessageDialog(this, "There are pieces in the current position. Please drop them again!");
				}
				this.repaint();
			}
		}

Give each button corresponding function

Give the start game button corresponding functions. Click "start game". If you want to restart the game, clear the board, reset the data in allchess to zero, change the "game information" display back to the initial state, and change the next game to black square

if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 70
				&& e.getY() <= 100) {
		int result = JOptionPane.showConfirmDialog(this, "Do you want to restart the game?");
		if (result == 0) 
		   allChess = new int[19][19];
		message = "Black first";
			isBlack = true;
				this.repaint();

			}
		}

Give "quit game" button corresponding functions

if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 370
				&& e.getY() <= 400) {
			JOptionPane.showMessageDialog(this, "game over");
			System.exit(0);
		}
	}

Give "game settings" button function

if (e.getX() >= 387 && e.getX() <= 496 && e.getY() >= 228
				&& e.getY() <= 261) {
			String input = JOptionPane
					.showInputDialog("Please enter the maximum time of the game(Company:minute),If you enter 0,No time limit:");
			try {
				maxTime = Integer.parseInt(input) * 60;
				if (maxTime < 0) {
					JOptionPane.showMessageDialog(this, "Please enter the correct information,Negative number is not allowed!");
				}
				if (maxTime == 0) {
					int result = JOptionPane.showConfirmDialog(this,
							"Setup complete,Do you want to restart the game?");
					if (result == 0) {
						for (int i = 0; i < 19; i++) {
							for (int j = 0; j < 19; j++) {
								allChess[i][j] = 0;
							}
						}
						// The other way is allChess = new int[19][19];
						message = "Black first";
						isBlack = true;
						blackTime = maxTime;
						whiteTime = maxTime;
						blackMessage = "unlimited";
						whiteMessage = "unlimited";
						this.canPlay = true; 
						this.repaint();
					}
				}
				if (maxTime > 0) {
					int result = JOptionPane.showConfirmDialog(this,
							"Setup complete,Do you want to restart the game?");
					if (result == 0) {
						for (int i = 0; i < 19; i++) {
							for (int j = 0; j < 19; j++) {
								allChess[i][j] = 0;
							}
						}
						// The other way is allChess = new int[19][19];
						message = "Black first";
						isBlack = true;
						blackTime = maxTime;
						whiteTime = maxTime;
						blackMessage = maxTime / 3600 + ":"
								+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
								+ (maxTime - maxTime / 60 * 60);
						whiteMessage = maxTime / 3600 + ":"
								+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
								+ (maxTime - maxTime / 60 * 60);
						t.resume();
						this.canPlay = true; 
						this.repaint();
					}
				}
			} catch (NumberFormatException e1) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this, "Please input the information correctly!");
			}
		}

Give "give up" button function

if (e.getX() >= 386 && e.getX() <= 496 && e.getY() >= 284
				&& e.getY() <= 316) {
			int result = JOptionPane.showConfirmDialog(this, "Confirm to give up?");
			if (result == 0) {
				if (isBlack) {
					JOptionPane.showMessageDialog(this, "The black side has conceded defeat,game over!");
					canPlay=false;
				} else {
					JOptionPane.showMessageDialog(this, "Bai Fang has conceded defeat,game over!");
					canPlay=false;
				}
				canPlay = false;
			}
		}

Give "Game Description" button function

if (e.getX() >= 392 && e.getX() <= 493 && e.getY() >= 388
				&& e.getY() <= 427) {
			JOptionPane.showMessageDialog(this,
					"This is a Gobang game program, black and white both sides take turns to play chess, when one side is connected to five, the game ends. By Zeng Lei");
		}

Judge win or lose

private boolean checkWin() {
		boolean flag = false;
		// Save how many pieces of the same color are connected
		int count = 1;
		// Judge whether there are 5 pieces connected in the horizontal direction. The characteristic ordinate is the same, that is, y value in allChess[x][y] is the same
		int color = allChess[x][y];
		// Judge horizontal
		count = this.checkCount(1, 0, color);
		if (count >= 5) {
			flag = true;
		} else {
			// Judge vertical
			count = this.checkCount(0, 1, color);
			if (count >= 5) {
				flag = true;
			} else {
				// Judge upper right and lower left
				count = this.checkCount(1, -1, color);
				if (count >= 5) {
					flag = true;
				} else {
					// Judge bottom right and top left
					count = this.checkCount(1, 1, color);
					if (count >= 5) {
						flag = true;
					}
				}
			}
		}

		return flag;
	}

	// Judge the number of pieces connected
	private int checkCount(int xChange, int yChange, int color) {
		int count = 1;
		int tempX = xChange;
		int tempY = yChange;
		while (x + xChange >= 0 && x + xChange <= 18 && y + yChange >= 0
				&& y + yChange <= 18
				&& color == allChess[x + xChange][y + yChange]) {
			count++;
			if (xChange != 0)
				xChange++;
			if (yChange != 0) {
				if (yChange > 0)
					yChange++;
				else {
					yChange--;
				}
			}
		}
		xChange = tempX;
		yChange = tempY;
		while (x - xChange >= 0 && x - xChange <= 18 && y - yChange >= 0
				&& y - yChange <= 18
				&& color == allChess[x - xChange][y - yChange]) {
			count++;
			if (xChange != 0)
				xChange++;
			if (yChange != 0) {
				if (yChange > 0)
					yChange++;
				else {
					yChange--;
				}
			}
		}
		return count;
	}

Detection time limit

public void run() {
		// TODO Auto-generated method stub
		// Determine if there is a time limit
		if (maxTime > 0) {
			while (true) {
				if (isBlack&&canPlay) {
					blackTime--;
					if (blackTime == 0) {
						JOptionPane.showMessageDialog(this, "Black side timeout,game over!");
					}
				} else if(!isBlack&&canPlay) {
					whiteTime--;
					if (whiteTime == 0) {
						JOptionPane.showMessageDialog(this, "White side timeout,game over!");
					}
				}
				blackMessage = blackTime / 3600 + ":"
						+ (blackTime / 60 - blackTime / 3600 * 60) + ":"
						+ (blackTime - blackTime / 60 * 60);
				whiteMessage = whiteTime / 3600 + ":"
						+ (whiteTime / 60 - whiteTime / 3600 * 60) + ":"
						+ (whiteTime - whiteTime / 60 * 60);
				this.repaint();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(blackTime + " -- " + whiteTime);
			}
		}
	}



Background map of the game

Posted by haddydaddy on Sat, 20 Jun 2020 01:19:45 -0700