简体   繁体   中英

Adding values to lists in python

I have created a simple 8 * 8 grid on python and want to be able to plot 1 "X" to it in the bottom left corner and 10 random "T"'s to it, which I have managed in the code below. The problem being is when I then try and then add a further 5 random "B"s to the grid it sometimes only brings up 4 as I think as it iterates through the list and is not seeing a "-" it is counting as an iteration and when it reaches 5 it is stopping.

from random import randint
board =[]
for item in range (0,8):
    board.append(["-"]*8)

def print_board (board):
    for row in board:
        print ("  ".join(row))

treasure = 10
bandits = 5

def player1(board):
    board[7][0] = 'X'

def random_treasure (board,x):
    for n in range(x):
    treasure_location1 = randint(0, len(board)-1)
    treasure_location2 = randint(0, len(board)-1)
    board[treasure_location1][treasure_location2]

        while board[treasure_location1][treasure_location2] == "X" or board[treasure_location1][treasure_location2] == "T":
        treasure_location1 = randint(0, len(board)-1)
        else:
            board[treasure_location1][treasure_location2] = 'T'

def random_bandits (board,y):
    for n in range(y):
        global treasure_location1
        global treasure_location2
        bandit_location1 = randint(0, len(board)-1)
        bandit_location2 = randint(0, len(board)-1)
        board[bandit_location1][bandit_location2]

        while board[bandit_location1][bandit_location2] == "X" or board[bandit_location1][bandit_location2] == "T":
        bandit_location1 = randint(0, len(board)-1)
        else:
            board[bandit_location1][bandit_location2] = "B"


player1(board)
random_treasure(board,treasure)
random_bandits (board,bandits)

print_board(board)

I thought doing something like this would be more efficient and thus will simply only print a T or B to the board if it sees a "-" but it is only printing one T not the range I want. I know this is probably some simple logic error but I am a bit stuck so any help is appreciated, thanks

def random_treasure (board,x):
    treasure_location1 = randint(0, len(board)-1)
    treasure_location2 = randint(0, len(board)-1)
    board[treasure_location1][treasure_location2]

    while board[treasure_location1][treasure_location2] == "-":
        for n in range(x):
            board.append("T")

尝试使用递归,因此将变量设置为 5,每次成功时将变量减一,否则通过,然后在变量大于零时放置一个 while 循环,调用该函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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