Reputation: 17
The code is for Tic Tac Toe using Randint and lists. Could some one explain why there is an error? I've tried to change it to a interger and a string but it still doesn't work.
import random
boardt = [1, 2, 3]
boardm = [4, 5, 6]
boardd = [7, 8, 9]
print ("This is Tic Tac Toe / Noaughts and Crosses")
print ('(x)Human against (o) "machine"')
print (boardt)
print (boardm)
print (boardd)
hpos = int(input("Pick a position "))
if hpos == 1:
boardt.remove(1)
boardt.insert(0,"X")
mpos = (int(random.randint(1,8)))
if mpos == 1 or 2:
boardt.remove(mpos)
boardt.insert(mpos,"O")
elif mpos == 3 or 4 or 5:
boardm.remove(mpos)
boardm.insert(mpos,"O")
elif mpos == 6 or 7 or 8:
boardd.remove(mpos)
boardd.insert(mpos,"O")
Error:
Traceback (most recent call last):
File "main.py", line 16, in <module>
boardt.remove(mpos)
ValueError: list.remove(x): x not in list
Upvotes: 0
Views: 65
Reputation: 691
I agree with SuperStormer, that you should replace remove+insert with a simple assignment. That's not the main problem, though.
if mpos == 1 or 2: does not do what you think. That statement will always pass for True. What you want is if mpos in (1, 2):.
You can get out of a lot of if-coding by using a 2-dimensional array, like this: [[1,2,3],[4,5,6],[7,8,9]]. Decide which one to set like this:
board = [[1,2,3],[4,5,6],[7,8,9]]
hpos = int(input("Pick a position "))
hpos -= 1 # Humans prefer to start at 1, computers at 0
x = hpos % 3 # Modulo to get column
y = hpos // 3 # Integer division to get row
board[y][x] = 'X'
for row in board:
print(''.join(map(str, row)))
Upvotes: 0
Reputation: 6315
The main problem is that e.g. if mpos == 1 or 2
does not test if the value is 1 or 2.
The test should be if mpos == 1 or mpos == 2:
, or better: if mpos in (1, 2):
Upvotes: 1
Reputation: 5387
remove
removes by index, not value. However, you can replace that line and the following line with boardd[mpos-6]="O"
. You should also clean up your code by using loops and a multidimensional array instead of 3 separate arrays.
Upvotes: 0