-2

So I'm currently making a tic tack toe game where you play against the computer, and I can't seem to figure this part out. I want the computer to select a random variable from a list of positions that haven't been used yet, and make that variable's value O. Here is what I have currently.

#positions is a list of variables that start off = ''

positions = [ul, uc, ur, cl, cc, cr, ll, lc, lr]

comchoice = randrange(0, len(positions))

while positions[comchoice] != '':
    comchoice = randrange(0, len(positions))
else:
    positions[comchoice] = 'O'

EDIT: This question is different than the one that it is said to be a duplicate of. It is different because it is asking about changing the value of a variable in a list. It's clear in my post that I understood the duplicate post's question with my code.

1 Answers1

1

This is working for me:

from random import randrange

positions = ['']*9

comchoice = randrange(0, len(positions))

while positions[comchoice] != '':
    comchoice = randrange(0, len(positions))
else:
    positions[comchoice] = 'O'

print(positions)

Producing:

['', '', '', 'O', '', '', '', '', '']
Dewald Abrie
  • 1,392
  • 9
  • 21
  • Okay I think that makes sense. instead of trying to change the variables, make the list index the thing i'm inputting. I'll play with it a bit and see if it works for me. thanks – Keizzerweiss Sep 18 '17 at 04:50