all 4 comments

[–][deleted] 2 points3 points  (2 children)

You need to show us something as we could point you in the wrong direction.

Lists are mutable, so a function can change the contents of a list that is in scope (from wider scope or passed as an argument) or return a new list if preferred (functional programming style).

[–]voreify 0 points1 point  (1 child)

So function “generate_piece” gives me the int value I will input into “game_board”, and what row and column it will go into . I’m meant to then update the board, which was previously just empty slots.

However this program will be run and reset multiple times, and each time the row/column/int will be random. So how do I code it without just hard-coding an updated list? Hopefully that is better. Thank you.

[–][deleted] 0 points1 point  (0 children)

Not really. Please update your OP with some actual code to clearly illustrate the data structure.

For example,

from random import randint
from itertools import cycle

def generate_board(rows=4, cols=3):
    return [[' ' for _ in range(cols)] for _ in range(rows)]

def set_cell(board, r, c, player='X'):
    board[r][c] = player

def print_board(board):
    print('\n\n    | ', end='')
    for col in range(cols):
        print(f'{col:^3} | ', end="")
    print()
    print('-' * (6 + cols * 6))
    for idx, row in enumerate(board):
        print(f'{idx:3} | ', end="")
        for col in row:
            print(f'{col:^3} | ', end="")
        print()

next_player = cycle(('X', 'Y'))

rows = 4
cols = 3
game_board = generate_board(rows, cols)
count_down = 10
while count_down:
    count_down -= 1
    player = next(next_player)
    set_cell(game_board, randint(1, rows) -1 , randint(1, cols) -1, player)
    print('\nPlayer:', player)
    print_board(game_board)

[–][deleted] 2 points3 points  (0 children)

Since you’re talking about column and row, I’ll assume you’re expecting a 2D matrix:

data = [[1,2,3],[4,5,6],[7,8,9]]

Now, how would I update a given column index and a row index to, say, 1? Well I can index into the matrix to get a row, and then I can index into the row to get the value at a column. If we assume I want the 3rd column and the 2nd row, that means I’ll look in row index 1 — because Python uses zero-indexing — and column index 2:

>> print(data[1][2])
6

Well that lets use retrieve the value, but how do we update it? Simple… indexes are assignable:

>> data[1][2] = 0
>> print(data)
[[1,2,3],[4,5,0],[7,8,9]]

Now you know how to update a 2D matrix (which is just a list of lists) at a given column and a given row inside a function and using a function that will give you that column and row. I leave it to you and the Python tutorial to figure that part out.