-
Notifications
You must be signed in to change notification settings - Fork 4
/
dice.pegjs
81 lines (73 loc) · 1.84 KB
/
dice.pegjs
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
start
= left:roll ";" right:start {
var on = [left, right];
if (right.type == 'aggregate') {
on = [left];
on.push.apply(on, right.on);
}
return {
'type': 'aggregate',
'value': 0,
'on': on,
'kind': "" + left.kind + "; " + right.kind }}
/ roll
roll
= left:die "+" right:roll {
var on = [left, right];
var result = left.value + right.value;
if (right.type == 'sum') {
on = [left];
on.push.apply(on, right.on);
}
return {
'type': 'sum',
'value': result,
'on': on,
'kind': "" + left.kind + " +" + right.kind }}
/ left:die "-" right:roll {
var on = [left, right];
var result;
if (right.type == 'difference') {
on = [left];
on.push.apply(on, right.on);
}
if (left.type == 'int') {
if (right.type == 'difference') {
result = (- left.value) + right.value;
} else {
result = - (left.value + right.value);
}
} else {
if (right.type == 'difference') {
result = left.value + right.value;
} else {
result = left.value - right.value;
}
}
return {
'type': 'difference',
'value': result,
'on': on,
'kind': "" + left.kind + " -" + right.kind }}
/ die
die
= qty:(integer / "") [dD] ceil:integer {
if (qty > 1024 || ceil > 1024) {
throw "values too large"
}
if (qty == "") qty = 1;
var result = 0;
var on = [];
for (var i = 0; i < qty; i++) {
var _r = Math.floor(Math.random() * ceil) + 1;
result += _r;
on.push(_r);
}
return {
'type': 'roll',
'value': result,
'on': on,
'kind': "" + qty + "D" + ceil }}
/ val:integer { return { 'type': 'int', 'value': val, 'kind': "" + val } }
integer "integer"
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }