Skip to content

Commit

Permalink
Merge pull request #4 from akshatkhatri/tictactoe
Browse files Browse the repository at this point in the history
added tic_tac_toe project in python
  • Loading branch information
wbhoomika authored Oct 2, 2023
2 parents 2a2fc96 + 867f1f6 commit c16d99e
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions Python Projects/tic_tac_toe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)

def check_winner(board):
# Check rows
for row in board:
if row.count(row[0]) == len(row) and row[0] != ' ':
return True

# Check columns
for col in range(len(board[0])):
if all(board[row][col] == board[0][col] and board[row][col] != ' ' for row in range(len(board))):
return True

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

return False

def is_board_full(board):
return all(all(cell != ' ' for cell in row) for row in board)

def is_valid_move(board, row, col):
return 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' '

def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'

while True:
print_board(board)

row = int(input(f"Player {current_player}, enter row (0, 1, or 2): "))
col = int(input(f"Player {current_player}, enter column (0, 1, or 2): "))

if not is_valid_move(board, row, col):
print("Invalid move. Try again.")
continue

board[row][col] = current_player

if check_winner(board):
print_board(board)
print(f"Player {current_player} wins!")
break

if is_board_full(board):
print_board(board)
print("It's a tie!")
break

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

if __name__ == "__main__":
tic_tac_toe()

0 comments on commit c16d99e

Please sign in to comment.