-
Notifications
You must be signed in to change notification settings - Fork 12.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c1252fd
commit b324c90
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
def print_board(board): | ||
for row in board: | ||
print(" | ".join(row)) | ||
print("-" * 9) | ||
|
||
def check_winner(board, player): | ||
for i in range(3): | ||
# Check rows and columns | ||
if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)): | ||
return True | ||
# Check diagonals | ||
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): | ||
return True | ||
return False | ||
|
||
def is_full(board): | ||
return all(cell != " " for row in board for cell in row) | ||
|
||
def main(): | ||
board = [[" " for _ in range(3)] for _ in range(3)] | ||
player = "X" | ||
|
||
while True: | ||
print_board(board) | ||
row = int(input(f"Player {player}, enter the row (0, 1, 2): ")) | ||
col = int(input(f"Player {player}, enter the column (0, 1, 2): ")) | ||
|
||
if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ": | ||
board[row][col] = player | ||
|
||
if check_winner(board, player): | ||
print_board(board) | ||
print(f"Player {player} wins!") | ||
break | ||
|
||
if is_full(board): | ||
print_board(board) | ||
print("It's a draw!") | ||
break | ||
|
||
player = "O" if player == "X" else "X" | ||
else: | ||
print("Invalid move. Try again.") | ||
|
||
if __name__ == "__main__": | ||
main() |