summaryrefslogtreecommitdiff
path: root/src/dice.cc
blob: 187bae6892c2bd0e03d0ec5f191c0fe48dd6f18c (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "dice.hpp"

#include "z-rand.hpp"

#include <cassert>

void dice_init(dice_type *dice, long base, long num, long sides)
{
	assert(dice != NULL);

	dice->base = base;
	dice->num = num;
	dice->sides = sides;
}

bool_ dice_parse(dice_type *dice, cptr s)
{
	long base, num, sides;

	if (sscanf(s, "%ld+%ldd%ld", &base, &num, &sides) == 3)
	{
		dice_init(dice, base, num, sides);
		return TRUE;
	}

	if (sscanf(s, "%ld+d%ld", &base, &sides) == 2)
	{
		dice_init(dice, base, 1, sides);
		return TRUE;
	}

	if (sscanf(s, "d%ld", &sides) == 1)
	{
		dice_init(dice, 0, 1, sides);
		return TRUE;
	}

	if (sscanf(s, "%ldd%ld", &num, &sides) == 2)
	{
		dice_init(dice, 0, num, sides);
		return TRUE;
	}

	if (sscanf(s, "%ld", &base) == 1)
	{
		dice_init(dice, base, 0, 0);
		return TRUE;
	}

	return FALSE;
}

void dice_parse_checked(dice_type *dice, cptr s)
{
	bool_ result = dice_parse(dice, s);
	if (!result)
	{
		abort();
	}
}

long dice_roll(dice_type *dice)
{
	assert(dice != NULL);
	return dice->base + damroll(dice->num, dice->sides);
}

void dice_print(dice_type *dice, char *output)
{
	char buf[16];

	output[0] = '\0';

	if (dice->base > 0)
	{
		sprintf(buf, "%ld", dice->base);
		strcat(output, buf);
	}

	if ((dice->num > 0) || (dice->sides > 0))
	{
		if (dice->base > 0)
		{
			strcat(output, "+");
		}

		if (dice->num > 1)
		{
			sprintf(buf, "%ld", dice->num);
			strcat(output, buf);
		}

		strcat(output, "d");

		sprintf(buf, "%ld", dice->sides);
		strcat(output, buf);
	}
}