Script: Implement backgammon in python

1. Language

Python

No environment configuration, no library installation.

2. Effect

Take the first round as an example

PlayerX

Insert image description here

Player 0

Insert image description here

3. Script

class GomokuGame:
    def __init__(self, board_size=15):
        self.board_size = board_size
        self.board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
        self.current_player = 'X'
        self.winner = None
 
    def print_board(self):
        print("  " + " ".join(str(i) for i in range(self.board_size)))
        for i in range(self.board_size):
            print(str(i) + " " + " ".join(self.board[i]))
        print()
 
    def make_move(self, row, col):
        if self.board[row][col] == ' ':
            self.board[row][col] = self.current_player
            if self.check_winner(row, col):
                self.winner = self.current_player
            self.current_player = 'X' if self.current_player == 'O' else 'O'
            return True
        return False
 
    def check_winner(self, row, col):
        directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
        for dr, dc in directions:
            count = 1
            for i in range(1, 5):
                r, c = row + i * dr, col + i * dc
                if 0 <= r < self.board_size and 0 <= c < self.board_size and self.board[r][c] == self.current_player:
                    count += 1
                else:
                    break
            for i in range(1, 5):
                r, c = row - i * dr, col - i * dc
                if 0 <= r < self.board_size and 0 <= c < self.board_size and self.board[r][c] == self.current_player:
                    count += 1
                else:
                    break
            if count >= 5:
                return True
        return False
 
    def play(self):
        while not self.winner:
            self.print_board()
            try:
                row = int(input("玩家{}的回合,请输入你要下的行数: ".format(self.current_player)))
                col = int(input("请输入你要下的列数: "))
                if 0 <= row < self.board_size and 0 <= col < self.board_size:
                    if self.make_move(row, col):
                        if self.winner:
                            self.print_board()
                            print("玩家{},你赢了".format(self.winner))
                            break
                    else:
                        print("无效移动。再试一次。")
                else:
                    print("输入无效。再试一次。")
            except ValueError:
                print("输入无效。输入一个数字。")
 
if __name__ == "__main__":
    game = GomokuGame()
    game.play()

4. Interpretation

First, GomokuGamethe class's constructor __init__ initializes the game. board_sizeThe parameter defaults to 15, indicating the size of the chessboard. boardis a two-dimensional list that represents the state on the chessboard. current_playerRecord the current player, initially 'X'. winnerRecord the winner, initially None.

print_boardMethod is used to print the current state of the chessboard. First, it prints the column index. Then, iterate through each line and print out the status of the current line's chess pieces.

make_moveMethod used for player moves. If the specified position is empty, places the current player's marker at that position. Then call check_winnerthe method to check if there is a winner. Finally, switch the current player.

check_winnerMethod used to check if any player won. It determines whether there are five consecutive identical pieces by checking the four directions of the current position. If it exists, it returns True, indicating that one player won.

playMethod is the main loop of the game. It continues to run until a player wins. In each round, it prints the current board, then gets the rows and columns entered by the player and performs the placement operation. If the move is invalid, the player is required to re-enter. If a player wins, the victory message is printed and the game ends.

At the end of the code, this conditional judgment ensures that creating the game object and starting the game will only be executed when running the script directly.

5. Future

Visualization and GUI experts are welcome to further improve it.

Reference

https://blog.csdn.net/SUEJESDA/article/details/132390225

Guess you like

Origin blog.csdn.net/JishuFengyang/article/details/132909475