I wrote a code to make a simple tic tac toe in python but an error is continuously popping. I can't figure out the problem.. pls help
The code works fine in first case but I don't know why it isn't
You may check the code on any editor -
import random
from random import choices
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
weights = [0.1, 0.05, 0.1, 0.05, 0.3, 0.05 , 0.1, 0.05, 0.1]
_board = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
def choose_random():
return(choices(board,weights))
def draw():
print(_board[0], _board[1], _board[2])
print(_board[3], _board[4], _board[5])
print(_board[6], _board[7], _board[8])
def user_chance():
draw()
choice = int(input('Choose any of the block: '))
board.remove(choice)
index = _board.index(choice)
_board[index] = "X"
comp_chance()
def comp_chance():
if(len(board) == 0):
print("It's a tie !")
else:
random = choose_random()
board.remove(random)
index = _board.index(random)
_board[index] = 'O'
user_chance()
user_chance()
There are few issues that you need to address here:
You are removing the value from board
list and not from the weights
list, so you are getting this problem
choose_random()
is returning a list of k
values, you haven't specified k
so it will return a list of with one value. You should add [0]
at the end of return statement.
You should also add check for whether user have entered valid position on the board or not, otherwise, you will get error that value is not in list
from random import choices
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
weights = [0.1, 0.05, 0.1, 0.05, 0.3, 0.05 , 0.1, 0.05, 0.1]
_board = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
def choose_random():
return(choices(board,weights))[0]
def draw():
print(_board[0], _board[1], _board[2])
print(_board[3], _board[4], _board[5])
print(_board[6], _board[7], _board[8])
def user_chance():
draw()
choice = int(input('Choose any of the block: '))
board.remove(choice)
index = _board.index(choice)
del weights[index]
_board[index] = "X"
comp_chance()
def comp_chance():
if(len(board) == 0):
print("It's a tie !")
else:
random = choose_random()
board.remove(random)
index = _board.index(random)
del weights[index]
_board[index] = 'O'
user_chance()
user_chance()