azihassan / LED-snake

Snake on a 8x8 LED matrix
2 stars 1 forks source link

Random number generation issues #1

Open azihassan opened 7 years ago

azihassan commented 7 years ago

Since srand() is always called with the same seed, the player will be able to predict where the food will show up. One solution for this issue would be to increment and store the seed in the EEPROM every time the game is ran. This however could reduce the EEPROM lifetime, but maybe I'm overthinking this. I wonder if there's another way to generate a seed randomly using, say, external factors ?

In addition to this, the food placement algorithm will be slower when the snake grows. Ideally, place_food() should make an array of empty coordinates and select a random coordinate from that array. This will guarantee that rand() will only be called once (not tested) :

uint8_t r, i = 0, size = world.width * world.height - snake.length;
uint8_t empty[size]; //indexes of the empty cells
for(r = 0; r < world.width * world.height; r++)
{
    if(world.grid[r] == EMPTY)
        empty[i++] = r;
}
world.grid[rand() % size] = FOOD;

If variable-length arrays are supported, this would be a relatively OK solution.

azihassan commented 7 years ago

Alright, it turns out VLAs are indeed supported but it has been brought to my attention (in a r/ECE thread) that allocating such a large array on the stack might not be a good idea after all. In a 8x8 grid, it could take up to 61 bytes (since the snake always occupies at least 3 dots), so if allocating a 61 byte array on the stack doesn't overflow it then the solution suggested above should work. Otherwise I will have to make it static.