summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordemo <demo@antix1>2026-05-24 23:24:12 -0400
committerdemo <demo@antix1>2026-05-24 23:24:12 -0400
commitb66bc6e6234e00ebd2e553eb9f43910d649e890f (patch)
treedafef06b411abe42fe0a8608b21cb636a0beaf36
parent26ce29b91e85b024eff7d5e3fd399080fd800ea0 (diff)
feat: generalize over multiple players
-rw-r--r--main.go45
1 files changed, 22 insertions, 23 deletions
diff --git a/main.go b/main.go
index 56d74ec..bdc4626 100644
--- a/main.go
+++ b/main.go
@@ -19,24 +19,24 @@ func main() {
func game(numSecs int) {
var wg sync.WaitGroup
- p0 := make(chan Ball)
- p1 := player(1, &wg, p0)
- p2 := player(2, &wg, p1)
- p3 := player(3, &wg, p2)
- p4 := player(4, &wg, p3)
- p5 := player(5, &wg, p4)
- p6 := player(6, &wg, p5)
- p7 := player(7, &wg, p6)
+ // FIXME: make this a flag.
+ const numPlayers = 7
+ players := make([]chan Ball, numPlayers+1)
+ players[0] = make(chan Ball)
+
+ for i := range numPlayers {
+ players[i+1] = player(i+1, &wg, players[i])
+ }
t := time.Tick(time.Duration(numSecs) * time.Second)
- p0 <- Ball{}
+ players[0] <- Ball{}
loop:
- for b := range p7 {
+ for b := range players[len(players)-1] {
select {
- case p0 <- b:
+ case players[0] <- b:
case <-t:
break loop
}
@@ -44,29 +44,28 @@ loop:
// This sets off a chain reaction that closes the other
// p-channels (p1, p2, etc.)
- close(p0)
+ close(players[0])
// Wait for all of the in-flight player goroutines to
// finish. You need this!
wg.Wait()
// If any of these prints out, we know we did something wrong.
- for range p0 {
- log.Fatal("P0")
- }
-
- for range p1 {
- log.Fatal("P1")
- }
-
- for range p2 {
- log.Fatal("P2")
+ for i, p := range players {
+ for range p {
+ log.Fatalf("P%d", i)
+ }
}
fmt.Println("Done for real!")
}
-func player(id int, wg *sync.WaitGroup, input <-chan Ball) <-chan Ball {
+// player spawns a new player goroutine that reads from the input
+// channel. Player returns a channel for listening for the goroutine's
+// output. Both channels are technically receive-only, but making them
+// bidirectional simplifies making them members of a slice which
+// contains a bidirectional channel.
+func player(id int, wg *sync.WaitGroup, input chan Ball) chan Ball {
out := make(chan Ball)
wg.Go(func() {