Java implementation of Gobang games

#Foreword

When I was learning the C language, I played a small game of Gobang. Recently I began to learn Java. I wondered if I could re implement the previous practice in Java. Now that I have this idea, I'll start to take action ~.

In the process of rewriting, we can feel some differences between process oriented language and object-oriented language. What bothers me most is the design of classes. I feel that we need to consider not only the implementation of functions, but also the logical relationship between classes. The function of functions is single, but there is no relationship between functions. If you want to use me, you can use it and pull it down without using it. When designing a class, you need to consider which methods are encapsulated in which class. The encapsulation position is inappropriate. Although it may also implement functions, it always feels strange. In fact, my final code is written according to the design idea of C, but some of its contents are abstracted into classes, and then the corresponding methods are encapsulated in them.

Introduction to Sanzi chess

Sanziqi is a kind of black and white chess. Sanzi chess is a traditional folk game, also known as Jiugong chess, circle fork, one dragon, Jingzi chess, etc. Connect the diagonals of the square and put three pieces on the opposite sides in turn. As long as you walk your three pieces into a line, the other party will lose. However, there are many times when there is a draw.

Three gobang rules

The player and the computer alternately drop a piece on the chessboard until one side wins or draws, then the game ends.

When three pieces in the same row, column or diagonal on the chessboard are the same, the party to which the pieces belong wins.

When the chessboard is full and there is no winner, there is a draw.

Concrete implementation

Test class

It is used to test the functions of the program, including the running logic of the program

public class BoardTest {
    public static void main(String[] args) {

        while(true){
            showMenu();  // Display chessboard
            boolean isPlay = Utility.readMenuSelection();   // Read player input
            if(isPlay){  // isPlay == true enter the game
                System.out.println("Welcome to the Gobang game!");
                Board board = new Board();      // Create a checkerboard object
                Player player = new Player();   // Create player object
                Computer computer = new Computer(); // Create computer object
                board.initBoard();  // Initialize chessboard
                char flag = ' ';    // Receive the return value of chess game judgment
                // Game process
                while(true){
                    board.showBoard();  // Display chessboard
                    System.out.print("Please enter the drop point(x,y):>");
                    player.moveChess(board);   // Player go
                    flag = board.isWin();
                    if(flag != 'c'){  // Pass in the player's and computer's pieces to judge the form of the current chess game
                        break;   // != ' c 'jumps out of the loop
                    }
                    computer.moveChess(board); // Computer walk
                    flag = board.isWin();
                    if(flag != 'c'){  // Pass in the player's and computer's pieces to judge the form of the current chess game
                        break;   // != ' c 'jumps out of the loop
                    }
                }
                if(flag == player.getChess()){
                    System.out.println("Players win!");
                } else if (flag == computer.getChess()){
                    System.out.println("Computer wins!");
                } else {
                    System.out.println("it ends in a draw!");
                }
            } else {    // Otherwise, confirm again whether the player wants to leave
                System.out.println("Are you really leaving?(Y/N):");
                boolean isExit = Utility.readConfirmSelection();  // Read player input
                if(isExit){  // isExit == true quit the game
                    System.out.println("Exit succeeded!");
                    break;
                }
            }
        }

    }

    // Game menu
    public static void showMenu(){
        System.out.println("============================================");
        System.out.println("==========        1. play        ===========");
        System.out.println("==========        2. exit        ===========");
        System.out.println("============================================");
        System.out.print("Please enter a selection:>");
    }
}

chessboard

Overview of attribute methods

// Properties:
private int row; // that 's ok
private int col; // column
private char[][] board; // Chessboard array

// method:
public void initBoard() {...} // Used to initialize the chessboard. Each element in the two-dimensional array of the chessboard is assigned as' '
public void showBoard() {...} // Used to display the chessboard
public char isWin() {...}     // Judge the current chess situation
private boolean isFull(){...} // Judge whether the chessboard is full
// getter method, because the chessboard property is not allowed to be set, there is no setter method
public int getRow() {...}    // Return row
public int getCol() {...}    // Return column
public char[][] getBoard() {...}  // Return chessboard array
// constructor 
public Board() {...} // Null parameter constructor, in which rows and columns are set by default, and the checkerboard array object is new

Complete code

public class Board {
    private int row; // that 's ok
    private int col; // column
    private char[][] board; // Chessboard array

    /**
     * @description:  Constructor to set the size of the chessboard
     * @parameter row, Indicates the number of rows; col, indicating the number of columns
     */
    public Board() {
        row = 3;
        col = 3;
        board = new char[row][col];
    }

    /**
     * @description: Used to initialize the chessboard. Each element in the two-dimensional array of the chessboard is assigned as' '
     */
    public void initBoard() {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                board[i][j] = ' ';
            }
        }
    }

    /**
     * @description: Used to display the chessboard
     */
    public void showBoard() {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (j < col - 1) {
                    System.out.print(" " + board[i][j] + " |");
                } else {
                    System.out.print(" " + board[i][j] + " ");
                }
            }
            System.out.println();
            if (i < row - 1) {
                for (int k = 0; k < col; k++) {
                    if (k < col - 1) {
                        System.out.print("---|");
                    } else {
                        System.out.print("---");
                    }
                }
                System.out.println();
            }
        }
    }

    /**
     * @description Judge the current chess situation
     * @return Return the player's pieces, the player wins, return the computer's pieces, and the computer wins
     * Return to 'q' draw, return to 'c' to continue
     */
    public char isWin() {
        // Judge whether the same line is the same
        for (int i = 0; i < row; i++) {
            if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') {
                return board[i][0];  // Returns a piece of the line
            }
        }
        // Judge whether the same column is the same
        for(int i = 0; i < col; i++){
            if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') {
                return board[i][0];  // Returns a piece of the column
            }
        }
        // Determine whether the diagonals are the same
        if(board[0][0] == board[1][1] && board[1][1]  == board[2][2] && board[0][0] != ' ' || board[0][2] == board[1][1] && board[1][1] ==  board[2][0] && board[0][2] != ' '){
            return board[1][1];        // Returns the piece in the middle of the diagonal
        }

        // Judge whether the chessboard is full
        if(isFull()){
            return 'q';  // Full return 'q'
        } else {
            return 'c';  // Under full return 'c'
        }
    }

    /**
     * @description Judge whether the chessboard is full
     * @return true Indicates full. false indicates not full
     */
    private boolean isFull(){
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if(board[i][j] == ' '){
                    return false;  // false if not full
                }
            }
        }
        return true; // Return true when full
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

    public char[][] getBoard() {
        return board;
    }
}

User class

Overview of attribute methods

// Properties:
private char chess;  // Player's chess pieces
// method:
public void moveChess(Board board){...} // Players play chess and put the pieces in the designated position
// getter method
public char getChess() {...} // Used to return the player's pieces
// Constructor:
public Player() {...} // Null parameter constructor, which sets the character representing the player's chess pieces by default

Complete code

public class Player {
    private char chess;  // piece

    /**
     * @description Null parameter constructor, which is used to set the user's chess pieces
     */
    public Player() {
        chess = '*';
    }

    /**
     * @description Players play chess and put the pieces in the designated position
     * @param board Receive checkerboard array used
     */
    public void moveChess(Board board){
        Scanner sc = new Scanner(System.in);
        while(true){
            int x = sc.nextInt(); // Receive x coordinate
            int y = sc.nextInt(); // Receive y coordinate
            boolean isFlag = Utility.readPosition(x,y,board); // Determine whether the position is appropriate
            if(isFlag){ // If appropriate, store the player's pieces in the corresponding position on the chessboard
                board.getBoard()[x-1][y-1] = chess; 
                return;
            }
            System.out.print("Input error, please re-enter:>");
        }
    }

    /**
     * @return Returns the player's pieces
     */
    public char getChess() {
        return chess;
    }
}

Computer

Overview of attribute methods

// Properties:
private char chess;  // Computer chess pieces
// method:
public void moveChess(Board board){...} // When playing chess on the computer, put a piece in a random position on the chessboard
// getter method:
public char getChess() {...}  // Return to the computer's chess pieces
// Constructor:
public Computer() {...}   // Empty parameter structure. The characters representing computer chess pieces are set by default

Complete code

import java.util.Scanner;

public class Computer {
    private char chess;  // Computer chess pieces

    /**
     * @description Chess pieces used to set up the computer
     */
    public Computer() {
        chess = '#';
    }

    /**
     * @description   Put a piece in a random position on the chessboard
     * @param board   Receive checkerboard array used
     */
    public void moveChess(Board board){
        Scanner sc = new Scanner(System.in);
        while(true){
            int x = (int)(Math.random() * 3);
            int y = (int)(Math.random() * 3);
            boolean isFlag = Utility.readPosition(x+1,y+1,board);
            if(isFlag){
                board.getBoard()[x][y] = chess;
                return;
            }
        }

    }

    /**
     *
     * @return Return to the computer's chess pieces
     */
    public char getChess() {
        return chess;
    }
}

Tool class

The static method is provided, which is mainly used to receive the player's input and judge whether the input is appropriate.

Overview of attribute methods

// method 
public static boolean readMenuSelection() {...} // Read the input options of the player entering the menu interface and judge.
public static boolean readConfirmSelection() {...} // Read the input of player confirmation option, 'Y' means confirmation and 'N' means denial
public static boolean readPosition(int x, int y, Board board){...} // Judge whether the X and Y coordinates entered by the player are reasonable. The reasonable position returns true and the unreasonable position returns false

Complete code

import java.util.Scanner;

public class Utility {
    /**
     * @description:  Read the number entered by the user and make judgment
     * @return Enter 1 to return true, and enter 2 to return false
     */
    public static boolean readMenuSelection() {
        int num = new Scanner(System.in).nextInt();
        while (true) {
            if (num == 1) {
                return true;
            } else if (num == 2) {
                return false;
            } else {
                System.out.print("Input error, please re-enter:>");
            }
        }
    }

    /**
     * @description:  Read the characters entered by the user and make a judgment
     * @return Enter 'Y' to return true, and enter 'N' to return false
     */
    public static boolean readConfirmSelection() {
        String str = new Scanner(System.in).next();
        while(true){
            if(str.length() == 1){
                char ch = str.toUpperCase().charAt(0);  // Get this character
                System.out.println(ch);
                if(ch == 'Y'){
                    return true;
                } else if( ch == 'N'){
                    return false;
                }
            }
            System.out.print("Input error, please re-enter:>");
        }
    }

    /**
     * @description Judge whether the drop point entered by the user is in a reasonable position
     * @param x x coordinate
     * @param y y coordinate
     * @param board Checkerboard object used
     * @return Return true for reasonable position and false for unreasonable position
     */
    public static boolean readPosition(int x, int y, Board board){
        if(1 <= x && x <= board.getRow() && 1 <= y && y <= board.getCol() && board.getBoard()[x - 1][y - 1] == ' '){
            return true;
        }
        return false;
    }
}

Keywords: Java

Added by jllydgnt on Wed, 12 Jan 2022 09:32:43 +0200