-
Notifications
You must be signed in to change notification settings - Fork 186
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4 from akshatkhatri/tictactoe
added tic_tac_toe project in python
- Loading branch information
Showing
1 changed file
with
60 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,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() |