python随机输出_Python随机输出有一个structu

我正在用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网格

注意:我不期望预期输出的精确输出。对于实际输出,我并不总能得到确切的结果,但所有的行总是相同的。在

108eed9c6361a4cb7734d97a38ec82ae.png

我不知道为什么所有的线都一样。最后生成的行似乎就是使用的行。我在代码中添加了一些调试行,并提供了一些可以清楚地显示我的问题的示例。我在代码中添加了一行代码,显示网格中每个插槽随机选择的标记,但是我的输出与此不符,除了它们匹配的最后一行。我在代码中包含了其他重要信息作为注释。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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值