-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreadme.html
80 lines (76 loc) · 2.27 KB
/
readme.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=yes"
/>
<title>readme</title>
<style type="text/css">
code {
white-space: pre-wrap;
}
span.smallcaps {
font-variant: small-caps;
}
span.underline {
text-decoration: underline;
}
div.column {
display: inline-block;
vertical-align: top;
width: 50%;
}
</style>
</head>
<body>
<h2 id="solution-for-error-handling-in-tic-tac-toe">
Solution for error handling in tic-tac-toe
</h2>
<p>
The only part of this first pass on the game that could fail is choosing
the location.
</p>
<p>
Did you notice that when it asks for a number, if you don’t enter anything
it crashes hard?
</p>
<p>
How about if you state too much? It asks for row and you answer 2,3 (row
and column)? Boom again.
</p>
<p>That’s what we fixed here with <code>try/except</code>:</p>
<pre><code>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</code></pre>
<p>
For a more advanced version, you could edit the tic-tac-toe from files and
make sure we have permissions to save to the files and that they are in a
correct format for <code>json</code> to read and so on.
</p>
<p>
See
<a href="./tictactoe_errors_handled.py">tictactoe_errors_handled.py</a>
</p>
</body>
</html>