Game Development Reference
In-Depth Information
10 - Tic Tac Toe
function. (This is a trick programmers sometimes use to reduce the amount they need to
type. Be sure to add a comment though, otherwise you may forget what bo and le are
supposed to mean.)
There are eight possible ways to win at Tic Tac Toe. First, have a line across the top,
middle, and bottom. Second, have a line down the left, middle, or right. And finally, have
either of the two diagonals. Note that each line of the condition checks if the three spaces
are equal to the letter provided (combined with the and operator) and we use the or
operator to combine the eight different ways to win. This means only one of the eight ways
must be true in order for us to say that the player who owns letter in le is the winner.
Let's pretend that le is 'O' , and the board looks like this:
| |
X | |
| |
-----------
| |
| X |
| |
-----------
| |
O | O | O
| |
If the board looks like that, then bo must be equal to [' ', 'O', 'O', 'O', '
', 'X', ' ', 'X', ' ', ' '] . Here is how the expression after the return
keyword on line 53 would evaluate:
Here is the expression as it is in the code:
53. return ((bo[7] == le and bo[8] == le and bo[9] == le) or
54. (bo[4] == le and bo[5] == le and bo[6] == le) or
55. (bo[1] == le and bo[2] == le and bo[3] == le) or
56. (bo[7] == le and bo[4] == le and bo[1] == le) or
57. (bo[8] == le and bo[5] == le and bo[2] == le) or
58. (bo[9] == le and bo[6] == le and bo[3] == le) or
59. (bo[7] == le and bo[5] == le and bo[3] == le) or
60. (bo[9] == le and bo[5] == le and bo[1] == le))
First Python will replace the variable bo with the value inside of it:
53. return (('X' == 'O' and ' ' == 'O' and ' ' == 'O') or
54. (' ' == 'O' and 'X' == 'O' and ' ' == 'O') or
55. ('O' == 'O' and 'O' == 'O' and 'O' == 'O') or
Search WWH ::




Custom Search