Some other tips.
(Sorry, this is going to be a big info dump.)
Array indices are 0-based - the first item is item 0, not item 1.
racer is actually the second item in the array and
racer is actually ouside the bounds of the array (so you’re trying to access an invalid array element).
This also means that
random(1, 35) will always skip the first item in the array (item 0).
Your array has 36 entries, so to properly use
random to get a random index you’d either need to do
With the random function, the first argument (the lower bound) is inclusive but the second argument (the upper bound) is exclusive (i.e. the upper bound is excluded from the possible outputs), so
random(0, 36) will output a number between 0 and 35 (inclusive, i.e.
35 are included).
However, instead of having to remember how big your array is,
if you use the
getSize function from here:
getSize(lizardNames) will give you the number of entries in the
(Don’t worry about how it works for now (it’s effectively high-level arcane wizardry), instead just worry about how to use it.)
Then you can do
random(getSize(lizardNames)) to get a valid index between
getSize(lizardNames) - 1 (i.e. all valid indices).
And lastly, instead of rewriting the entire array each time, there’s a better (more scalable) way to ensure unique numbers:
// Checks whether the given nameIndex is unique in the given range of elements
bool isNameIndexUnique(uint8_t nameIndex, uint8_t count)
// For all chosen elements
for(uint8_t index = 0; index < count; ++index)
// If the nameIndex matches
if(racers[index] == nameIndex)
// The nameIndex is not unique
// None of the nameIndexes matched
// So the nameIndex is unique
// Generates unique name indices into the racers array
// For each item in racers
for(uint8_t index = 0; index < getSize(racers); ++index)
// Stores whether or not the name index is unique
bool unique = false;
// Start an infinite loop
// Generate a name index
uint8_t nameIndex = random(getSize(lizardNames));
// If name is unique
// Write the nameIndex to the array
racer[index] = nameIndex;
// Break out of the infinite loop
It might look like a lot more code, but it’s actually not that much larger and this should hopefully be a bit more efficient.
And most importantly, it will still work if you change the number of racers.
(I’ll admit I haven’t actually tested this, but I’m fairly confident that it should work.)
And some final minor points:
- You don’t need to put
if(!arduboy.nextFrame()) because you clear the buffer later on.
- You should move
- ALL_CAPS should only be used for macros (
- (Hence why I keep writing
lizardNames instead of
- Arrays should (almost) always have plural names because they’re a collection of more than one object.
- (Hence why I wrote
racers instead of