Hello! I've been trying to code a random number generator for a text-based combat game, the code compiles but I get the same result every time no matter what, I tried rebuilding the program a bunch of times but it still didn't work. Any idea how to do this?
It's working perfectly. A random number is being generated each time & the appropriate if statement is being executed.
Codeblocks shouldn't matter much, but I think it may use a different compiler. I was using codeBlocks, but I migrated to Virtual Studio; & I'm glad I did. It has a locals window which allows you to view variables as you step-through the code. Seeing in your program that random numbers are being generated.
Try adding a loop so you can see the result of generated random numbers more than one time. Your "hit/miss" test is set low enough that a hit is a very uncommon event:
#include <iostream>
#include <random>
#include <ctime>
int main()
{
std::default_random_engine randomGenerator(time(0));
std::uniform_real_distribution<float> attackRoll(0.0f, 1.0f);
std::cout << "I am attacking a goblin!\n\n";
for (int i { }; i < 25; i++)
{
float attack = attackRoll(randomGenerator);
if(attack <= 0.3f)
{
std::cout << "I hit the goblin! yasss!\n";
}
else
{
std::cout << "I missed the goblin oh nooooo!\n";
}
}
}
Nothing wrong with your code that I can see, other than needing a loop.
Personally I'd have gone with a uniform_int_distribution of (0, 10). 3 or less is a hit, 0 is a critical hit. But, of course, YMMV. "Hitting" with an int distribution would still be an uncommon event.
std::random_device is not fully implemented with MinGW. At least up to and including the MinGW version included with Code::Blocks it is still not working correctly. The entropy of std::random_device with C::B is zero. The series of numbers obtained from a random engine seeded with std::random_device are predictably repetitive and non-random. https://en.cppreference.com/w/cpp/numeric/random/random_device/entropy
Code::Blocks, or MSVC, using <ctime>'s time() function does provide somewhat of a changeable seed. The OP's real problem was not obtaining a a sufficient series of random numbers with a particularly low threshhold if condition.
Now, if the OP switches over to VS then std::random_device is a good seed choice.