Skip to content

五子棋code on a 9x9 board #3

@ch3ls3ak0

Description

@ch3ls3ak0

Create a 9x9 board filled with "." (a 2D list)

board = [["."] * 9 for _ in range(9)]

Function: print the board

def print_board():
# Print column numbers (1–9) on top
print("\n 1 2 3 4 5 6 7 8 9")
# Print top border of the board
print(" +-------------------+")
# Loop through each row (i goes from 0 to 8)
for i in range(9):
# Print row number (i+1) and left border
print(f"{i+1} |", end="")
# Loop through each column in the row
for j in range(9):
# Print each cell in the board
print(board[i][j], end=" ")
# Print right border at the end of the row
print("|")
# Print bottom border of the board
print(" +-------------------+")

Function: check if there are 5 in a row inside a list of cells

def check_line(cells, player):
count = 0 # Variable: count consecutive pieces
# Loop through each cell in the given line
for c in cells:
# If the cell belongs to the player
if c == player:
count += 1 # Add 1 to consecutive count
# If 5 in a row are found, return True
if count == 5:
return True
else:
# Reset count if broken
count = 0
# Return False if no 5 in a row
return False

Function: check if the player wins after placing a piece

def check_win(row, col, player):
# --- Check the row ---
if check_line(board[row], player):
return True

# --- Check the column ---
col_list = [board[i][col] for i in range(9)]  # Extract column
if check_line(col_list, player):
    return True

# --- Check ↘ diagonal ---
diag1 = []  # Variable: store diagonal cells
i, j = row, col  # Start from the placed piece
# Move to top-left corner of this diagonal
while i > 0 and j > 0:
    i -= 1
    j -= 1
# Collect all cells from top-left to bottom-right
while i < 9 and j < 9:
    diag1.append(board[i][j])
    i += 1
    j += 1
# Check if diagonal has 5 in a row
if check_line(diag1, player):
    return True

# --- Check ↙ diagonal ---
diag2 = []  # Variable: store diagonal cells
i, j = row, col  # Start from the placed piece
# Move to top-right corner of this diagonal
while i > 0 and j < 8:
    i -= 1
    j += 1
# Collect all cells from top-right to bottom-left
while i < 9 and j >= 0:
    diag2.append(board[i][j])
    i += 1
    j -= 1
# Check if diagonal has 5 in a row
if check_line(diag2, player):
    return True

# If no win found
return False

------------------------

Main Program starts here

------------------------

player = "X" # Variable: start with player X

Game loop: keeps running until someone wins

while True:
print_board() # Show current board

try:
    # Input row and col (split into two numbers)
    row, col = map(int, input(f"Player {player}, enter row and column (1-9): ").split())
except:
    # If input is not two numbers
    print("Please enter two numbers!")
    continue  # Go back to ask again

# Check if numbers are in valid range 1–9
if not (1 <= row <= 9 and 1 <= col <= 9):
    print("Out of range! Enter numbers between 1 and 9.")
    continue

# Convert input to 0-based index for the board
row -= 1
col -= 1

# Check if the cell is already taken
if board[row][col] != ".":
    print("This position is already occupied!")
    continue

# Place the player's piece
board[row][col] = player

# Check if this move makes the player win
if check_win(row, col, player):
    print_board()  # Show final board
    print(f"🎉 Player {player} wins!")  # Announce winner
    break  # End the game

# Switch players: X -> O, O -> X
player = "O" if player == "X" else "X"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions