Godot Version
Godot 4.2
Question
Hello, i just started using godot recently after learning some basics about coding.
I was trying to make a minesweeper game just to learn about grid based games and stuff like that, and i got to the part of code where i have choose which tiles have to be mines and which dont
somehow after hours of trial and error i managed to finish it, but i dont understand at all why this works, and why what i did originally didn’t. The problem i had was that, 90% of the time i reached the place_mine() func when turning on the game, the game would crash and say “out of bounds get index … (on base: ‘Array’)”
it still happens like 5-10% of the time now and i want to fix it, but don’t know how, so if someone could explain why this happens to me that would be great
notes:
1 tile_data is an array that has all the tiles in it
2 had to replace the asterisks with × because it made the text italicized
3 the place_mine() func was just made to see if its working properly, thats why i put ‘i’ in there
4 this is in gdscript
this is the code that ended up working:
func set_mines():
# Grab z random numbers from 1 to xy
# Will be using these numbers as placeholders for now: z=40, x=16, y=16
# These will be changed in the future if I decide to add a method to change them in game
var x := 16
var y := 16
var z := 40
tile_bomb.append(tile_data.pick_random())
for i in range(z):
var random_number = randi() % (x×y)
i-=1
if tile_data[random_number] not in tile_bomb:
tile_bomb.append(tile_data[random_number])
place_mine(i, tile_bomb[i-1])
this is the one that didn’t work:
func set_mines():
# Grab z random numbers from 1 to xy
# Will be using these numbers as placeholders for now: z=40, x=16, y=16
# These will be changed in the future if I decide to add a method to change them in game
var x := 16
var y := 16
var z := 40
for a in range(1):
tile_bomb.append(tile_data.pick_random())
for i in range(zzz):
place_mine(i, tile_bomb[i])
var random_number = randi() % (x*y)
if tile_data[random_number] in tile_bomb:
i=i-1
continue;
tile_bomb.append(tile_data[random_number])
if tile_bomb.size() >= z:
break;