input.Random.Read yields input.Button
This commit is contained in:
5
src/device/input/input.go
Normal file
5
src/device/input/input.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package input
|
||||
|
||||
type Input interface {
|
||||
Read() []byte
|
||||
}
|
||||
37
src/device/input/random.go
Normal file
37
src/device/input/random.go
Normal file
@@ -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}
|
||||
}
|
||||
}
|
||||
16
src/device/input/random_test.go
Normal file
16
src/device/input/random_test.go
Normal file
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user