Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Random number generation issues #1

Open
azihassan opened this issue Nov 4, 2016 · 1 comment
Open

Random number generation issues #1

azihassan opened this issue Nov 4, 2016 · 1 comment

Comments

@azihassan
Copy link
Owner

azihassan commented Nov 4, 2016

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
Copy link
Owner Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant