-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtic_tac_bug_toe.py
More file actions
89 lines (73 loc) · 2.7 KB
/
tic_tac_bug_toe.py
File metadata and controls
89 lines (73 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'''A buggy Tic-Tac-Toe game that provides an opportunity to debug code by both reasoning about it and stepping through it in a debugger.
The program has a number of bugs that are introduced one at a time. The goal is to find and fix the bugs.
Ensure you step through this program in an IDE debugger to understand how the program works and to find the bugs.'''
# A buggy Tic-Tac-Toe game partially generated by ChatGPT-4
board = [[' ' for _ in range(3)] for _ in range(3)]
def print_board():
"""
Prints the Tic-Tac-Toe Board.
"""
for row in range(3):
for column in range(3):
print(board[row][column], end='')
if column < 2:
print("|", end='')
print()
if row < 2:
print("-----")
def is_win(player, board):
"""
Check if the current player won the game.
:param player: ('X' or 'O') to check for win.
:return: True if the player won, and False if not.
"""
for i in range(3):
if all([cell == player for cell in board[i]]): # Rows
return True
if all([board[j][i] == player for j in range(3)]): # Columns
return True
if (board[0][0] == board[1][1] == board[2][2] == player) or (
board[0][2] == board[1][1] == board[2][0] == player): # Diagonals
return True
return False
def tally_wins(results):
"""
Numbers of win from a list of game.
:param results: List of bool values indicating weather each game resulted in a win.
:return: The total numbers of wins.
"""
return sum(results)
def main():
"""
Main function
"""
current_player = 'X'
moves = 0
results = []
while moves < 9:
print_board()
try:
row, col = map(int, input(f"Player {current_player}, enter row and column (0-2) separated by space: ").split())
if not (0 <= row <= 2 and 0 <= col <= 2):
raise ValueError("Input values must be within the range 0-2.")
except ValueError:
print(f"Error, enter a value in the range of 0-2!!!")
continue
if board[row][col] == ' ':
board[row][col] = current_player
win = is_win(current_player)
results.append(win)
if win:
print_board()
print(f"Player {current_player} wins!")
return
current_player = 'O' if current_player == 'X' else 'X' # Switch player
moves += 1
else:
print("Cell already occupied! Try again.")
print_board()
if not any(results):
print("It's a draw!")
print(f"Number of wins during the game: {tally_wins(results)}")
if __name__ == "__main__":
main()