Author’s brief introduction

CSDN blog expert, engaged in software development for many years, proficient in Java, JavaScript, the blogger is also from scratch to learn and grow step by step, know the importance of learning and accumulation, like to fight with the majority of ADC upgrade, welcome your attention, look forward to learning, growth and take off with you!

rendering

Implementation approach

1. Create a run window and add a background color.

2. Draw the board. 3. Use two-dimensional array to control the minimum position of the child, drawing indicator. 4. Click the mouse in the lock-down position to lock-down. 5. Check to see if you have won the game. 6. The machine determines the next step and places the target. 7. The machine decides if it has won.

Code implementation

Create a window

First create a game form class GameFrame, inherit to JFrame, used to display on the screen (window object), each game has a window, set the window title, size, layout, etc.

/* * Game form class */
public class GameFrame extends JFrame {
	
	public GameFrame(a) {
		setTitle("Gobang");// Set the title
		setSize(620.670);// Set the size
		getContentPane().setBackground(new Color(209.146.17));// Add background color
		setLayout(new BorderLayout());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// Click the close button to close the program
        setLocationRelativeTo(null);   // Set to center
    	setResizable(false); // The interface size cannot be changed}}Copy the code

Create the panel container GamePanel to inherit from JPanel


import javax.swing.JFrame;
import javax.swing.JPanel;

/* * Canvas class */
public class GamePanel extends JPanel {
	private static final long serialVersionUID = 1L;
	GamePanel gamePanel=this;
	private JFrame mainFrame=null;
	
	// Initialize the related parameters in the constructor
	public GamePanel(JFrame frame){
		this.setLayout(null);
		this.setOpaque(false);
		mainFrame = frame;
		
		mainFrame.requestFocus();
		mainFrame.setVisible(true); }}Copy the code

Create a Main class to launch the window.

public class Main {
	/ / the main class
	public static void main(String[] args) {
		GameFrame frame = new GameFrame();
		GamePanel gamePanel = new GamePanel(frame);
		frame.add(gamePanel);
		frame.setVisible(true);// Set the display}}Copy the code

Right click to execute the Main class and the window is created

Create menus and menu options

Create a menu

private void  initMenu(a){
	// Create a menu and menu options
	jmb = new JMenuBar();
	JMenu jm1 = new JMenu("Game");
	jm1.setFont(new Font("Song Of song origin", Font.BOLD, 18));// Set the font displayed in the menu
	JMenu jm2 = new JMenu("Help");
	jm2.setFont(new Font("Song Of song origin", Font.BOLD, 18));// Set the font displayed in the menu
	
	JMenuItem jmi1 = new JMenuItem("Start a new game");
	JMenuItem jmi2 = new JMenuItem("Quit");
	jmi1.setFont(new Font("Song Of song origin", Font.BOLD, 18));
	jmi2.setFont(new Font("Song Of song origin", Font.BOLD, 18));
	
	JMenuItem jmi3 = new JMenuItem("Operation Instructions");
	jmi3.setFont(new Font("Song Of song origin", Font.BOLD, 18));
	JMenuItem jmi4 = new JMenuItem("Success/failure determination");
	jmi4.setFont(new Font("Song Of song origin", Font.BOLD, 18));
	
	jm1.add(jmi1);
	jm1.add(jmi2);
	
	jm2.add(jmi3);
	jm2.add(jmi4);
	
	jmb.add(jm1);
	jmb.add(jm2);
	mainFrame.setJMenuBar(jmb);// Put the menu Bar on the JFrame
	jmi1.addActionListener(this);
	jmi1.setActionCommand("Restart");
	jmi2.addActionListener(this);
	jmi2.setActionCommand("Exit");
	
	jmi3.addActionListener(this);
	jmi3.setActionCommand("help");
	jmi4.addActionListener(this);
	jmi4.setActionCommand("lost");
}
Copy the code

Implement ActionListener override method actionPerformed GamePanel is reporting an error. Override the actionPerformed method.

== Implementation of actionPerformed method ==

@Override
public void actionPerformed(ActionEvent e) {
	String command = e.getActionCommand();
	System.out.println(command);
	UIManager.put("OptionPane.buttonFont".new FontUIResource(new Font("Song Of song origin", Font.ITALIC, 18)));
	UIManager.put("OptionPane.messageFont".new FontUIResource(new Font("Song Of song origin", Font.ITALIC, 18)));
	if ("Exit".equals(command)) {
		Object[] options = { "Sure"."Cancel" };
		int response = JOptionPane.showOptionDialog(this."Are you sure you want to quit?"."",
				JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null,
				options, options[0]);
		if (response == 0) {
			System.exit(0); }}else if("Restart".equals(command)){
		if(!"end".equals(gamePanel.gameFlag)){
			JOptionPane.showMessageDialog(null."Unable to restart in game!"."Hint!, JOptionPane.INFORMATION_MESSAGE); 
		}else{
			if(gamePanel! =null) { gamePanel.restart(); }}}else if("help".equals(command)){
		JOptionPane.showMessageDialog(null."Mouse in the pointer position point, then the child!"."Hint!, JOptionPane.INFORMATION_MESSAGE);
	}else if("lost".equals(command)){
		JOptionPane.showMessageDialog(null."Wuzi lianzhu side wins!"."Hint!, JOptionPane.INFORMATION_MESSAGE); }}Copy the code

The GamePanel code is as follows:

package main;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;

/* * Canvas class */
public class GamePanel extends JPanel implements ActionListener{
	private static final long serialVersionUID = 1L;
	GamePanel gamePanel=this;
	private JFrame mainFrame=null;
	JMenuBar jmb=null;
	public String gameFlag="";
	
	// Initialize the related parameters in the constructor
	public GamePanel(JFrame frame){
		this.setLayout(null);
		this.setOpaque(false);
		mainFrame = frame;
		
		// Create button
		initMenu();
		
		mainFrame.requestFocus();
		mainFrame.setVisible(true);
	}
	
	private void  initMenu(a){
		// Create a menu and menu options
		jmb = new JMenuBar();
		JMenu jm1 = new JMenu("Game");
		jm1.setFont(new Font("Song Of song origin", Font.BOLD, 18));// Set the font displayed in the menu
		JMenu jm2 = new JMenu("Help");
		jm2.setFont(new Font("Song Of song origin", Font.BOLD, 18));// Set the font displayed in the menu
		
		JMenuItem jmi1 = new JMenuItem("Start a new game");
		JMenuItem jmi2 = new JMenuItem("Quit");
		jmi1.setFont(new Font("Song Of song origin", Font.BOLD, 18));
		jmi2.setFont(new Font("Song Of song origin", Font.BOLD, 18));
		
		JMenuItem jmi3 = new JMenuItem("Operation Instructions");
		jmi3.setFont(new Font("Song Of song origin", Font.BOLD, 18));
		JMenuItem jmi4 = new JMenuItem("Success/failure determination");
		jmi4.setFont(new Font("Song Of song origin", Font.BOLD, 18));
		
		jm1.add(jmi1);
		jm1.add(jmi2);
		
		jm2.add(jmi3);
		jm2.add(jmi4);
		
		jmb.add(jm1);
		jmb.add(jm2);
		mainFrame.setJMenuBar(jmb);// Put the menu Bar on the JFrame
		jmi1.addActionListener(this);
		jmi1.setActionCommand("Restart");
		jmi2.addActionListener(this);
		jmi2.setActionCommand("Exit");
		
		jmi3.addActionListener(this);
		jmi3.setActionCommand("help");
		jmi4.addActionListener(this);
		jmi4.setActionCommand("lost");
	}
	
	// Start over
	public void restart(a) {
		// Game start flag
		gameFlag="start";
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		System.out.println(command);
		UIManager.put("OptionPane.buttonFont".new FontUIResource(new Font("Song Of song origin", Font.ITALIC, 18)));
		UIManager.put("OptionPane.messageFont".new FontUIResource(new Font("Song Of song origin", Font.ITALIC, 18)));
		if ("Exit".equals(command)) {
			Object[] options = { "Sure"."Cancel" };
			int response = JOptionPane.showOptionDialog(this."Are you sure you want to quit?"."",
					JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null,
					options, options[0]);
			if (response == 0) {
				System.exit(0); }}else if("Restart".equals(command)){
			if(!"end".equals(gamePanel.gameFlag)){
				JOptionPane.showMessageDialog(null."Unable to restart in game!"."Hint!, JOptionPane.INFORMATION_MESSAGE); 
			}else{
				if(gamePanel! =null) { gamePanel.restart(); }}}else if("help".equals(command)){
			JOptionPane.showMessageDialog(null."Mouse in the pointer position point, then the child!"."Hint!, JOptionPane.INFORMATION_MESSAGE);
		}else if("lost".equals(command)){
			JOptionPane.showMessageDialog(null."Wuzi lianzhu side wins!"."Hint!, JOptionPane.INFORMATION_MESSAGE); }}}Copy the code

Run the

Drawing board

Rewrite the paint method

@Override
public void paint(java.awt.Graphics g) {
	super.paint(g);
}
Copy the code

Define 15 rows and 15 columns for the lines that connect the horizontal and vertical lines

public static final int ROWS=15;
public static final int COLS=15;
Copy the code

Draw a grid

// Draw the grid
private void drawGrid(Graphics g) {
	Graphics2D g_2d=(Graphics2D)g;
	int start=26;
	int x1=start;
	int y1=20;
	int x2=586;
	int y2=20;
	for (int i = 0; i < ROWS; i++) {
		y1 = start + 40*i;
		y2 = y1;
		g_2d.drawLine(x1, y1, x2, y2);		
	}
	
	y1=start;
	y2=586;
	for (int i = 0; i < COLS; i++) {
		x1 = start + 40*i; x2 = x1; g_2d.drawLine(x1, y1, x2, y2); }}Copy the code

Draw 5 dots

// Draw 5 black dots
private void draw5Point(Graphics g) {
	// first point
	g.fillArc(142.142.8.8.0.360);
	// Point 2
	g.fillArc(462.142.8.8.0.360);
	
	// The third point
	g.fillArc(142.462.8.8.0.360);
	// Point 4
	g.fillArc(462.462.8.8.0.360);
	
	/ / center
	g.fillArc(302.302.8.8.0.360);
}
Copy the code

Call the above two methods inside the paint method

@Override
public void paint(java.awt.Graphics g) {
	super.paint(g);
	// Draw the grid
	drawGrid(g);
	// Draw 5 black dots
	draw5Point(g);
}
Copy the code

The board has been drawn

Implement drop indicator

  1. Creating the indicator class
package main;

import java.awt.Color;
import java.awt.Graphics;

// Indicator class
public class Pointer {
	private int i=0;// two dimensional subscript I
	private int j=0;// two-dimensional subscript j
	private int x=0;/ / coordinates X
	private int y=0;/ / Y coordinate
	private GamePanel panel=null;
	private Color color=null;
	private int h=40;// Indicates the size
	private boolean isShow=false;// Whether to display
	private int qizi = 0 ;// Chess type 0: none 1: white 2: black
	
	public Pointer(int x,int y,int i,int j,Color color,GamePanel panel){
		this.x=x;
		this.y=y;
		this.i=i;
		this.j=j;
		this.panel=panel;
		this.color=color;
	}
	/ / to draw
	void draw(Graphics g){
		Color oColor = g.getColor();
		if(color! =null){
			g.setColor(color);
		}
		if(isShow){
			// Draw the indicator
			g.drawRect(x-h/2, y-h/2, h, h);
		}
		if(color! =null) {// Go back to colorg.setColor(oColor); }}// Check whether the mouse is within the pointer range
	boolean isPoint(int x,int y){
		// Coordinates greater than the upper left corner and less than the lower right corner are definitely in range
		if(x>this.x-h/2 && y >this.y-h/2
			&& x<this.x+h/2 && y <this.y+h/2) {return  true;
		}
		return false;
	}
	public boolean isShow(a) {
		return isShow;
	}
	public void setShow(boolean isShow) {
		this.isShow = isShow;
	}
	public int getQizi(a) {
		return qizi;
	}
	public void setQizi(int qizi) {
		this.qizi = qizi;
	}
	public int getX(a) {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY(a) {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	public int getI(a) {
		return i;
	}
	public void setI(int i) {
		this.i = i;
	}
	public int getJ(a) {
		return j;
	}
	public void setJ(int j) {
		this.j = j; }}Copy the code
  1. Initialize a two-dimensional array
public Pointer points[][] =  new Pointer[ROWS][COLS];
Copy the code
  1. Create indicator instance objects
// Create a two-dimensional array
private void createArr(a) {
	int x=0,y=0;
	for (int i = 0; i < ROWS; i++) {
		for (int j = 0; j < COLS; j++) {
			y = 26 + 40*i;
			x = 26 + 40*j;
			Pointer pointer = new Pointer(x, y, i,j,new Color(255.0.0), this); points[i][j] = pointer; }}}Copy the code
  1. Initial call
// Initialize the related objects
private void init(a) {
	createArr();
	// Game start flag
	gameFlag="start";
}
Copy the code

Init method is also called in GamePanel constructor.

  1. The paint method traverses a two-dimensional array and draws.
@Override
public void paint(java.awt.Graphics g) {
	super.paint(g);
	// Draw the grid
	drawGrid(g);
	// Draw 5 black dots
	draw5Point(g);
	// Draw the indicator
	Pointer pointer = null;
	for (int i = 0; i < ROWS; i++) {
		for (int j = 0; j < COLS; j++) {
			pointer = points[i][j] ;
			if(pointer! =null){ pointer.draw(g); }}}}Copy the code

Run the following

But this indicator box is not what we want and needs to be changed

  1. Modify the drawing code for the indicator class

Add a new method to the Pointer method and call it when the indicator is drawn instead of drawRect.

private void drawPointer(Graphics g) {
	
	Graphics2D g2 = (Graphics2D)g;  //g is the Graphics object
	g2.setStroke(new BasicStroke(2.0 f));

	/* * 1. Count the four vertices * 2. Draw two lines from each vertex in turn */
	
	/ / the top left corner
	int x1 = x-h/2;
	int y1 = y-h/2;
	// Draw lines to the right
	int x2 = x1+1*h/4;
	int y2 = y1;
	g2.drawLine(x1, y1, x2, y2);
	
	// Draw a line down
	x2 = x1;
	y2 = y1+1*h/4;
	g2.drawLine(x1, y1, x2, y2);
	
	/ / the top right corner
	x1 = x+h/2;
	y1 = y-h/2;
	// Draw lines to the left
	x2 = x1-1*h/4;
	y2 = y1;
	g2.drawLine(x1, y1, x2, y2);
	
	// Draw a line down
	x2 = x1;
	y2 = y1+1*h/4;
	g2.drawLine(x1, y1, x2, y2);
	
	/ / the bottom right hand corner
	x1 = x+h/2;
	y1 = y+h/2;
	// Draw lines to the left
	x2 = x1-1*h/4;
	y2 = y1;
	g2.drawLine(x1, y1, x2, y2);
	
	// Draw the line up
	x2 = x1;
	y2 = y1-1*h/4;
	g2.drawLine(x1, y1, x2, y2);
	
	/ / the bottom left corner
	x1 = x-h/2;
	y1 = y+h/2;
	// Draw lines to the right
	x2 = x1+1*h/4;
	y2 = y1;
	g2.drawLine(x1, y1, x2, y2);
	
	// Draw the line up
	x2 = x1;
	y2 = y1-1*h/4;
	g2.drawLine(x1, y1, x2, y2);
}
Copy the code

Run again

Move later

  1. Create the ImageValue load class
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageValue {
    public static BufferedImage whiteQiziImage  ;
    
    public static BufferedImage blackQiziImage  ;
    / / path
    public static String ImagePath = "/images/";
    // Initialize the image
    public static void init(a){
    	String whitePath = ImagePath +"white.png";
    	String blackPath = ImagePath +"black.png";
    	try {
			whiteQiziImage = ImageIO.read(ImageValue.class.getResource(whitePath));
			blackQiziImage = ImageIO.read(ImageValue.class.getResource(blackPath));
		} catch(IOException e) { e.printStackTrace(); }}}Copy the code
  1. Creating a subclass

import java.awt.Color;
import java.awt.Graphics;
import common.ImageValue;

public class Qizi {

	private int x = 0;
	private int y = 0;
	private int r = 36;
	private GamePanel panel = null;
	private Color color = null;
	private int type = 1;// Pawn type 1: white 2: black

	public Qizi(int x, int y, int type, GamePanel panel) {
		this.x = x;
		this.y = y;
		this.panel = panel;
		this.type=type;
	}

	/ / to draw
	void draw(Graphics g) {
		Color oColor = g.getColor();
		if (type == 1) {/ / white
			g.drawImage(ImageValue.whiteQiziImage, x - r / 2, y - r / 2,r,r, null);
		} else {/ / black
			g.drawImage(ImageValue.blackQiziImage, x - r / 2, y - r / 2,r,r, null);
		}

		if(color ! =null) {// Go back to colorg.setColor(oColor); }}public int getType(a) {
		return type;
	}

	public void setType(int type) {
		this.type = type; }}Copy the code
  1. Overwrite mouseClicked in the createMouseListener method to create the pieces
@Override
public void mouseClicked(MouseEvent e) {
	// Click in the appropriate position to carry out the operation
	if(!"start".equals(gameFlag)) return ;
	
	int x = e.getX();
	int y = e.getY();
	
	Pointer pointer;
	for (int i = 0; i <ROWS; i++) {
		for (int j = 0; j < COLS; j++) {
			pointer = points[i][j];
			if(pointer==null)continue;
			// If it is clicked, and there is no chess piece, it can be played
			if(pointer.isPoint(x, y) && pointer.getQizi()==0){
				Qizi qizi = new Qizi(pointer.getX(), pointer.getY(), 2, gamePanel);
				pointer.setQizi(2);
				qizis.add(qizi);
			    // Re-paint the cloth
				repaint();
				return; }}}}Copy the code
  1. Draw the pieces in the paint method
@Override
public void paint(java.awt.Graphics g) {
	super.paint(g);
	// Draw the grid
	drawGrid(g);
	// Draw 5 black dots
	draw5Point(g);
	// Draw the indicator
	Pointer pointer = null;
	for (int i = 0; i < ROWS; i++) {
		for (int j = 0; j < COLS; j++) {
			pointer = points[i][j] ;
			if(pointer! =null){ pointer.draw(g); }}}// Draw the chess pieces
	Qizi qizi=null;
	for (int i = 0; i < qizis.size(); i++) { qizi = (Qizi)qizis.get(i); qizi.draw(g); }}Copy the code

Added computer AI

  1. Create AI class
  2. Create static method next
  3. Create static method has5 (joined into 5 children)
public class AI {
	//AI goes to the next step
	static void next(GamePanel gamePanel){}// Make sure that you have a good time
	static boolean has5(Pointer pointer1,GamePanel gamePanel){
		
		return false; }}Copy the code
  1. After you have scored, the has5 method is executed to determine the direction of the game based on the return
  2. Has5 returns true if you win, otherwise the AI will make a move

Modify the code in the mouseClicked just now

@Override
public void mouseClicked(MouseEvent e) {
	// Click in the appropriate position to carry out the operation
	if(!"start".equals(gameFlag)) return ;
	
	int x = e.getX();
	int y = e.getY();
	
	Pointer pointer;
	for (int i = 0; i <ROWS; i++) {
		for (int j = 0; j < COLS; j++) {
			pointer = points[i][j];
			if(pointer==null)continue;
			// If it is clicked, and there is no chess piece, it can be played
			if(pointer.isPoint(x, y) && pointer.getQizi()==0){
				Qizi qizi = new Qizi(pointer.getX(), pointer.getY(), 2, gamePanel);
				pointer.setQizi(2);
				qizis.add(qizi);
				// Re-paint the cloth
				repaint();
				// Check whether there are five zi lianzhu
				if(AI.has5(pointer, gamePanel)){
					gamePanel.gameWin();
				}else{
					AI.next(gamePanel);
				}
				return; }}}}Copy the code
  1. Random placement in AI class

– Randomly get subscripts I and j. – Retrieves an indicator object from a two-dimensional array by subscript. – If this indicator is occupied, it is randomized again (recursively) until the indicator object is correctly retrieved. – At this indicator location, create a pawn object and update the indicator’s pawn information. – Adds the last attribute to class Qizi, indicating the last piece played by AI. – Create a small red square in the corresponding position according to last to mark the last piece of AI.

// Random drop
static boolean luoziRandom(GamePanel gamePanel){
	
	Pointer pointer = getRandomPointer(gamePanel);
	
	luozi(pointer, gamePanel,1);
	
	return true;
}

// Get random pieces
static Pointer getRandomPointer(GamePanel gamePanel){
	Random random = new Random();
	int i = random.nextInt(gamePanel.ROWS);
	int j = random.nextInt(gamePanel.COLS);
	// Get a random grid
	Pointer pointer = gamePanel.points[i][j];
	if(pointer.getQizi()! =0) {// If there are already chess pieces in the current grid, recursively pick them again
		pointer = getRandomPointer(gamePanel);
	}
	return pointer;
}

//AI drop the child operation
static void luozi(Pointer pointer,GamePanel gamePanel,int type){
	if(pointer.getQizi()==0) {// If there are no pieces, the game is played
		Qizi qizi = new Qizi(pointer.getX(), pointer.getY(), type, gamePanel);
		qizi.setLast(true);
		pointer.setQizi(type);
		gamePanel.qizis.add(qizi);
		
		// Re-paint the cloth
		gamePanel.repaint();
		
		// Check whether the computer has a case of wuzi lianzhu
		if(AI.has5(pointer, gamePanel)){ gamePanel.gameOver(); }}}Copy the code
  1. AI’s next method calls a random drop
//AI goes to the next step
	static void next(GamePanel gamePanel){
		luoziRandom(gamePanel);
	}
Copy the code

Operation effect:

  1. The little red block keeps changing the code

Just clear the other little red squares before you hit the ball

// Clears the last checker indicator of the computer checker
private void clearAILast(a) {
	Qizi qizi;
	for (int i = 0; i < qizis.size(); i++) {
		qizi = (Qizi)qizis.get(i);
		if(qizi! =null && qizi.getType()==1){
			qizi.setLast(false); }}}Copy the code

AI algorithms

The four directions of the pieces

  • The transverse

  • The vertical

  • The right si

  • Left off

Weight points

Description: Calculate the score, the highest score to determine the next piece.

Left open: that is to say, left can fall son right open: right can fall son

Related definitions of sub-3 (similar to sub-4 and sub-5)

What is three pieces left, so there are two pieces, and the next piece can go to the left

3 pieces can only be placed in the middle, the picture shows:

Three to the right is to the right

Only fractions with more than three children are counted

type Three sons left open 3 the son 3 the son right away
score 32 30 31
type 4 left open 4 children 4 the son right away
score 42 40 41
type Five son left open Five son Five son right away
score 52 50 51

As can be seen from the above table, the order of weights is 5>4>3, and at the same time: left > right > middle.

Calculate the horizontal weight score

  1. Judge from left to right

* The horizontal subscript I is the same, and the cycle starts at the current position j plus 1. * Counter +1 when it encounters a child that is the same as the current child. * Exit the loop when encountering something different, which means blocking. * If a hole is encountered, the first time the counter +1, the second time out of the loop. * Determine the state of left and right open. * According to the counter and left and right on state, calculate the score

  1. Judge from right to left

* The horizontal subscript I is the same, and the cycle starts at the current position j minus 1. * Counter +1 when it encounters a child that is the same as the current child. * Exit the loop when encountering something different, which means blocking. * If a hole is encountered, the first time the counter +1, the second time out of the loop. * Determine the state of left and right open. * According to the counter, left and right on state, calculate the score and the position of the pin.

In fact, the left and right are very similar

static Data getData(Pointer pointer,int dir,int type,GamePanel gamePanel){
	Pointer[][] points = gamePanel.points;
	int i = pointer.getI();
	int j = pointer.getJ();
	
	Data resData = new Data();
	Pointer tempPointer;
	int num=1;// The default is 1, because it is itself a child.
	int num2=1;// The default value is 1, used to add up the number of consecutive pieces
	int breakNum=0;// The default value is 0.
	
	boolean lClosed=false;// Whether the left side is closed
	boolean rClosed=false;// Whether to close the right side
	if(dir==1) {/ / lateral
		// loop right to determine how many consecutive chess pieces can be the same as the current pointer.
		if(type==1) {for (int k = j+1; k < gamePanel.COLS; k++) {
				tempPointer = points[i][k];
				if(tempPointer.getQizi()==pointer.getQizi()){/ / continuous
					num++;
					num2++;
					if(k == gamePanel.COLS-1) {// If the last child is also continuous, it is also right-closed
						rClosed = true; }}else if(tempPointer.getQizi()==0) {/ / blank
					if(breakNum==1) {// One can't pass
						if(points[i][k-1].getQizi()==0) {// If the previous one is empty, set it not to interrupt
							breakNum=0;
						}else{
							breakNum=2;
						}
						break;
					}
					breakNum=1;
					num++;
					// Is the kind of interrupt, here set the location of the child
					resData.setI(i);
					resData.setJ(k);
				}else{// Close the object right
					rClosed = true;
					break; }}// Check whether the left is closed
			if(j==0) {// The current child is the left-most child
				lClosed = true;
			}else{
				tempPointer = points[i][j-1];
				if(tempPointer.getQizi()! =0) {// Left closed if there are children to the left of the current child
					lClosed = true; }}}else{// From right to left
			for (int k = j-1; k >=0; k--) {
				tempPointer = points[i][k];
				if(tempPointer.getQizi()==pointer.getQizi()){/ / continuous
					num++;
					num2++;
					if(k == 0) {// If the last child is also continuous, it is also left closed
						lClosed = true; }}else if(tempPointer.getQizi()==0) {/ / blank
					if(breakNum==1) {// One can't pass.
						if(points[i][k+1].getQizi()==0) {// If the previous one is empty, set it not to interrupt
							breakNum=0;
						}else{
							breakNum=2;
						}
						break;
					}
					breakNum=1;
					num++;
					// Is the kind of interrupt, here set the location of the child
					resData.setI(i);
					resData.setJ(k);
				}else{// Close the opposition left
					lClosed = true;
					break; }}// Determine whether to close right
			if(j==gamePanel.COLS-1) {// The current child is the rightmost child
				rClosed = true;
			}else{
				tempPointer = points[i][j+1];
				if(tempPointer.getQizi()! =0) {// Close right if there are children to the right of the current child
					rClosed = true;
				}
			}
		}
	}
	setCount(resData, i, j, dir, type, num,num2, breakNum, lClosed, rClosed);
	
	return resData;
}

// Calculate and set the score
static void setCount(Data data,int i,int j,int dir,int type,
		int num,int num2,int breakNum,boolean lClosed,boolean rClosed){
	int count=0;
	if(num>2) {// More than 3 pieces in a row
		if(num==3) {// Set the default score
			count=30;
		}else if(num==4){
			count=40;
		}else if(num==5){
			count=50;
		}
		if(num2>=5&&breakNum==0) {// It is used to determine whether there are five children or more
			count=100;
			// Set the weight score
			data.setCount(count);
			return ;
		}
		if(breakNum==0) {// If it is not the interrupted kind
			if(lClosed&&rClosed){// If there is no break, and both left and right are closed, the score is -1, -1 means that the chip should be filtered
				count = -1;
			}else if(! lClosed){// The left side is not closed if the type is interrupted
				count+=2;/ / add two points
				if(dir==1) {if(type==1){
						data.setI(i);
						data.setJ(j-1);
					}else{
						data.setI(i);
						data.setJ(j-num+1); }}else if(dir==2) {if(type==1){
						data.setI(i-1);
						data.setJ(j);
					}else{
						data.setI(i-num+1); data.setJ(j); }}else if(dir==3) {if(type==1){
						data.setI(i-1);
						data.setJ(j-1);
					}else{
						data.setI(i-num+1);
						data.setJ(j-num+1); }}else if(dir==4) {if(type==1){
						data.setI(i+1);
						data.setJ(j-1);
					}else{
						data.setI(i+num-1);
						data.setJ(j-num+1); }}}else if(! rClosed){// If it is interrupted, the right side is not closed
				count+=1;/ / add one point
				if(dir==1) {if(type==1){
						data.setI(i);
						data.setJ(j+num-1);
					}else{
						data.setI(i);
						data.setJ(j+1); }}else if(dir==2) {if(type==1){
						data.setI(i+num-1);
						data.setJ(j);
					}else{
						data.setI(i+1); data.setJ(j); }}else if(dir==3) {if(type==1){
						data.setI(i+num-1);
						data.setJ(j+num-1);
					}else{
						data.setI(i+1);
						data.setJ(j+1); }}else if(dir==4) {if(type==1){
						data.setI(i-num+1);
						data.setJ(j+num-1);
					}else{
						data.setI(i-1);
						data.setJ(j+1); }}}}else{// If it interrupts,
			if(num! =5) {//num is not 5, and both left and right are closed
				if(lClosed&&rClosed){
					count = -1; }}}// Set the weight scoredata.setCount(count); }}Copy the code

AI drop processing

– Select horizontal, vertical, right, and left fractions and place them in List – sort the set (from highest to bottom) – select the first fraction value as the next drop – drop operation (if the set has no value, randomly drop)

// Proceed to the next step
static boolean go(GamePanel gamePanel){
	
	List<Data> datas=new ArrayList<Data>();
	// Loop to find black and determine if there are 4 pieces in this piece: 1 horizontal, 2 vertical, 3 right, and 4 left.
	Pointer pointer;
	for (int i = 0; i <gamePanel.ROWS; i++) {
		for (int j = 0; j < gamePanel.COLS; j++) {
			pointer = gamePanel.points[i][j];
			if(pointer==null)continue;
			if(pointer.getQizi()==0) {// Skip if there are no pieces
				continue;
			}
			// Loop in 4 directions
			int dir=1;
			for (int k = 1; k <= 4; k++) {
				dir = k;
				Data data = getData(pointer, dir,1, gamePanel);
				if(data.getCount()! = -1&&data.getCount()! =0) {// filter out 0 and -1
					datas.add(data);
				}
				data = getData(pointer, dir, 2,gamePanel);
				if(data.getCount()! = -1&&data.getCount()! =0) {// filter out 0 and -1datas.add(data); }}}}// Sort by weight, from large to small
	Collections.sort(datas, new DataCount());
	
	/*for (int i = 0; i < datas.size(); i++) { System.out.println("----------"+datas.get(i).getCount()); } * /
	if(datas.size()>0) {// take the first position
		Data data = datas.get(0);
		Pointer p = gamePanel.points[data.getI()][data.getJ()];
		luozi(p, gamePanel, 1);
		return true;
	}
	
	return false;
}
Copy the code

Five pieces or more is easy to judge, when the pieces are consecutive and the counter is greater than 5 success!

This is only the horizontal case, the other three cases are similar, just pay attention to the subscript processing.

The last

1. AI is not particularly intelligent, it should be a simple version, not difficult to win. There may be some bugs I haven’t found, please understand!

See here big guy, move rich little hands [praise], can [concern] a wave of better.

Code acquisition method:

Add my wechat: QQ283582761