Hi I have been trying to program minesweeper in pygame as my first ever video game. I have been trying to create an array that tells me on every pixel how many bombs is there in a radius of 3x3 be checking inside of another array that generates 10 bombs on a 10 by 8 grid (The array is actually 12 by 10 so that if you check a bomb on the corner and it tries to check the places before the position 0,0 it doesn't crash). But no matter what I do I can't make it work. Please help me.
import random
import numpy as np
num_bomb = 10
num_cell_x = 10
num_cell_y = 8
bombs = np.zeros([int(num_cell_y+2),int(num_cell_x+2)],dtype = np.uint)
for i in range(num_bomb):
bombs[random.randint(1,num_cell_y),random.randint(1,num_cell_x)] = 1
num_bombs = np.zeros([num_cell_y,num_cell_x],dtype = np.uint)
# The part that doesn't work:
for x in range(0,num_cell_x):
for y in range(0,num_cell_y):
bomb_count = 0
if bombs[y,x] == 0:
for sy in range(y-1,y+1):
for sx in range(x-1,x+1):
if bombs[sy,sx] == 1:
num_bombs[y,x] += 1
print(bombs)
print()
print(num_bombs)
I think easiest way to do what you want would be to use convolution 2D with kernel np.ones((3, 3))
import scipy.signal
num_bombs = scipy.signal.convolve2d(bombs, np.ones((3, 3), mode='same')
https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html
range(a, b)
generated the number sin range [a, b[ respectively all numbers >= a
but < b
. Therefore you have to generate the ranges range(y-1,y+2)
and range(x-1,x+2)
instead of range(y-1,y+1)
and range(x-1,x+1)
:
for sy in range(y-1,y+2):
for sx in range(x-1,x+2):
# [...]
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.