-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtictactoe_errors_handled.py
115 lines (87 loc) · 2.69 KB
/
tictactoe_errors_handled.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def main():
print()
print("Welcome to TIC TAC TOE from TALK PYTHON")
print(" Safe edition!")
print()
# CREATE THE BOARD:
# Board is a list of rows
# Rows are a list of cells
board = [[None, None, None], [None, None, None], [None, None, None]]
# CHOOSE INITIAL PLAYER
active_player_index = 0
players = ["Michael", "Computer"]
symbols = ["X", "O"]
player = players[active_player_index]
# UNTIL SOMEONE WINS
while not find_winner(board):
# SHOW THE BOARD
player = players[active_player_index]
symbol = symbols[active_player_index]
announce_turn(player)
show_board(board)
if not choose_location(board, symbol):
print("That isn't an option, try again.")
continue
# TOGGLE ACTIVE PLAYER
active_player_index = (active_player_index + 1) % len(players)
print()
print(f"GAME OVER! {player} has won with the board: ")
show_board(board)
print()
def choose_location(board, symbol):
try:
row = int(input("Choose which row: "))
row -= 1
if row < 0 or row >= len(board):
return False
column = int(input("Choose which column: "))
column -= 1
if column < 0 or column >= len(board[0]):
return False
cell = board[row][column]
if cell is not None:
return False
board[row][column] = symbol
return True
except ValueError as ve:
print(f"Error: Cannot convert input to a number.")
return False
except Exception:
# Not sure what else happened here, but didn't work.
return False
def show_board(board):
for row in board:
print("| ", end="")
for cell in row:
symbol = cell if cell is not None else "_"
print(symbol, end=" | ")
print()
def announce_turn(player):
print()
print(f"It's {player}'s turn. Here's the board:")
print()
def find_winner(board):
sequences = get_winning_sequences(board)
for cells in sequences:
symbol1 = cells[0]
if symbol1 and all(symbol1 == cell for cell in cells):
return True
return False
def get_winning_sequences(board):
sequences = []
# Win by rows
rows = board
sequences.extend(rows)
# Win by columns
for col_idx in range(0, 3):
col = [board[0][col_idx], board[1][col_idx], board[2][col_idx]]
sequences.append(col)
# Win by diagonals
diagonals = [
[board[0][0], board[1][1], board[2][2]],
[board[0][2], board[1][1], board[2][0]],
]
sequences.extend(diagonals)
return sequences
if __name__ == "__main__":
main()