我正在用python编写一个Tic-Tac-Toe游戏的小脚本。{tactic}存储在一个空的网格中。以下是列表的可能字符串:' '没有玩家标记此字段
'X'玩家X
'O'玩家O
我编写了一个创建空网格(create_grid)的函数、创建随机网格(create_random_grid)的函数(稍后将用于测试目的)以及一个以这样的方式打印网格的函数,以便最终用户可以读取网格(show_grid)。我在使用create_random_grid函数时遇到了问题,但是其他两个方法可以工作。{cd6>函数是如何处理的:首先使用create_grid创建一个空网格
迭代网格线
迭代行中的字符
在这里将字符更改为随机选择的项目。['X', 'O', ' ']
return网格
注意:我不期望预期输出的精确输出。对于实际输出,我并不总能得到确切的结果,但所有的行总是相同的。在
我不知道为什么所有的线都一样。最后生成的行似乎就是使用的行。我在代码中添加了一些调试行,并提供了一些可以清楚地显示我的问题的示例。我在代码中添加了一行代码,显示网格中每个插槽随机选择的标记,但是我的输出与此不符,除了它们匹配的最后一行。我在代码中包含了其他重要信息作为注释。Pastebin链接here
代码:from random import choice
def create_grid(size=3):
"""
size: int. The horizontal and vertical height of the grid. By default is set to 3 because thats normal
returns: lst. A list of lines. lines is a list of strings
Creates a empty playing field
"""
x_lst = [' '] * size # this is a horizontal line of the code
lst = [] # final list
for y in range(size): # we append size times to the lst to get the proper height
lst.append(x_lst)
return lst
def show_grid(grid):
"""
grid: list. A list of lines, where the lines are a list of string
returns: None
"""
for line in grid:
print('[' + ']['.join(line)+']') # print each symbol in a box
def create_random_grid(size=3):
"""
size: int. The horizontal and vertical height of the grid. By default is set to 3 because thats normal
returns: lst. A list of lines. lines is a list of strings
Creates a grid with random player marks, used for testing purposes
"""
grid = create_grid()
symbols = ['X', 'O', ' ']
for line in range(size):
for column in range(size):
# grid[line][column] = choice(symbols) # what I want to use, but does not work
# debug, the same version as ^^ but in its smaller steps
random_item = choice(symbols)
print 'line: ', line, 'column: ', column, 'symbol chosen: ', random_item # shows randomly wirrten mark for each slot
grid[line][column] = random_item # over-write the indexes of grid with the randomly chosen symbol
return grid
hardcoded_grid = [['X', ' ', 'X'], [' ', 'O', 'O'], ['O', 'X', ' ']]
grid = create_random_grid()
print('\nThe simple list view of the random grid:\n'), grid
print('\nThis grid was created using the create_random_grid method:\n')
show_grid(grid)
print('\nThis grid was hard coded (to show that the show_grid function works):\n')
show_grid(hardcoded_grid)