60 lines
1.3 KiB
C
60 lines
1.3 KiB
C
#include "stdlib.h"
|
|
#include "stdio.h"
|
|
#include "string.h"
|
|
#include "memory.h"
|
|
|
|
int rolld(int d) {
|
|
return rand() % d + 1;
|
|
}
|
|
|
|
int rollnd(int n, int d, int* i) {
|
|
int total=0;
|
|
while(n-->0) {
|
|
int roll = rolld(d);
|
|
total += roll;
|
|
if(i!=(void*)0)
|
|
*(i++) = roll;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
int process_dice_format(const char* format,int* num,int* die) {
|
|
int dummy; // dummy int for if either of the out adresses is 0
|
|
if(num==(void*)0)num=&dummy;
|
|
if(die==(void*)0)die=&dummy;
|
|
char buf[10];
|
|
memset(buf,0,10); // clear buffer
|
|
char* bufw=buf;
|
|
const char* next=format;
|
|
while(*next!='\0') {
|
|
if(*next=='d') { // argument is d in <num>d<die> format
|
|
if(next==format) // if there is no die count given, assume 1
|
|
*num=1;
|
|
else
|
|
*num=atoi(buf); // store buffered string as number
|
|
memset(buf,0,10); // clear buffer
|
|
bufw=buf; // reset buffer walker
|
|
next++; // skip
|
|
}
|
|
*bufw=*next; // buffer next character
|
|
bufw++;next++; // increment walker and next character
|
|
}
|
|
*die=atoi(buf);
|
|
return 0;
|
|
}
|
|
|
|
void roll_and_print(int n, int d) {
|
|
int* out_rolls=malloc(sizeof(int)*n);
|
|
int result=rollnd(n,d,out_rolls);
|
|
printf(" %d (%dd%d) ",result,n,d);
|
|
// only print inbetween steps if there are any
|
|
if(n>1) {
|
|
for(int i=0;i<n;++i) {
|
|
printf("%d%s",out_rolls[i],i==n-1?"\n":"+");
|
|
}
|
|
} else {
|
|
printf("\n");
|
|
}
|
|
free(out_rolls);
|
|
}
|