简体   繁体   中英

Python: Randomly choose a spot on a tic-tac-toe board

I am writing a program that will essentially be a tic-tac-toe game. It uses a simple text based drawing of the board game using - lines and + pluses. In the beginning of the program, I have the 9 spaces in the tic-tac-toe board defined as the following:

valuea1 = " "
valuea2 = " "
valuea3 = " "
valueb1 = " "

And so on through valuec3 ... The blank spaces are set up to allow substitution of an X or an O. My board function looks like this:

def board():
    """ prints the tic-tac-toe board"""
    print(" +---A------B------C--+")
    print(" |      |      |      |")
    print("1|  " + valuea1 +"   |  " + valueb1 +"   |  " + valuec1 + "   |")
    print(" |      |      |      |")
    print(" ----------------------")
    print(" |      |      |      |")
    print("2|  " + valuea2 +"   |  " + valueb2 +"   |  " + valuec2 + "   |")
    print(" |      |      |      |")
    print(" ----------------------")
    print(" |      |      |      |")
    print("3|  " + valuea3 +"   |  " + valueb3 +"   |  " + valuec3 + "   |")
    print(" |      |      |      |")
    print(" +--------------------+")
    return

Later on in the program, based on an if statement, the symbol the "computer player" will be using (either X or O) is stored in the variable:

computer_mark ## is either "X" or "O" based on player choice

Now here is my main concern and question

randomlist = ("valuea1", "valuec1", "valuea3", "valuec3")
random_result = random.choice(randomlist)
## (REPLACE WITH CODE)
## takes the value stored in random_result, somehow treats the value as a variable,
## assigns that given variable the string value that is stored in computer_mark

I try to randomly choose 1 of 4 spots on the board, and change that spot from a " " string value to the string value stored in computer_mark.

Is there a way to code Python into choosing a random variable, and assigning it a value that is stored in a different variable?

EDIT I am a python and general programming noob. I've only been coding for two weeks, therefore, I apologize if my coding techniques are, somewhat, unintelligent.

You should definetly consider using a list or a nested list for this:

import random

board = [[' ', ' ', ' '],
         [' ', ' ', ' '],
         [' ', ' ', ' ']]

Then you can access a random field (the main list contains 3 lists each containing 3 items:

random_field = random.randint(0, 2), random.randint(0, 2)
board[random_field[0]][random_field[1]] = 'x'
print(board)
# [[' ', ' ', ' '], [' ', ' ', 'x'], [' ', ' ', ' ']]  # just one example

Or if you want a random choice out of several possibilities:

random_field = random.choice([(0, 0), (1, 1), (2, 2)])
board[random_field[0]][random_field[1]] = 'x'
print(board)
# [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]  # sets only one of the diagonals

It is a very bad idea to try and modify these variables by name (if you really want to do this see below for an older answer). This is how you could improve your code by using a list instead of a bunch of variables:

import random

board = [' '] * 9

def set_random(board,computer_mark):
    board[random.randint(0, 8)] = computer_mark

def print_board(board):
    lines = [' +--%s--+' % ('-'*5).join(['A','B','C'])]
    for i in range(3):
        lines.append('%d|  %s  |' % (i,'  |  '.join(board[3*i:(3*i+3)])))
        if i < 2:
            lines.append(' ' + '-'*19)
    lines.append(' +%s+' % ('-'*17))
    print('\n |     |     |     |\n'.join(lines))

print_board(board)

random.seed(0)
set_random(board,'X')

print_board(board)

Output:

 +--A-----B-----C--+
 |     |     |     |
0|     |     |     |
 |     |     |     |
 -------------------
 |     |     |     |
1|     |     |     |
 |     |     |     |
 -------------------
 |     |     |     |
2|     |     |     |
 |     |     |     |
 +-----------------+
 +--A-----B-----C--+
 |     |     |     |
0|     |     |     |
 |     |     |     |
 -------------------
 |     |     |     |
1|     |     |     |
 |     |     |     |
 -------------------
 |     |     |     |
2|  X  |     |     |
 |     |     |     |
 +-----------------+

To better understand which list index goes into which field it is useful to visualize the indexes on the board:

>>> print_board(list(map(str,range(9))))
 +--A-----B-----C--+
 |     |     |     |
0|  0  |  1  |  2  |
 |     |     |     |
 -------------------
 |     |     |     |
1|  3  |  4  |  5  |
 |     |     |     |
 -------------------
 |     |     |     |
2|  6  |  7  |  8  |
 |     |     |     |
 +-----------------+

You can access the current namespace (as a dict) using the locals() function. Thus you could to do the following: - This is however a very bad idea . See above for a much better way to tackle the general problem of representing and manipulating the board.

locals()[random_result] = computer_mark

Edit Based on the updated question a full example:

import random

valuea1 = valuea2 = valuea3 = valueb1 = valueb2 = valueb3 = valuec1 = valuec2 = valuec3 = " "

def board():
    """ prints the tic-tac-toe board"""
    print(" +---A------B------C--+")
    print(" |      |      |      |")
    print("1|  " + valuea1 +"   |  " + valueb1 +"   |  " + valuec1 + "   |")
    print(" |      |      |      |")
    print(" ----------------------")
    print(" |      |      |      |")
    print("2|  " + valuea2 +"   |  " + valueb2 +"   |  " + valuec2 + "   |")
    print(" |      |      |      |")
    print(" ----------------------")
    print(" |      |      |      |")
    print("3|  " + valuea3 +"   |  " + valueb3 +"   |  " + valuec3 + "   |")
    print(" |      |      |      |")
    print(" +--------------------+")
    return

random.seed(0) #to make this example reproducible
computer_mark = "X"

randomlist = ("valuea1", "valuec1", "valuea3", "valuec3")
random_result = random.choice(randomlist)
locals()[random_result] = computer_mark

board()

If I execute the above code I get the following result:

 +---A------B------C--+
 |      |      |      |
1|      |      |      |
 |      |      |      |
 ----------------------
 |      |      |      |
2|      |      |      |
 |      |      |      |
 ----------------------
 |      |      |      |
3|      |      |  X   |
 |      |      |      |
 +--------------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM