Search code examples
pythonpython-3.xminesweeper

Grid Generation for minesweeper


Hi so I am making a minesweeper game and I am a bit stuck with the grid generation part. This is my code so far:

from random import randint
import pygame

def MineGen():
    mineamount = 100
    grid_across = 40
    grid_up = 25
    mine_list = []
    my2dthatlist = []
    numacoss = 0
    for i in range (mineamount):
        numacoss = randint(1,40)
        my2dthatlist.append(numacoss)
        numup = randint(1,25)
        my2dthatlist.append(numup)
        mine_list.append(my2dthatlist)
        my2dthatlist = []
    return mine_list

def GridGen():
    grid_across = 40
    grid_up = 25
    GRIDD = [[0]* grid_across for i in range(grid_up)]

    return GRIDD

def MineGrid(GridOutMine, mine_list):
    mineplace = 0
    placeX = 0
    placeY = 0
    for i in range(100):
        mineplace = mine_list[i]
        placeX = mineplace[0]
        placeY = mineplace[1]
        GridOutMine[placeX][placeY] = 1
    print(GridOutMine)

mine_list = MineGen()
GridOutMine = GridGen()
MineGrid(GridOutMine, mine_list)

My issue is that i am getting a list index out of range for the

GridOutMine[placeX][placeY] = 1

part. I don't really know why this is. If you could give me some assistance in what to do, or just some general comments on my code, I would really appreciate it thanks.


Solution

  • That's because, unlike range, random.randint outputs numbers within the specified bounds inclusively. That is, randint(1, 25) could output 25, which is not a valid index for a list that's only 25 elements long (since the last index is 24).

    In MineGen, you need to change randint(1, 25) to randint(1, 25-1) or randint(1, 24), and likewise for randint(1, 40) which needs to be randint(1, 39). I'd actually suggest randint(0, 24) and (0, 39), but I don't know if that's intentional.

    There are many other things that could/should be improved about this code, but I'd suggest you ask for that kind of input over on CodeReview instead of here once your code is working (they don't fix broken code).


    EDIT:

    Also, you're indexing your grid in the wrong order. It's a list (25-long) of rows (40-long), so you need to index it in the Y dimension first, then X: GridOutMine[placeY][placeX] = 1