'cannot write function that checks in "X" has won the game in Tic Tac Toe (Python)
I am attending a course at EDx about AI in python. We were asked to build a program that played Tic Tac Toe.I have written this function that checks if "x" has won the game. The thing is my IDE pycharm finds an error:
An illegal target for a variable annotation
When I try to run the function I get this:
Traceback (most recent call last):
File "/home/jason/miniconda3/envs/TicTacToe/lib/python3.9/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/home/jason/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/221.5080.212/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/home/jason/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/221.5080.212/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/mnt/2ABA103F2BF5D2E6/PycharmProjects/TicTacToe/tictactoe.py", line 76
for i in range(len(board):
^
SyntaxError: invalid syntax
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
if board[0][0] == X and board[1][1] == X and board[2][2] == X:
return X
elif board[0][2] == X and board[1][1] == X and board[2][0] == X:
return X
else:
for i in range(len(board):
if board[i][0] == X and board[i][1] == X and board[i][2] == X:
return X
for i in range(len(board)):
if board[0][i] == X and board[1][i] == X and board[2][i] == X:
return X
Solution 1:[1]
You miss the closing bracket. Try following the code.
for i in range(len(board)):
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
if board[0][0] == X and board[1][1] == X and board[2][2] == X:
return X
elif board[0][2] == X and board[1][1] == X and board[2][0] == X:
return X
else:
for i in range(len(board)):
if board[i][0] == X and board[i][1] == X and board[i][2] == X:
return X
for i in range(len(board)):
if board[0][i] == X and board[1][i] == X and board[2][i] == X:
return X
Solution 2:[2]
In the error message you have a call stack (read it bottom up)
It states you have an invalid syntax error in line 76:
File "/mnt/2ABA103F2BF5D2E6/PycharmProjects/TicTacToe/tictactoe.py", line 76 for i in range(len(board): ^ SyntaxError: invalid syntax
You are missing a closing ) bracket on that line
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sabil |
| Solution 2 | Dingoldine |
