list - Python - Random output has a structure -
i writing small script tic tac toe game in python. store tic tac toe grid in list (example of empty grid): [[' ', ' ', ' ',], [' ', ' ', ' ',], [' ', ' ', ' ',]]
. these following possible string list:
' '
no player has marked field'x'
player x'o'
player o
i have written function creates empty grid (create_grid
), function creates random grid (create_random_grid
) (this used testing purposes later) , function prints grid in such manner read-able end user (show_grid
). having trouble create_random_grid
function, other 2 method work though. here how approached create_random_grid
function:
first create empty grid using
create_grid
iterate on grid line
iterate on character in line
change character item randomly selected form here.
['x', 'o', ' ']
return
grid
note: not expect exact output expected output. actual output, not lines same.
i not know why lines same. seems last generated line 1 used. added debug lines in code along examples cleary show problem. added line in code show me randomly chosen mark each slot of grid, output not correspond that, except last line match. have included other important information comments in code. pastebin link here
code:
from random import choice def create_grid(size=3): """ size: int. horizontal , vertical height of grid. default set 3 because thats normal returns: lst. list of lines. lines list of strings creates empty playing field """ x_lst = [' '] * size # horizontal line of code lst = [] # final list y in range(size): # append size times lst proper height lst.append(x_lst) return lst def show_grid(grid): """ grid: list. list of lines, lines list of string returns: none """ line in grid: print('[' + ']['.join(line)+']') # print each symbol in box def create_random_grid(size=3): """ size: int. horizontal , vertical height of grid. default set 3 because thats normal returns: lst. list of lines. lines list of strings creates grid random player marks, used testing purposes """ grid = create_grid() symbols = ['x', 'o', ' '] line in range(size): column in range(size): # grid[line][column] = choice(symbols) # want use, not work # debug, same version ^^ in smaller steps random_item = choice(symbols) print 'line: ', line, 'column: ', column, 'symbol chosen: ', random_item # shows randomly wirrten mark each slot grid[line][column] = random_item # over-write indexes of grid randomly chosen symbol return grid hardcoded_grid = [['x', ' ', 'x'], [' ', 'o', 'o'], ['o', 'x', ' ']] grid = create_random_grid() print('\nthe simple list view of random grid:\n'), grid print('\nthis grid created using create_random_grid method:\n') show_grid(grid) print('\nthis grid hard coded (to show show_grid function works):\n') show_grid(hardcoded_grid)
x_lst = [' '] * size lst = [] y in range(size): lst.append(x_lst)
all elements of lst
same list object. if want equal independent lists, create new list each time:
lst = [] y in range(size): lst.append([' '] * size)
Comments
Post a Comment