-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRNGesus.js
More file actions
82 lines (82 loc) · 2.14 KB
/
Copy pathRNGesus.js
File metadata and controls
82 lines (82 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class RNGesus
{
static die(sides)
{
return Math.ceil(Math.random()*sides);
}
static roll(roll_spec)
{
let count = 1;
let sides = 0;
let offset = 0;
let current = "";
let mode = "count";
let negative=false;
for(let i=0;i<roll_spec.length;i++)
{
let c = roll_spec[i];
if(c>='0' && c<='9')
{
current+=c;
}
else
{
if(mode == "count" && c=="d")
{
count = current==""?1:parseInt(current);
current ="";
mode="sides";
continue;
}
if(mode=="sides" && (c=="-" || c=="+"))
{
sides = current==""?0:parseInt(current);
current ="";
mode="offset";
if(c=="-")
{
negative=true;
}
continue;
}
console.warn("Invalid dice roll spec (unknown char '"+c+"' at "+i+"): \""+roll_spec+"\"");
return 0;
}
}
switch(mode)
{
case "count":
{
count = current==""?1:parseInt(current);
break;
}
case "sides":
{
sides = current==""?1:parseInt(current);
break;
}
case "offset":
{
offset = current==""?1:parseInt(current);
break;
}
}
if(negative)
{
offset*=-1;
}
if(sides==0)
{
console.warn("Invalid dice roll spec (0 sides): \""+roll_spec+"\"");
return 0;
}
let result = 0;
console.log("Rolling <"+roll_spec+">, "+count+" "+sides+"-sided dice"+(offset==0?"": " offset by "+offset)+".")
for(let i=0;i<count;i++)
{
result+=this.die(sides);
}
result+=offset;
return result;
}
}