'Python - How to correctly balance an array?
I have a code in python that doesn't seem to work as intended. The goal of the code is to take in a randomly generated 2D list of numbers on a square grid-like [[0,1,3],[4,5,0],[2,5,3]], detect if any of the values are superior to 4, and if so, make its value is reduced by 4 and all its neighbors (if not inside border of the square grid) are raised by 1.
I have a theoretically correct code that does the job but there is an issue:
def balance_terrain():
global grid, size_grid
grid_mem = grid.copy()
for x in range(size_grid):
for y in range(size_grid):
if grid[y][x] >= 4:
grid_mem[y][x] -= 4
if y-1 >= 0:
grid_mem[y-1][x] += 1
if y+1 < taille_plateau:
grid_mem[y+1][x] += 1
if x-1 >= 0:
grid_mem[y][x-1] += 1
if x+1 < taille_plateau:
grid_mem[y][x+1] += 1
grid = grid_mem.copy()
show_grid_to_screen(grid)
The problem with this code is that if a space is, for example, equal to 3, which means it shouldn't try to balance itself, but one of its neighbors makes it equal 4, then it triggers for that square in the same turn when it shouldn't.
How do I modify the code so that only the spaces that are in the current state and are equal or more than 4, triggers but not the ones that will be equal or more than 4 in the same turn?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
