Skip to content

Random number generation issues #1

Description

@azihassan

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions