0% found this document useful (0 votes)
237 views4 pages

Gomoku Code

The document defines functions for a Gomoku game including creating and printing the board, placing stones, checking for available moves and winners, and implementing a random computer player. The main play_game function allows selecting the board size and playing against another player or computer in PvP or PvC mode by calling the various game functions.

Uploaded by

Noor Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
237 views4 pages

Gomoku Code

The document defines functions for a Gomoku game including creating and printing the board, placing stones, checking for available moves and winners, and implementing a random computer player. The main play_game function allows selecting the board size and playing against another player or computer in PvP or PvC mode by calling the various game functions.

Uploaded by

Noor Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

import random

# 3.1 Game menu function


def game_menu():
print("Welcome to Gomoku!")
print("1. Start a Game")
print("2. Print the Board")
print("3. Place a Stone")
print("4. Reset the Game")
print("5. Exit")

# 3.2 Creating the Board


def create_board(size):
board = [[' ' for _ in range(size)] for _ in range(size)]
return board

# 3.3 Is the target position occupied?


def is_occupied(board, x, y):
return board[x][y] != ' '

# 3.4 Placing a Stone at a Specific Intersection


def place_on_board(board, stone, position):
x, y = int(position[0]), ord(position[1].upper()) - ord('A')
if 0 <= x < len(board) and 0 <= y < len(board) and not
is_occupied(board, x, y):
board[x][y] = stone
return True
return False

# 3.5 Printing the Board


def print_board(board):
size = len(board)

# Print the column labels


for col_label in range(size):
print(f"{chr(ord('A') + col_label)} ", end="")
print()

for row in range(size-1):


# Print the top border of the boxes
for col2 in range(size):
# print(board[row][col2])
if col2 == size -1 and board[row][col2] != ' ':
print(f"{board[row][col2]}", end="")

if col2 < size - 1:


if board[row][col2] != ' ':
print(f"{board[row][col2]}--", end="")
else:
print(" --", end="")

# Print the row label


print(f" {row}")

for col in range(size - 1):


print(f"| ", end="")
print("|")
# Print the bottom border of the boxes after the last row
for col in range(size):
if board[size -1][col] != ' ':
if col != size - 1:
print(f"{board[size-1][col]}--", end="")
else:
print(f"{board[size - 1][col]}", end="")
else:
if col != size -1:
print(" --", end="")
print(f" {size - 1}")

# 3.6 Check Available Moves


def check_available_moves(board):
size = len(board)
available_moves = []
for i in range(size):
for j in range(size):
if not is_occupied(board, i, j):
available_moves.append((str(i), chr(ord('A') + j)))
return available_moves

# 3.7 Check for the Winner


def check_for_winner(board):
size = len(board)
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]

for i in range(size):
for j in range(size):
if board[i][j] != ' ':
stone = board[i][j]
for direction in directions:
dx, dy = direction
count = 1
for k in range(1, 5):
x, y = i + k * dx, j + k * dy
if 0 <= x < size and 0 <= y < size and board[x]
[y] == stone:
count += 1
else:
break
if count == 5:
return stone
if len(check_available_moves(board)) == 0:
return "Draw"
return None

# 3.8 Random Computer Player


def random_computer_player(board, player_move):
size = len(board)
player_x, player_y = int(player_move[0]), ord(player_move[1].upper())
- ord('A')
available_moves = []

for i in range(player_x - 1, player_x + 2):


for j in range(player_y - 1, player_y + 2):
if 0 <= i < size and 0 <= j < size and not is_occupied(board,
i, j):
available_moves.append((str(i), chr(ord('A') + j)))

if len(available_moves) == 0:
return random.choice(check_available_moves(board))
else:
return random.choice(available_moves)

# 3.9 Play Game


def play_game():
while True:
game_menu()
choice = input("Enter your choice: ")

if choice == "1":
size = int(input("Enter the board size (9, 13, 15): "))
while size not in [9, 13, 15]:
size = int(input("Invalid size. Enter 9, 13, or 15: "))

mode = input("Enter the mode (PvP or PvC): ").lower()


while mode not in ["pvp", "pvc"]:
mode = input("Invalid mode. Enter PvP or PvC: ").lower()

board = create_board(size)

if mode == "pvp":
player_stone = "●"
computer_stone = "○"
else:
player_stone = "●"
computer_stone = "○"

print_board(board)

while True:
if mode == "pvp":
player_move = input(f"Player {player_stone}, enter
your move (e.g. '2 F'): ")
else:
player_move = input(f"Player {player_stone}, enter
your move (e.g. '2 F'): ")

if place_on_board(board, player_stone, player_move):


print_board(board)
winner = check_for_winner(board)
if winner:
print(f"Player {winner} wins!")
break
else:
print("Invalid move. Try again.")
continue

if mode == "pvp":
computer_move = input(f"Player {computer_stone},
enter your move (e.g. '2 F'): ")
else:
computer_move = random_computer_player(board,
player_move)

if place_on_board(board, computer_stone, computer_move):


print_board(board)
winner = check_for_winner(board)
if winner:
print(f"Player {winner} wins!")
break
else:
print("Invalid move by the computer. Something went
wrong.")
break
elif choice == "2":
print_board(board)
elif choice == "3":
print("Not implemented yet.")
elif choice == "4":
board = create_board(size)
print("Game reset.")
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")

# Start the game


if __name__ == "__main__":
play_game()

You might also like