1

Currently my code adds bombs through random x and y coordinates on my hidden grid. What would I have to add here in order for the code to add numbers if the grid space is touching a bomb?

def addBombNum(bombs,gSize,hiddenGrid,bCount):

  fNum = ""

  for i in range(bombs):
    randPlace = True
    while randPlace:
      x = random.randint(0,gSize - 1)
      y = random.randint(0,gSize - 1)

      if hiddenGrid[y][x] == "[-]": hiddenGrid[y][x] = "\033[90m[*]\033[m" ; randPlace = False
      if hiddenGrid[y][x] == "\033[90m[*]\033[m": pass

  for i in range(gSize):
    for j in range(gSize):

      if hiddenGrid[i][j] == "\033[90m[*]\033[m": continue

This is my hiddenGrid if needed.

hiddenGrid = [["[-]" for y in range(gSize)] for x in range(gSize)]

1 Answers1

1

I would personally recomment storing the bomb array as a numerical array and having a way to process it into the output afterwards. However, to answer your question directly, what I would recommend doing is each time you place down a bomb, you increment a counter for every cell adjacent to it.

So, at the top of your function, you could first create a number grid: grid = [[0 for y in range(gSize)] for x in range(gSize)].

Next, each time you add a bomb, increment the counter for each grid space that touches it:

for a in range(y - 1, y + 2):
    for b in range(x - 1, x + 2):
        if 0 <= a < gSize and 0 <= b < gSize:
            grid[a][b] += 1

Finally, at the very end, you can just relay this information from the grid to the output. Thus, after the if hiddenGrid[i][j] == "\033[90m[*]\033[m": continue line (which I assume you added to prevent it from overwriting bombs with numbers), you can add this block:

if grid[i][j] > 0:
    hiddenGrid[i][j] = "\033[90m[%d]\033[m" % grid[i][j]

A different way you could do it is just add this block to the very end after the bomb skip check:

count = 0
for a in range(i - 1, i + 2):
    for b in range(j - 1, j + 2):
        if 0 <= a < gSize and 0 <= b < gSize:
            if hiddenGrid[a][b] == "\033[90m[*]\033[m":
                count += 1
if count > 0:
    hiddenGrid[i][j] = "\033[90m[%d]\033[m" % count

This way, you don't need to have the counter grid and don't need to increment it each time. However, having the grid means if you need to use it for other things later on, you have it around and don't need to recompute it every time.

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
  • When using the second method you posted (the one not needing to increment), it gives me a "list index out of range" error every time. I don't see why, maybe there is a fix to it? – Problemat1c Dec 08 '21 at 22:49
  • @Problemat1c Oh. You need to add the `if 0 <= a < gSize and 0 <= b < gSize` check to the second one as well. My bad, I'll edit it in. – hyper-neutrino Dec 08 '21 at 22:59
  • Nevermind, tried the first method and it worked flawlessly, thanks so much! – Problemat1c Dec 08 '21 at 23:02