From b2bea80c4cbdcc71919c5da3e57b8e5a429c1a60 Mon Sep 17 00:00:00 2001 From: bel Date: Wed, 1 Mar 2023 22:03:44 -0700 Subject: [PATCH] input.Random.Read yields input.Button --- src/device/input/input.go | 5 +++++ src/device/input/random.go | 37 +++++++++++++++++++++++++++++++++ src/device/input/random_test.go | 16 ++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 src/device/input/input.go create mode 100644 src/device/input/random.go create mode 100644 src/device/input/random_test.go diff --git a/src/device/input/input.go b/src/device/input/input.go new file mode 100644 index 0000000..e2c35d8 --- /dev/null +++ b/src/device/input/input.go @@ -0,0 +1,5 @@ +package input + +type Input interface { + Read() []byte +} diff --git a/src/device/input/random.go b/src/device/input/random.go new file mode 100644 index 0000000..9fd6d00 --- /dev/null +++ b/src/device/input/random.go @@ -0,0 +1,37 @@ +package input + +import ( + "math/rand" + "time" +) + +type Button struct { + Char byte + Down bool +} + +type Random struct { + start byte + stop byte + down []Button +} + +func NewRandom(start, stop byte) *Random { + rand.Seed(time.Now().UnixNano()) + return &Random{start: start, stop: stop + 1} +} + +func (r *Random) Read() []Button { + if rand.Int()%2 == 0 { + was := r.down + for i := range was { + was[i].Down = false + } + r.down = r.down[:0] + return was + } else { + c := Button{Char: r.start + byte(rand.Int()%int(r.stop-r.start)), Down: true} + r.down = append(r.down, c) + return []Button{c} + } +} diff --git a/src/device/input/random_test.go b/src/device/input/random_test.go new file mode 100644 index 0000000..6850e0a --- /dev/null +++ b/src/device/input/random_test.go @@ -0,0 +1,16 @@ +package input_test + +import ( + "mayhem-party/src/device/input" + "testing" +) + +func TestRandom(t *testing.T) { + r := input.NewRandom('a', 'g') + for i := 0; i < 100; i++ { + batch := r.Read() + for _, got := range batch { + t.Logf("[%d] %c:%v", i, got.Char, got.Down) + } + } +}