Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.75 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. ## dice rolling prototype
  4. ## input arg examples
  5. ## 3 sided 4 dice: 3d4
  6. ## 6 sided 7 dice: 6d7
  7. ## add 3 to total: +6
  8. ## sub 5 from tot: -5
  9. ##### SPECIAL CASE #####
  10. ## 10 sided 2 dice produces percentages
  11.  
  12.  
  13. # a test to make sure a variable is a number
  14. int_test() {
  15.   [ -n "$1" ]                   &&
  16.   [ "$1" -eq "$1" 2>&- ]
  17. }
  18.  
  19.  
  20. read INPUT
  21. TOTAL=0
  22. for WORD in ${INPUT[@]} ; do       #Grab an argument
  23.   {
  24.     [ "${WORD%%[-,+]*}" = "" ]  && #Start with a + or - ??
  25.     EXTRA="${WORD#[-,+]}"       && #Get the number
  26.     int_test $EXTRA             &&
  27.     {
  28.       [ "${WORD%%+*}" = "" ]    && #Is it positive ??
  29.       {
  30.         TOTAL=$(( TOTAL + EXTRA ))
  31.         echo "ADD: $EXTRA"
  32.       } || {                       #Must be negative
  33.         TOTAL=$(( TOTAL - EXTRA ))
  34.         echo "SUB: $EXTRA"
  35.       }
  36.     }
  37.   } && continue || {               #Continue to the next arg ??
  38.     SIDES=${WORD%%[d,D]*}
  39.     DICE=${WORD#$SIDES[d,D]}
  40.     int_test "$SIDES"           &&
  41.     int_test "$DICE"
  42.   } && {                           #Correct format ??
  43.     [ $SIDES -eq 10 ]           && #Percentage special case ??
  44.     [ $DICE  -eq 2  ]           &&
  45.     {
  46.       ROLL=$(( RANDOM % SIDES ))
  47.       ROLL2=$(( RANDOM % SIDES ))
  48.       echo "PERCENT: $ROLL$ROLL2%"
  49.     } || {                         #Roll the dice!!
  50.       CNT=1 ; SUB_TOT=0
  51.       echo "SIDES: $SIDES"
  52.       while [ $DICE -ge $CNT ] ; do
  53.         ROLL=$(( (RANDOM % SIDES)+1 ))
  54.         SUB_TOT=$(( SUB_TOT + ROLL))
  55.         echo " $CNT $ROLL"
  56.         CNT=$(( CNT + 1 ))
  57.       done
  58.       echo "SUB TOT: $SUB_TOT"
  59.     }
  60.   }                             &&  
  61.    TOTAL=$(( TOTAL + SUB_TOT )) ||
  62.    echo "ERROR: $WORD"             #Must have been a bad arg
  63. done
  64. echo "TOTAL: $TOTAL"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement