Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tic tac toe game #32

Open
biros1112 opened this issue Jul 14, 2024 · 0 comments
Open

Tic tac toe game #32

biros1112 opened this issue Jul 14, 2024 · 0 comments

Comments

@biros1112
Copy link

def display_board(board):
"""Display Tic-Tac-Toe board."""
for row in board:
print("|".join(row))
print("-----")

def check_winner(board):
"""Check if there is a winner."""
# Check rows
for row in board:
if row[0] == row[1] == row[2] != ' ':
return row[0]

# Check columns
for col in range(3):
    if board[0][col] == board[1][col] == board[2][col] != ' ':
        return board[0][col]

# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != ' ':
    return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != ' ':
    return board[0][2]

return None

def check_tie(board):
"""Check if the game is a tie."""
for row in board:
for cell in row:
if cell == ' ':
return False
return True

def get_player_move(board, player):
"""Get valid player move."""
while True:
try:
move = input(f"Player {player}, enter your move (row[0-2] column[0-2]): ")
row, col = map(int, move.split())
if board[row][col] == ' ':
return row, col
else:
print("That position is already taken. Try again.")
except ValueError:
print("Invalid input. Please enter row and column as numbers.")

def play_game():
"""Run Tic-Tac-Toe game."""
board = [[' ']*3 for _ in range(3)]
current_player = 'X'

while True:
    display_board(board)
    row, col = get_player_move(board, current_player)
    board[row][col] = current_player

    if check_winner(board):
        display_board(board)
        print(f"Player {current_player} wins!")
        break
    elif check_tie(board):
        display_board(board)
        print("It's a tie!")
        break

    current_player = 'O' if current_player == 'X' else 'X'

if name == "main":
play_game()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant