Search code examples
pythonpython-2.7listrandomminesweeper

Pick multiple index of a specific list of list


Greetings to whoever reading this! I have been assigned to make a minesweeper program in python where yeah I could just copy paste an already made one but I wanted to make it myself but I'm having a hard time with my lists here. To make things a little bit more clear I have the main list lets call it List within it I have 10 more lists for the rows of the games board BUT now that I have to add the mines to it I can't find a way to randomly place them around the lists!

x=random.choice(list)
    board.replace(x,"nuke",forrow)
-----------------------------------------
x=randrange(len(list))
    board.replace(x,"nuke",forrow)
--------------------------------------
x=random.sample(list[i],1)
    board.insert(x,"nuke")
----------------------------------------
    for x in range(len(list)):
            board.insert(random.choice(x),"nuke")

import random
board = [[" "]*10 for i in range(10)]# here i create the big list and the other ones within it

bombs=15#input("Please provide the amount of bombs you want in the game: ")

for list in board: #here is my problem
    x=random.sample(list[i],1) 
    board.insert(x,"nuke")



for x in board:print x 

I am expecting anything that is able to help me out on my little program I need something to be able to get the position of X amount of positions in a list and be able to replace them with a "bomb" so call it!


Solution

  • Instead of randomly picking positions in the field, how about this approach: Initialize a long list with the right amount of "nukes" and empty cells, random.shuffle that list, and break it down to a 2D-board.

    >>> bombs = 15
    >>> all_cells = ["nuke"] * bombs + [" "] * (100 - bombs)
    >>> random.shuffle(all_cells)
    >>> board = [all_cells[i:i+10] for i in range(0, 100, 10)]
    

    This way, you do not have to check whether you already randomly rolled the same cell before.