Commit ae4c0a7

mo <mo.khan@gmail.com>
2019-06-18 23:13:40
implement simple craps
1 parent f9ce5bc
src/Q4/RandomSumGame.java
@@ -5,10 +5,10 @@ import java.util.*;
 
 public class RandomSumGame {
   private boolean start;
-  private int d1;
-  private int d2;
-  private int sum;
-  private int valuePoint;
+  private int d1 = 0;
+  private int d2 = 0;
+  private int sum = 0;
+  private int valuePoint = 0;
   private String status;
   private PrintStream out;
 
@@ -16,19 +16,72 @@ public class RandomSumGame {
     this.out = out;
   }
 
-  public void play(int d1, int d2) {}
-
   public void play() {
     this.rollDice();
     this.play(this.d1, this.d2);
   }
 
+  public void play(int d1, int d2) {
+    int total = d1 + d2;
+    this.puts("You rolled: %d", total);
+    if (!hasValuePoint()) {
+      switch (total) {
+        case 2:
+        case 3:
+        case 12:
+          this.puts("Craps! You lose.");
+          break;
+        case 7:
+        case 11:
+          this.puts("Natural! You win!");
+          break;
+        default:
+          this.puts("Value point established: %d", total);
+          this.valuePoint = total;
+          play();
+          break;
+      }
+    } else {
+      if (total == this.valuePoint) {
+        this.puts("You win!");
+        this.reset();
+        return;
+      } else if (total == 7) {
+        this.puts("You lose.");
+        this.reset();
+        return;
+      } else {
+        play();
+      }
+    }
+  }
+
   public void rollDice() {
     this.d1 = this.roll();
     this.d2 = this.roll();
+    this.sum = this.d1 + this.d2;
   }
 
   private int roll() {
     return new Random().nextInt(5) + 1;
   }
+
+  private void puts(String format, Object... args) {
+    this.out.println(String.format(format, args));
+  }
+
+  private boolean hasValuePoint() {
+    return this.valuePoint > 0;
+  }
+
+  private void reset() {
+    this.valuePoint = this.d1 = this.d2 = this.sum = 0;
+  }
+
+  public static void main(String[] args) {
+    Scanner in = new Scanner(System.in);
+    System.out.println("Welcome to Craps");
+    RandomSumGame game = new RandomSumGame(System.out);
+    game.play();
+  }
 }
src/App.java
@@ -23,6 +23,9 @@ public class App {
         case 3:
           Q3.CreditCard.main(args);
           break;
+        case 4:
+          Q4.RandomSumGame.main(args);
+          break;
         default:
           System.out.println("Bye");
           System.exit(0);
Rakefile
@@ -27,6 +27,6 @@ task(doc: [:pdf]) { sh 'mvn javadoc:javadoc' }
 task publish: [:clean, :test, :doc, :repackage]
 task(:build) { sh "mvn package" }
 task(run: :build) { run_cli }
-1.upto(3) { |n| task("run#{n}": :build) { run_cli(n) } }
+1.upto(4) { |n| task("run#{n}": :build) { run_cli(n) } }
 
 task default: [:publish]