Advertisement
etlon

dnd dice

Jul 16th, 2020
633
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package calc;
  2.  
  3. import java.util.concurrent.ThreadLocalRandom;
  4.  
  5. public abstract class Dice {
  6.    
  7.     public static int roll(String s) {
  8.         //1d8+20
  9.        
  10.         //Teilt den String "1d8+20" in ein Array mit "1" und "8+20" ein
  11.         String[] arr = s.split("(d)");
  12.        
  13.         //teilt den zweiten Teil des Arrays "8+20" in ein neues Array mit "8", "+" und "20" ein
  14.         String diceMaxOperatorBonus = arr[1];
  15.         String[] diceMaxOperatorBonusSplit = splitKeep(diceMaxOperatorBonus);
  16.        
  17.         //Speicherung aller einzelnen Werte in Variablen
  18.         int amountRoll = Integer.parseInt(arr[0]);
  19.         int diceMax = Integer.parseInt(diceMaxOperatorBonusSplit[0]);
  20.         char operator = '.';
  21.         int bonus = 0;
  22.         try {
  23.             operator = diceMaxOperatorBonusSplit[1].charAt(0);
  24.             bonus = Integer.parseInt(diceMaxOperatorBonusSplit[2]);
  25.         } catch(Exception e) {}
  26.        
  27.        
  28.        
  29.        
  30.         /*
  31.          * generiert die eine/mehrere Zufallszahlen mit diceMax als Maximum und amountRoll der Anzahl
  32.          * der Würfe und addiert Speicherung der Summe in sum
  33.          * Gibt aus, welche Würfel welche Zahl gewürfelt hat
  34.          */
  35.         int sum = 0;
  36.         for(int i = 0; i < amountRoll; i++) {
  37.             int randomNum = ThreadLocalRandom.current().nextInt(1, diceMax+1);
  38.             System.out.println("Zufallszahl " + (i+1) + ": " +  randomNum);
  39.             sum += randomNum;
  40.         }
  41.        
  42.         System.out.println("Bonus: " + bonus);
  43.        
  44.         //verrechnet den Bonus mit der Summe
  45.         int result = math(sum, operator, bonus);
  46.        
  47.         System.out.println("Gewürfelte Zahl: " + result);
  48.        
  49.         return result;
  50.     }
  51.    
  52.     public static String[] splitKeep(String s) {
  53.         //Gewöhnliche Split-Funktion, bei dem die Selektion im Array gespeichert wird
  54.         return s.split("((?<=[+,-])|(?=[+,-]))");
  55.     }
  56.    
  57.     public static int math(int sum, char operator, int bonus) {
  58.        
  59.         switch(operator) {
  60.         case '+':
  61.             sum += bonus;
  62.             break;
  63.         case '-':
  64.             sum -= bonus;
  65.             break;
  66.         case '*':
  67.             sum *= bonus;
  68.             break;
  69.         case '/':
  70.             sum /= bonus;
  71.             break;
  72.         }
  73.        
  74.         return sum;
  75.     }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement