❤️Java❤️Realize "Gobang" Game❤️

Gobang Game Program Source Code and Implementation Page

Need all kinds of game source programs (Snake Eater, Match Man, Gobang, Mobile Interface Air Conditioning, etc.) Privately trust me!!!


1. Requirements
(1) Each side of the board will play the same chess piece.
(2) Opening of an empty board.
(3) Alternating descendants, one at a time.
(4) When a chess piece is placed on a blank point on the board, it must not move to another point, or be removed from the board or picked up to fall elsewhere.
(5) The first piece can be played at any intersection of the board.
2. Workload
(1) It has a menu interface.
(2) Opening of an empty board.
(3) Alternating descendants, one at a time.
(4) When a chess piece is placed on a blank point on the board, it must not move to another point, or be removed from the board or picked up to fall elsewhere.
(5) The first piece can be played at any intersection of the board.
(6) Win or lose can be judged after five children are connected

3. Program description
Design checker coordinates and size codes
package game;

import java.awt.Color;//Provides classes for color spaces.
import java.awt.Graphics;//This class is an abstract base class for all graphical contexts, allowing applications to draw on components implemented on a variety of devices and on off-screen images.
import java.awt.Graphics2D;//This class extends the graphics class to provide more complex control over geometry, coordinate conversion, color management, and text layout.
import java.awt.RadialGradientPaint;//This class provides a way to fill shapes with a circular radial color gradient pattern. Users can specify two or more gradient colors, and this paint will provide interpolation between each color.
import java.awt.RenderingHints;//This class defines and manages key collections and associated values, allowing applications to provide input for algorithm choices used by other categories that perform rendering and image manipulation services.

public class Chess {//Define the properties of a chess class
	Chessboard cp; 	//Checkerboard
	int row;		//Transverse coordinates
	int col;		//Ordinate coordinates
	Color color;	//Chess color
	
	public Chess(Chessboard cp, int col, int row, Color color) {
		this.cp = cp;
		this.col = col;
		this.row = row;
		this.color = color;
	}//Construction Method Draw Chess

	public Color getColor() {//Return color
		return color;
	}

	public void setColor(Color color) {//Modify Colors
		this.color = color;
	}

	public int getRow() {//Return x-coordinates
		return row;
	}

	public void setRow(int row) {//Modify x-coordinates
		this.row = row;
	}

	public int getCol() {//Return ordinates
		return col;
	}

	public void setCol(int col) {//Modify ordinates
		this.col = col;
	}

	public static final int BANJING = 18;//Define Static Variable Radius
	
    public void draw(Graphics g) {
		//Define the center of a chess piece
		Graphics2D g2d = (Graphics2D) g;//Force conversion of Graphics g to Graphics 2D
		int xPos = col * 20 + 15;
		int yPos = row * 20 + 15;//x-coordinate and y-coordinate of chess pieces'falling point
        RadialGradientPaint paint = null;
		Color[] c = { Color.WHITE, Color.black };//Chess is divided into two colors, black and white
		float[] f = { 0f, 1f };//Provides an array of float s that specify how colors are distributed along a gradient. These values range from 0.0 to 1.0 and act like keyframes along a gradient (they mark where the gradient should change completely to a particular color).
		int x = xPos + 3 ;
		int y = yPos + 3; //Place the pieces on the crossing line of the board
		if (color == Color.WHITE) {
			paint = new RadialGradientPaint(x, y, BANJING * 3, f, c);
		} else {
			paint = new RadialGradientPaint(x, y, BANJING, f, c);
		}
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//Anti-aliased
		g2d.setPaint(paint);//Give chess piece color
		g2d.fillOval(xPos - BANJING / 2, yPos - BANJING / 2, BANJING, BANJING);
		//Draw the pieces on the board, xPos-BANJING/2,yPos-BANJING/2 refers to the x and y coordinates of the upper left corner of the filled ellipse, BANJING, BANJING determines the size of the pieces (unchanged)
	}
}

4 Program 2 (Identifier) Design Description
4.1 Program Description
Defines the size of the board, the number of steps, the position of the pieces, determines the victory, determines whether there are pieces on the board, whether the pieces are placed in a reasonable position, and prompts what pieces should be played (black indicates white, and the falling pieces are white), change the color of the board, change the line color of the board, set the size and color of the text, display the text prompt, define the restart game action and regret action.
package game;

import java.awt.BasicStroke;//This class defines the basic set of rendering properties for the original graphic outline, which are represented by the graphic 2D object with the stroke property set to this property. Describes the rendering properties defined by the shape of the marker drawn by the pen along the shape outline and the ornaments applied at the ends and joins of the path segment.
import java.awt.Color;
import java.awt.Font;//Classes for setting fonts
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;//MouseAdapter's class is an abstract class (adapter) used to receive mouse events. All methods of this class are empty. This class is a convenient class for creating listener objects.
import java.awt.event.MouseEvent;//Represents an event in a component where a mouse action occurs. A mouse action should be considered to occur in a particular component if and only if the mouse cursor exceeds the unobstructed portion of the component boundary when the action occurs. For lightweight components such as Swing's componentsMouse event types are enabled by adding a mouse-based corresponding mouse to a component (mouse list or mouse motion listener) or by invoking a component. Enable Enable Events (Long) with appropriate mask parameters (or)If the mouse event type is not enabled on the component, the corresponding mouse event is sent to the first ancestor of the mouse event type enabled.
import javax.swing.JOptionPane;//It provides a standard way to pop up a standard dialog box of values or notify the user of something.
import javax.swing.JPanel;//JFrame is used to design an interface similar to a window in Windows.

public class Chessboard extends JPanel {
	public static final int MARGIN = 15;
	public static final int SPAN = 20;
	public static final int ROWS = 19;
	public static final int COLS = 19;
	Chess[] chessList = new Chess[20 * 20]; //Represents the position of a chess piece
	int chessCount = 0;//Represents the number of steps played
	boolean iso = false;
	boolean isBlack = true;
	String message = "Please start";//Prompt message
	private boolean isWin(int col, int row) {//Function to judge success
		boolean result = false;
		int CountCh = 1;
		Color c = null;
		if (isBlack) {
			c = Color.BLACK;
		} else {
			c = Color.WHITE;
		}

		// Horizontal to Left Connection
		for (int x = col - 1; x >= 0; x--) {
			if (exist(x, row, c)) {//Determine if a piece already exists in a position
				CountCh++;
			} else {
				break;
			}
		}
		// Connect Horizontally to Right
		for (int x = col + 1; x <= 19; x++) {
			if (exist(x, row, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Horizontal connection wins
		if (CountCh >= 5) {
			result = true;
			message = "Game over";
		} else {
			result = false;
			CountCh = 1;
		}
		// Connect vertically up
		for (int y = row - 1; y >= 0; y--) {
			if (exist(col, y, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Connect vertically down
		for (int y = row + 1; y <= 19; y++) {
			if (exist(col, y, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Vertical connection wins
		if (CountCh >= 5) {
			result = true;
			message = "Game over";
		} else {
			result = false;
			CountCh = 1;
		}
		// Diagonal Connection Upper Right
		for (int x = col + 1, y = row - 1; x <= 19 && y >= 0; x++, y--) {
			if (exist(x, y, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Diagonal Connection Lower Left
		for (int x = col - 1, y = row + 1; x >= 0 && y <= 19; x--, y++) {
			if (exist(x, y, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Diagonal Connection Wins
		if (CountCh >= 5) {
			result = true;
			message = "Game over";
		} else {
			result = false;
			CountCh = 1;
		}
		// Diagonal Connection Upper Left
		for (int x = col - 1, y = row - 1; x >= 0 && y >= 0; x--, y--) {
			if (exist(x, y, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Diagonal Connection Lower Right
		for (int x = col + 1, y = row + 1; x <= 19 && y <= 19; x--, y--) {
			if (exist(x, y, c)) {
				CountCh++;
			} else {
				break;
			}
		}
		// Diagonal Connection Wins
		if (CountCh >= 5) {
			result = true;
			message = "Game over";
		} else {
			result = false;
			CountCh = 1;
		}

		return result;
	}
	
	
	private boolean exist(int col, int row) {//Used to determine if a piece already exists at a position on the board, returns true if it exists
		boolean result = false;
		for (int i = 0; i < chessCount; i++) {
			Chess cc = chessList[i];
			if (cc != null && cc.getCol() == col && cc.getRow() == row) {
				return true;
			}
		}
		return result;
	}
	
	private boolean exist(int col, int row, Color c) {//Overloaded exist function
		Boolean result = false;
		for (int i = 0; i < chessCount; i++) {
			Chess ch = chessList[i];
			if (ch != null && ch.getCol() == col && ch.getRow() == row && ch.getColor() == c) {
				result = true;
			}
		}
		return result;
	}
	public Chessboard() {
		this.addMouseListener(new MouseAdapter() {//Use the component's addMouseListener method to register a listener object created from that class with that component. When the mouse is pressed, released, or clicked (pressed and released), a mouse event is generated that allows the chess pieces to appear on the board.

		        public void mousePressed(MouseEvent dianji) {//mousePressed is called when a mouse button is pressed on a component.
				if (iso) {
					return;
				}
				int col, row;
				col = (dianji.getX() - 15 + 10) /20;
				row = (dianji.getY() - 15 + 10) / 20;

				if (col > 19 || col < 0 || row > 19 || row < 0) {
					return;//Click on a place that is not on the board and do not respond
				} else {
					if (exist(col, row)) {
						return;//A chess piece can no longer be played where it already exists
					} else {
						Color yanse = Color.BLACK;//Start Black First
						if (isBlack) {
							yanse = Color.BLACK;
							message = "It's White's turn";//Show White after Black
						} else {
							yanse = Color.WHITE;
							message = "It's Black's turn";//Suggest Black after White
						}
						Chess location = new Chess(Chessboard.this, col, row, yanse);//Create a new use case to represent the position of a piece
						chessList[chessCount++] = location;//Implement use cases to show positions on the board
						repaint();//Refresh

						if (isWin(col, row)) {//isWin is a function of victory
							if (yanse == Color.BLACK) {
								JOptionPane.showMessageDialog(Chessboard.this, "Black wins!");
							} else if (yanse == Color.WHITE) {
								JOptionPane.showMessageDialog(Chessboard.this, "White wins!");//Indicates a message dialog box
							}
							iso = true;
							return;
						}
						isBlack = !isBlack;
					}
				}
			}
		});
	}

	public void paint(Graphics qipan) {
		qipan.setColor(Color.blue);//Modify the color of the board
		qipan.fillRect(0, 0, 410, 460);//Draw a filled rectangle on the canvas
		qipan.setColor(Color.pink);//Modify the color of the board line
		for (int i = 0; i < 20; i++) {
			qipan.drawLine(MARGIN, MARGIN + SPAN * i, MARGIN + 19 * 20, MARGIN + 20 * i);
		}
		for (int i = 0; i < 20; i++) {
		    qipan.drawLine(15 + SPAN * i, 15, 15 + SPAN * i, 15 + 19 * 20);
		}

		qipan.fillRect(73, 73, 5, 5);
		qipan.fillRect(193,73, 5, 5);
		qipan.fillRect(313, 73, 5, 5);
		qipan.fillRect(73, 193, 5, 5);
		qipan.fillRect(193, 193, 5, 5);
		qipan.fillRect(313, 193, 5, 5);
		qipan.fillRect(73, 313, 5, 5);
		qipan.fillRect(193, 313, 5, 5);
		qipan.fillRect(313, 313, 5, 5);//Show nine stars in the score

		Graphics2D tu = (Graphics2D) qipan;
		tu.setStroke(new BasicStroke(3f));
		tu.drawLine(10, 10, 10, 400);
		tu.drawLine(10, 10, 400, 10);
		tu.drawLine(400, 10, 400, 400);
		tu.drawLine(10, 400, 400, 400);

		for (int i = 0; i < chessCount; i++) {
			chessList[i].draw(qipan);//Draw the pieces on the board
		}
		qipan.setFont(new Font("Bold", Font.BOLD, 15));
		qipan.drawString("Game Tips:" + message, 20, 420);//Show Text Tips
	}

	
	    public void againGame() {//Restart Game Action
		for (int i = 0; i < chessList.length; i++) {
			chessList[i] = null;
		}//Clear the position information of all the pieces on the board
		chessCount = 0;
		iso = false;
		message = "Please start";
		repaint();//Refresh Page Effect
	}

	public void huiqi() {//Chess repentance action
		if (iso) {
			return;
		}
		chessList[chessCount - 1] = null;//Clears the position information of the most recently played pieces on the board
		chessCount--;//When the position information of a chess piece is clear, the number of chess pieces (steps) is subtracted by one
		if (isBlack) {
			message = "White Chess Regret";
		} else {
			message = "Black Chess Regret";
		}
		isBlack = !isBlack;
		repaint();//Refresh interface effect
	}
}

5. Main program
Program Description
Used to play games.
package game;

import java.awt.BorderLayout;//Layout Manager
import java.awt.Button; //Button Component
import java.awt.Color;
import java.awt.Dimension;//This class encapsulates the width and height (integer precision) of a component in a single object. This class is associated with some properties of the component.
import java.awt.FlowLayout;//Components are arranged from left to right in the order in which they were added, one line full and the next starting with the set alignment
import java.awt.Font;//This class represents fonts that are used to render text in a visible manner. Fonts provide the information needed to map character sequences to font sequences and to render font sequences and objects.
import java.awt.GridLayout;//GridLayout Layout Layout Manager splits containers into vertically and horizontally split grids
import java.awt.event.ActionEvent;//Represents a semantic event that occurs when a component-specific action occurs, such as press. This advanced event is generated by the component (such as a). The event is passed to each object registered to receive such an event using the component method.
import java.awt.event.ActionListener;//ActionListener is an interface for event handling in Java
import java.awt.event.MouseAdapter;//Class for implementing MouseListener
import java.awt.event.MouseEvent;//Indicates an event in a component where a mouse action occurs

import javax.swing.JDialog;//The main class used to create the dialog window.
import javax.swing.JFrame;//Is the object of the window on the screen, which can be maximized, minimized and closed.
import javax.swing.JLabel;//You can display text, images, or both.
import javax.swing.JMenu;//Implement a pop-up window
import javax.swing.JMenuBar;//Create Menu Bar Object
import javax.swing.JMenuItem;//Classes that add content to menus
import javax.swing.JPanel;//A middle-tier container that holds components and groups them together, but it must itself be added to other containers for use.

public class GameMain extends JFrame {

	Chessboard qpan;

	public GameMain() {
		qpan = new Chessboard();
		JMenuBar menubar = new JMenuBar();// Create a menu

		JMenu menu = new JMenu("Game(G)"); 
		JMenuItem item1 = new JMenuItem("New Game");
		JMenuItem item2 = new JMenuItem("Sign out");//Add Text to Menu
		menu.add(item1);
		menu.addSeparator();//Creates a dividing line between menu items filled in the menu
		menu.add(item2);
		menubar.add(menu);//Add Menu to Menu Bar


		JPanel button = new JPanel();//A JPanel Object Representation Panel was created
		button.setBackground(Color.yellow);//Set background panel color
		button.setLayout(new GridLayout(5, 4));//Set Button Layout Size
		Button button1 = new Button("Reopen");
		Button button2 = new Button("Regret Chess");//Set button prompt
		button.add(button1);
		button.add(button2);//Apply Button
		BorderLayout bl = new BorderLayout();//create a window
		this.setTitle("Handsome Gobang");//Set window name
		this.setSize(480, 490);//Set window size
		this.setLocationRelativeTo(null);//Window Centered
		this.setVisible(true);//Allows the JVM to start drawing based on the data model and display it on the screen
		this.setResizable(true);//Set window size to change
		this.add(menubar, bl.NORTH);
		this.add(qpan, bl.CENTER);
		this.add(button, bl.EAST);//Menus are set on top of graphics, checkerboards are set in the middle of graphics, and buttons are set on the right side of graphics

		button1.addMouseListener(new MouseAdapter() {

			
			public void mouseClicked(MouseEvent a) {
				
				qpan.againGame();
			}//Call againGame action after clicking button1 button

		});
	    button2.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent b) {
				qpan.huiqi();
			}//After clicking the button2 button, call the huiqi action
			});

	     item1.addActionListener(new ActionListener() {
         
	    	 public void actionPerformed(ActionEvent c) {
				qpan.againGame();
			}
		});//Trigger againGame action after clicking item1

		
		item2.addActionListener(new ActionListener() {

		public void actionPerformed(ActionEvent d) {
				System.exit(0);
			}
		});//Trigger exit action after clicking item2

	}

	public static void main(String[] args) {
		
		new GameMain();
	}

Adjust program to change board color


Tags: Java Eclipse

Posted on Mon, 20 Sep 2021 04:14:29 -0400 by ltd