summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md15
-rw-r--r--go.mod3
-rw-r--r--main.go72
3 files changed, 90 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a142056
--- /dev/null
+++ b/README.md
@@ -0,0 +1,15 @@
+# The Scene
+
+Several people agree to convene to play a game of dice. Beforehand,
+they decided on the number of sides a given die should have. Once they
+do that, each player brings with them a die of that many sides (for
+example, 6, 12, etc.; even a coin can count as a die in this case.)
+
+A random number is selected from one of the die faces. Each player is
+tasked with rolling their die until they hit that number.
+
+For example, three players get together and decide to use an ordinary
+six-sided die each.
+
+The player to hit the number in the smallest number of turns,
+wins. There can be more than one winner.
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..bf55d87
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module git.brandonirizarry.xyz/dicegame
+
+go 1.25.0
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..d6e70f6
--- /dev/null
+++ b/main.go
@@ -0,0 +1,72 @@
+package main
+
+import (
+ "flag"
+ "fmt"
+ "log"
+ "math/rand"
+ "time"
+)
+
+func main() {
+ numPlayers := flag.Int("n", 2, "Number of players")
+ sides := flag.Int("sides", 6, "How many sides the die should have")
+ flag.Parse()
+
+ if *numPlayers < 2 {
+ log.Fatalf("we need at least 2 players")
+ }
+
+ if *sides < 2 {
+ log.Fatalf("die needs at least two sides")
+ }
+
+ fmt.Println("Welcome to the game")
+ fmt.Printf("There are %d players, each with a %d-sided die\n", *numPlayers, *sides)
+
+ game(*numPlayers, *sides)
+}
+
+type Score struct {
+ id int
+ score int
+}
+
+// The player with the lowest score wins.
+func game(numPlayers, faces int) {
+ // Get the game's winning number by throwing the die once.
+ winningNumber := throwDie(faces)
+
+ // The scores channel communicates the number of turns a
+ // player took to hit the winning number.
+ scores := make(chan Score)
+
+ for i := range numPlayers {
+ id := i + 1
+ fmt.Printf("Player %d start!\n", id)
+
+ // Spawn a player.
+ go func() {
+ var score int
+
+ // Start rolling the dice!
+ for {
+ score++
+ outcome := throwDie(faces)
+ if outcome == winningNumber {
+ scores <- Score{id: id, score: score}
+ }
+
+ time.Sleep(1 * time.Second)
+ }
+ }()
+ }
+
+ for score := range scores {
+ fmt.Printf("%v\n", score)
+ }
+}
+
+func throwDie(faces int) int {
+ return rand.Intn(faces) + 1
+}