# [Code] Chance to cause effect

## Recommended Posts

Hi everyone, I have been working on project that includes weapon which makes enemies fall asleep after hit. I had searched through game files and I haven't found any code lines to make my effect based on luck. I mean that I don't want this effect to occur everytime character hits with the weapon. So maybe you know method to cause sleep on attack every few hits.

This is the code:

------sleep
local function sleepattack(inst, owner, target)
if not target:IsValid() then
--target killed or removed in combat damage phase
return
end

target.SoundEmitter:PlaySound("dontstarve/common/blackpowder_explo")

if target.components.sleeper ~= nil then
elseif target.components.grogginess ~= nil then
end
end

Thanks in advance and have a great day/night

##### Share on other sites
Ultroman    695
```if math.random() < 0.25 then
-- Do thing 25% of the time
end```

math.random() generates a real number between 0.0 and 1.0.

##### Share on other sites

Whoa. I didn't expect such fast response. Thank you very kindly.

##### Share on other sites
Ultroman    695

You're welcome. It was an easy one

The scripting language is called LUA. It's easy to find this sort of language-specific things with a Google search.

Search: lua random

Just so you don't have to wait for an answer next time

Edited by Ultroman

##### Share on other sites
CarlZalph    4116

Alternatively to make it a fixed guarantee to do it X times in Y tries, create a set of Y tries with X of them being the good outcome.

This can be simplified down nicely if X is 1 by using an incrementer and a stored random integer between the set size to compare against.

Example of simplified:

Spoiler
```
local ODDS = 4

local ent = {}
ent.try = 1

local function TrySpecial(ent)
ent.try = ent.try - 1
if ent.try == 0
then
ent.try = ODDS
ent.tryspecial = math.random(1, ODDS)
print("")
end
if ent.try == ent.tryspecial
then
print("special")
else
print("boring")
end
end

for i=1,ODDS*3
do
TrySpecial(ent)
end```

Output:

```
special
boring
boring
boring

boring
boring
special
boring

special
boring
boring
boring
```