简体   繁体   English

Python:在tic-tac-toe板上随机选择一个点

[英]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: 在程序的开头,我在tic-tac-toe板上有9个空格,定义如下:

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: 依此类推,通过valuec3 ...空格被设置为允许替换X或O.我的板函数如下所示:

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: 稍后在程序中,基于if语句,“计算机播放器”将使用的符号(X或O)存储在变量中:

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. 我尝试随机选择板上4个点中的1个,并将该点从" "字符串值更改为存储在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? 有没有办法将Python编码为选择随机变量,并为其分配一个存储在不同变量中的值?

EDIT I am a python and general programming noob. 编辑我是一个python和一般编程菜鸟。 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: 您应该明确考虑使用list或嵌套列表:

import random

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

Then you can access a random field (the main list contains 3 lists each containing 3 items: 然后你可以访问一个随机字段(主列表包含3个列表,每个列表包含3个项目:

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. 您可以使用locals()函数访问当前命名空间(作为dict)。 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   |
 |      |      |      |
 +--------------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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