0 votes

I am attempting to create a sort of random item generator. I have a database that stores the base stats for an item. When the item is created in the world, a function randomizes the item's stats. Here is an example of my code:

toughness = randi() % (toughness + 3) + (toughness - 3)

Before this point in the code, toughness can be one of 4 values: 1, 2, 3, and 5. Now this is my understanding of how this should work, given toughness == 1 before this line of code, I would think that a random integer between -2 and 4 would be chosen. Sometimes, it chooses 0.

For the purposes of my code this is okay, toughness can be 0. However, it will throw an error saying "Division by Zero in operator '%'" and it points to this line of code. So I'm assuming this is not good code, but I'm not entirely sure why.

What exactly is randi() doing here? From my point of view, I don't see any division so I'm clearly misunderstanding how this works. Is there a better way for me to implement this? Perhaps a way that doesn't allow it to choose zero? Or is there something else I could use so that zero would be an allowable solution?

Thanks in advance for your time and consideration.

in Engine by (15 points)

1 Answer

+2 votes
Best answer

randi() is not your problem. This just produces a random integer.

I don't see any division

The % operator gives the remainder after division. When toughness is -3, you're asking "what's the remainder when I divide by 0"?

Using your formula, when toughness is 1, you're doing randi() % 4, which results in either 0, 1, 2, or 3. You then add -2, resulting in -2, -1, 0, or 1.

Now you have your problem. If toughness is -1, then randi() % 2 is either 0 or 1. Adding -4 gives either -4 or -3. Boom, division by 0.

by (18,975 points)
selected by

Okay I think I see where I went wrong now. Thank you very much for your help!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.

Categories