Debian Codegraph @

modules/gameserv/dice.c

raw
1 /*
2 * Copyright (c) 2005-2007 William Pitcock <[email protected]>
3 * Copyright (c) 2006-2007 Jilles Tjoelker <[email protected]>
4 *
5 * Rights to this code are documented in doc/LICENSE.
6 *
7 * Dice generator.
8 *
9 */
10
11 #include "atheme.h"
12 #include "gameserv_common.h"
13
14 #include <math.h>
15
16 DECLARE_MODULE_V1("gameserv/dice", false, _modinit, _moddeinit, PACKAGE_STRING, VENDOR_STRING);
17
18 static void command_dice(sourceinfo_t *si, int parc, char *parv[]);
19 static void command_calc(sourceinfo_t *si, int parc, char *parv[]);
20
21 command_t cmd_dice = { "ROLL", N_("Rolls one or more dice."), AC_NONE, 3, command_dice, {.path = "gameserv/roll"} };
22 command_t cmd_calc = { "CALC", N_("Calculate stuff."), AC_NONE, 3, command_calc, {.path = "gameserv/calc"} };
23
24 static unsigned int max_rolls = 10;
25
26 void _modinit(module_t * m)
27 {
28 service_t *svs;
29
30 service_named_bind_command("chanserv", &cmd_dice);
31 service_named_bind_command("chanserv", &cmd_calc);
32
33 svs = service_find("gameserv");
34 if (!svs)
35 return;
36
37 service_bind_command(svs, &cmd_dice);
38 service_bind_command(svs, &cmd_calc);
39
40 add_uint_conf_item("MAX_ROLLS", &svs->conf_table, 0, &max_rolls, 1, INT_MAX, 10);
41 }
42
43 void _moddeinit(module_unload_intent_t intent)
44 {
45 service_t *svs;
46
47 service_named_unbind_command("chanserv", &cmd_dice);
48 service_named_unbind_command("chanserv", &cmd_calc);
49
50 svs = service_find("gameserv");
51 if (!svs)
52 return;
53
54 service_unbind_command(svs, &cmd_dice);
55 service_unbind_command(svs, &cmd_calc);
56
57 del_conf_item("MAX_ROLLS", &svs->conf_table);
58 }
59
60 #define CALC_MAX_STACK (128)
61
62 #define DICE_MAX_DICE (100)
63 #define DICE_MAX_SIDES (100)
64
65 int do_calc_expr(sourceinfo_t *si, char *expr, char *errmsg, double *presult);
66 int do_calc_eval(sourceinfo_t *si, double lhs, char oper, double rhs, double *out, char *errmsg);
67 int is_calcoper(char oper);
68
69 //
70 // <expr>
71 // expr = {<op>(<expr>)}|{<op><expr>}
72 // op = { ~ ! d * / % \ ^ + - & $ | }
73 //
74 // [Rank 1] | [Rank 4]
75 // ~ = One's compliment | + - = Add / Subtract
76 // ! = Logical NOT |
77 // d = Dice Generator, LOL. | [Rank 5]
78 // | & = Bitwise AND
79 // [Rank 2] |
80 // ^ = Power | [Rank 6]
81 // | $ = Bitwise XOR (eXclusive OR)
82 // [Rank 3] |
83 // * / = Multiply / Divide | [Rank 7]
84 // % \ = Modulus / Integer-divide | | = Bitwise inclusive OR
85 //
86 static bool eval_calc(sourceinfo_t *si, char *s_input)
87 {
88 static char buffer[1024];
89
90 char *ci = s_input;
91
92 int err, braces = 0;
93 double expr;
94
95
96 if (s_input == NULL)
97 {
98 command_fail(si, fault_badparams, _("Error: You typed an invalid expression."));
99 return false;
100 }
101
102 // Skip leading whitespace
103 while (*ci && isspace((unsigned char)*ci))
104 ci++;
105
106 if (!*ci)
107 {
108 command_fail(si, fault_badparams, _("Error: You typed an invalid expression."));
109 return false;
110 }
111
112 // Validate braces
113 while (*ci)
114 {
115 if (*ci == '(')
116 {
117 braces++;
118 }
119 else if (*ci == ')')
120 {
121 if (--braces < 0)
122 break; // mismatched!
123 }
124 else if (!isspace((unsigned char)*ci) && !isdigit((unsigned char)*ci) && *ci != '.' && !is_calcoper(*ci))
125 {
126 command_fail(si, fault_badparams, _("Error: You typed an invalid expression."));
127 return false;
128 }
129 ci++;
130 }
131
132 if (braces != 0)
133 {
134 command_fail(si, fault_badparams, _("Error: Mismatched braces '( )' in expression."));
135 return false;
136 }
137
138 err = do_calc_expr(si, s_input, buffer, &expr);
139
140 if (!err)
141 {
142 if (strlen(s_input) > 250)
143 {
144 mowgli_strlcpy(buffer, s_input, 150);
145 sprintf(&buffer[150], "...%s = %.8g", &s_input[strlen(s_input) - 10], expr);
146 }
147 else
148 {
149 sprintf(buffer, "%s = %.8g", s_input, expr);
150 }
151 }
152 else
153 return false;
154
155 gs_command_report(si, "%s", buffer);
156 return true;
157 }
158
159
160 //////////////////////////////////////////////////////////////////////////
161
162 enum
163 {
164 CALCEXPR_VALUE,
165 CALCEXPR_OPER
166 };
167
168 typedef struct _tagCalcStack
169 {
170 double _value;
171 char _oper;
172 int _rank;
173 int _brace;
174 } CalcStack;
175
176 int do_calc_expr(sourceinfo_t *si, char *expr, char *errmsg, double *presult)
177 {
178 int expect = CALCEXPR_VALUE, lastrank, currank;
179 char *cur = expr, *endptr, lastop, curop = ' ';
180 double total, curval = 0;
181 static int nStack = 0; // Current stack position
182 static CalcStack pStack[CALC_MAX_STACK]; // Value stack
183
184 nStack = 0;
185
186 total = 0;
187 lastrank = is_calcoper(lastop = '+');
188
189 while (*cur)
190 {
191 switch (expect)
192 {
193 case CALCEXPR_VALUE:
194 {
195 curval = strtol(cur, &endptr, 10);
196 if (*endptr == '.' || (curval < -2000000000 || curval > 2000000000))
197 curval = strtod(cur, &endptr);
198 if (cur == endptr)
199 { // didn't go anywhere! o.O
200 if (*cur == '(')
201 {
202 if (curop != ' ')
203 {
204 command_fail(si, fault_badparams, _("Error: Missing expected value in expression."));
205 return 1;
206 }
207 cur++; // skip it
208 pStack[nStack]._value = total;
209 pStack[nStack]._oper = lastop;
210 pStack[nStack]._rank = lastrank;
211 pStack[nStack++]._brace = 1;
212 total = 0;
213 lastrank = is_calcoper(lastop = '+');
214 }
215 else if ((currank = is_calcoper(curop = *cur)))
216 {
217 if (currank != 1)
218 { // Unary: ~!
219 command_fail(si, fault_badparams, _("Error: Missing expected value in expression."));
220 return 1;
221 }
222 cur++; // skip unary op
223 }
224 else
225 {
226 command_fail(si, fault_badparams, _("Error: You typed an invalid expression."));
227 return 1;
228 }
229 }
230 else
231 {
232 // got value... grab next operator
233 if (curop != ' ')
234 {
235 // LHS ignored -- unary ops only have RHS :)
236 if (do_calc_eval(si, 0, curop, curval, &curval, errmsg))
237 {
238 return 1; // error
239 }
240 }
241 cur = endptr;
242 expect = CALCEXPR_OPER;
243 }
244 break;
245 }
246 case CALCEXPR_OPER:
247 {
248 currank = is_calcoper(curop = *cur);
249 if (curop == '(')
250 {
251 cur--;
252 currank = is_calcoper(curop = '*');
253 }
254 if (currank == 0)
255 {
256 if (curop == ')')
257 {
258 do
259 {
260 if (do_calc_eval(si, total, lastop, curval, &curval, errmsg))
261 {
262 return 1; // error
263 }
264 total = pStack[--nStack]._value;
265 lastop = pStack[nStack]._oper;
266 lastrank = pStack[nStack]._rank;
267 } while (!pStack[nStack]._brace);
268 expect = CALCEXPR_OPER;
269 }
270 else
271 {
272 command_fail(si, fault_badparams, _("Error: Missing expected operator in expression."));
273 return 1;
274 }
275 }
276 else if (currank < lastrank)
277 { // operator precedence (new over old!)
278 pStack[nStack]._value = total;
279 pStack[nStack]._oper = lastop;
280 pStack[nStack]._rank = lastrank;
281 pStack[nStack++]._brace = 0;
282 total = curval;
283 lastop = curop;
284 lastrank = currank;
285 currank = is_calcoper(curop = ' ');
286 expect = CALCEXPR_VALUE;
287 }
288 else
289 { // previous opers have precedence -- work backwards (until start/brace)
290 while (currank >= lastrank)
291 {
292 if (do_calc_eval(si, total, lastop, curval, &curval, errmsg))
293 {
294 return 1; // error
295 }
296 if (nStack == 0)
297 break;
298 if (pStack[nStack - 1]._brace || currank < pStack[nStack - 1]._rank)
299 break;
300 total = pStack[--nStack]._value;
301 lastop = pStack[nStack]._oper;
302 lastrank = pStack[nStack]._rank;
303 }
304 total = curval;
305 lastop = curop;
306 lastrank = currank;
307 currank = is_calcoper(curop = ' ');
308 expect = CALCEXPR_VALUE;
309 }
310 cur++;
311 break;
312 }
313 }
314 if (nStack >= CALC_MAX_STACK)
315 {
316 command_fail(si, fault_badparams, _("Error: Expression is too deeply nested."));
317 return 1;
318 }
319 // skip whitespace
320 while (*cur && isspace((unsigned char)*cur))
321 cur++;
322 }
323
324 // Did we end on an operator instead of a value?
325 if (expect == CALCEXPR_VALUE)
326 {
327 command_fail(si, fault_badparams, _("Error: Missing expected value in expression."));
328 return 1;
329 }
330
331 // Wind back up the stack, if it exists (including last value!)
332 while (nStack > -1)
333 {
334 if (do_calc_eval(si, total, lastop, curval, &curval, errmsg))
335 {
336 return 1; // error
337 }
338 if (nStack == 0)
339 break;
340 total = pStack[--nStack]._value;
341 lastop = pStack[nStack]._oper;
342 // rank doesn't matter now
343 }
344
345 *presult = curval;
346 return 0; // no error
347 }
348
349
350 static double calc_dice_simple(double lhs, double rhs)
351 {
352 double out = 0.0;
353 int i, sides, dice;
354
355 dice = floor(lhs);
356 sides = floor(rhs);
357
358 if (dice < 1 || dice > 100)
359 return 0.0;
360
361 if (sides < 1 || sides > 100)
362 return 0.0;
363
364 for (i = 0; i < dice; i++)
365 {
366 out += 1.0 + (arc4random() % sides);
367 }
368
369 return out;
370 }
371
372 //////////////////////////////////////////////////////////////////////////
373
374 int do_calc_eval(sourceinfo_t *si, double lhs, char oper, double rhs, double *out, char *errmsg)
375 {
376 switch (oper)
377 {
378 case '~': // 1's compliment (unary)
379 *out = (double)(~(long long)rhs);
380 break;
381 case '!': // NOT (unary)
382 *out = (double)(!(long long)rhs);
383 break;
384 case 'd':
385 *out = calc_dice_simple(lhs, rhs);
386 break;
387 case '*': // multiplication
388 *out = lhs * rhs;
389 break;
390 case '/': // division
391 case '%': // MOD
392 case '\\': // DIV
393 if (rhs <= 0.0 || (oper == '%' && ((long long)rhs == 0)))
394 {
395 command_fail(si, fault_badparams, _("Error: Cannot perform modulus or division by zero."));
396 return 1;
397 }
398
399 switch (oper)
400 {
401 case '/':
402 *out = lhs / rhs;
403 break;
404 case '%':
405 *out = (double)((long long)lhs % (long long)rhs);
406 break;
407 case '\\':
408 lhs /= rhs;
409 *out = (lhs < 0) ? ceil(lhs) : floor(lhs);
410 break;
411 }
412 break;
413 case '^': // power-of
414 *out = pow(lhs, rhs);
415 break;
416 case '+': // addition
417 *out = lhs + rhs;
418 break;
419 case '-': // subtraction
420 *out = lhs - rhs;
421 break;
422 case '&': // AND (bitwise)
423 *out = (double)((long long)lhs & (long long)rhs);
424 break;
425 case '$': // XOR (bitwise)
426 *out = (double)((long long)lhs ^ (long long)rhs);
427 break;
428 case '|': // OR (bitwise)
429 *out = (double)((long long)lhs | (long long)rhs);
430 break;
431 default:
432 command_fail(si, fault_unimplemented, _("Error: Unknown mathematical operator %c."), oper);
433 return 1;
434 }
435
436 return 0;
437 }
438
439 //////////////////////////////////////////////////////////////////////////
440
441 // Is 'oper' an operator? If so, return its 'rank', else '0'.
442 //
443 int is_calcoper(char oper)
444 {
445 static char *opers = "~!d ^ */%\\ +- & $ |";
446 char *c = opers;
447 int rank = 1;
448
449 while (*c && *c != oper)
450 {
451 if (*c == ' ')
452 rank++;
453 c++;
454 }
455
456 return (*c ? rank : 0);
457 }
458
459 /*************************************************************************************/
460
461 static bool eval_dice(sourceinfo_t *si, char *s_input)
462 {
463 static char buffer[1024], result[32];
464
465 char op = '\0', *c = s_input;
466 unsigned int dice, roll, x, y, z = 0;
467 double total;
468
469 while (*c && isspace((unsigned char)*c))
470 ++c;
471 if (!*c || !isdigit((unsigned char)*c))
472 {
473 gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
474 return false;
475 }
476
477 x = strtoul(c, &c, 10);
478 if (x == 0 || c == NULL || ToLower(*c++) != 'd' || !isdigit((unsigned char)*c))
479 {
480 if (x < 1 || x > DICE_MAX_DICE)
481 {
482 gs_command_report(si, _("Only 1-100 dice may be thrown at once."));
483 return false;
484 }
485
486 gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
487 return false;
488 }
489
490 y = strtoul(c, &c, 10);
491 if (c != NULL)
492 {
493 while (*c && isspace((unsigned char)*c))
494 ++c;
495
496 if (*c && strchr("-+*/", *c) == NULL)
497 {
498 gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
499 return false;
500 }
501 }
502
503 if (x < 1 || x > 100)
504 {
505 gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
506 return false;
507 }
508
509 if (y < 1 || y > DICE_MAX_SIDES)
510 {
511 gs_command_report(si, _("Only 1-100 sides may be used on a dice."));
512 return false;
513 }
514
515 if (*c)
516 {
517 op = *c++;
518
519 z = strtoul(c, &c, 10);
520
521 while (*c && isspace((unsigned char)*c))
522 ++c;
523
524 if (*c)
525 {
526 gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
527 return false;
528 }
529 else if (op == '/' && z == 0)
530 {
531 gs_command_report(si, _("Can't divide by zero."));
532 return false;
533 }
534 }
535
536 total = 0.0;
537 snprintf(buffer, 1024, _("\2%s\2 rolled %ud%u: "), si->su->nick, x, y);
538 for (roll = 0; roll < x; ++roll)
539 {
540 snprintf(result, 32, "%d ", dice = (1 + (arc4random() % y)));
541 mowgli_strlcat(buffer, result, sizeof(buffer));
542 total += dice;
543 }
544
545 if (op == '\0')
546 snprintf(result, 32, _(" <Total: %g>"), total);
547 else
548 {
549 snprintf(result, 32, _(" <Total: %g(%c%u) = "), total, op, z);
550 mowgli_strlcat(buffer, result, sizeof(buffer));
551 switch (op)
552 {
553 case '+':
554 total += z;
555 break;
556 case '-':
557 total -= z;
558 break;
559 case '/':
560 total /= z;
561 break;
562 case '*':
563 total *= z;
564 break;
565 default:
566 break;
567 }
568 snprintf(result, 32, "%g>", total);
569 }
570 mowgli_strlcat(buffer, result, sizeof(buffer));
571
572 gs_command_report(si, "%s", buffer);
573 return true;
574 }
575
576 static void command_dice(sourceinfo_t *si, int parc, char *parv[])
577 {
578 char *arg;
579 mychan_t *mc;
580 int i, times = 1;
581
582 if (!gs_do_parameters(si, &parc, &parv, &mc))
583 return;
584 if (parc < 1)
585 {
586 command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "ROLL");
587 command_fail(si, fault_needmoreparams, _("Syntax: ROLL [times] [dice]d<sides>"));
588 return;
589 }
590 if (parc < 2)
591 arg = parv[0];
592 else
593 {
594 times = atoi(parv[0]);
595 arg = parv[1];
596
597 if (times > max_rolls)
598 times = max_rolls;
599 }
600
601 if (!strcasecmp("RICK", arg))
602 {
603 gs_command_report(si, _("Never gonna give you up; Never gonna let you down"));
604 gs_command_report(si, _("Never gonna run around and desert you; Never gonna make you cry"));
605 gs_command_report(si, _("Never gonna say goodbye; Never gonna tell a lie and hurt you"));
606 return;
607 }
608
609 for (i = 0; i < times; i++)
610 if(!eval_dice(si, arg))
611 break;
612 }
613
614 static void command_calc(sourceinfo_t *si, int parc, char *parv[])
615 {
616 char *arg;
617 mychan_t *mc;
618 int i, times = 1;
619
620 if (!gs_do_parameters(si, &parc, &parv, &mc))
621 return;
622 if (parc < 1)
623 {
624 command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "CALC");
625 command_fail(si, fault_needmoreparams, _("Syntax: CALC [times] <expression>"));
626 return;
627 }
628 if (parc < 2)
629 arg = parv[0];
630 else
631 {
632 times = atoi(parv[0]);
633 arg = parv[1];
634
635 if (times > max_rolls)
636 times = max_rolls;
637 }
638
639 for (i = 0; i < times; i++)
640 if (!eval_calc(si, arg))
641 break;
642 }
643
644 //////////////////////////////////////////////////////////////////////////