Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- ## dice rolling prototype
- ## input arg examples
- ## 3 sided 4 dice: 3d4
- ## 6 sided 7 dice: 6d7
- ## add 3 to total: +6
- ## sub 5 from tot: -5
- ##### SPECIAL CASE #####
- ## 10 sided 2 dice produces percentages
- # a test to make sure a variable is a number
- int_test() {
- [ -n "$1" ] &&
- [ "$1" -eq "$1" 2>&- ]
- }
- read INPUT
- TOTAL=0
- for WORD in ${INPUT[@]} ; do #Grab an argument
- {
- [ "${WORD%%[-,+]*}" = "" ] && #Start with a + or - ??
- EXTRA="${WORD#[-,+]}" && #Get the number
- int_test $EXTRA &&
- {
- [ "${WORD%%+*}" = "" ] && #Is it positive ??
- {
- TOTAL=$(( TOTAL + EXTRA ))
- echo "ADD: $EXTRA"
- } || { #Must be negative
- TOTAL=$(( TOTAL - EXTRA ))
- echo "SUB: $EXTRA"
- }
- }
- } && continue || { #Continue to the next arg ??
- SIDES=${WORD%%[d,D]*}
- DICE=${WORD#$SIDES[d,D]}
- int_test "$SIDES" &&
- int_test "$DICE"
- } && { #Correct format ??
- [ $SIDES -eq 10 ] && #Percentage special case ??
- [ $DICE -eq 2 ] &&
- {
- ROLL=$(( RANDOM % SIDES ))
- ROLL2=$(( RANDOM % SIDES ))
- echo "PERCENT: $ROLL$ROLL2%"
- } || { #Roll the dice!!
- CNT=1 ; SUB_TOT=0
- echo "SIDES: $SIDES"
- while [ $DICE -ge $CNT ] ; do
- ROLL=$(( (RANDOM % SIDES)+1 ))
- SUB_TOT=$(( SUB_TOT + ROLL))
- echo " $CNT $ROLL"
- CNT=$(( CNT + 1 ))
- done
- echo "SUB TOT: $SUB_TOT"
- }
- } &&
- TOTAL=$(( TOTAL + SUB_TOT )) ||
- echo "ERROR: $WORD" #Must have been a bad arg
- done
- echo "TOTAL: $TOTAL"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement