Skip to content

Commit

Permalink
Add NotifyAt (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
kelindar authored Dec 3, 2022
1 parent 3ace9f7 commit 545865a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
10 changes: 9 additions & 1 deletion grid.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,14 @@ func (m *Grid) MergeAt(x, y int16, tile, mask Tile) {
}
}

// NotifyAt triggers the notification event for all of the observers at a given tile.
func (m *Grid) NotifyAt(x, y int16) {
if x >= 0 && y >= 0 && x < m.Size.X && y < m.Size.Y {
tile := m.pages[m.indexOf(x/3, y/3)].Get(x, y)
m.observers.Notify(At(x/3*3, y/3*3), At(x, y), tile)
}
}

// Neighbors iterates over the direct neighbouring tiles
func (m *Grid) Neighbors(x, y int16, fn Iterator) {

Expand Down Expand Up @@ -166,7 +174,7 @@ func (m *Grid) Neighbors(x, y int16, fn Iterator) {
func (m *Grid) View(rect Rect, fn Iterator) *View {
view := &View{
Grid: m,
Inbox: make(chan Update, 8),
Inbox: make(chan Update, 16),
rect: NewRect(-1, -1, -1, -1),
}

Expand Down
36 changes: 33 additions & 3 deletions view_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,25 @@ import (
"github.com/stretchr/testify/assert"
)

// BenchmarkView/write-8 11170822 105.1 ns/op 16 B/op 1 allocs/op
// BenchmarkView/move-8 9049 163019 ns/op 0 B/op 0 allocs/op
/*
cpu: Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
BenchmarkView/write-8 5910660 191.7 ns/op 16 B/op 1 allocs/op
BenchmarkView/move-8 8253 138149 ns/op 0 B/op 0 allocs/op
BenchmarkView/notify-8 6024670 197.5 ns/op 16 B/op 1 allocs/op
*/
func BenchmarkView(b *testing.B) {
m := mapFrom("300x300.png")
v := m.View(NewRect(100, 0, 199, 99), nil)
go func() {
for range v.Inbox {
}
}()

b.Run("write", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
v.WriteAt(152, 52, Tile{})
<-v.Inbox
}
})

Expand All @@ -37,6 +44,14 @@ func BenchmarkView(b *testing.B) {
v.MoveAt(locs[n%2], nil)
}
})

b.Run("notify", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
m.NotifyAt(150, 50)
}
})
}

func TestView(t *testing.T) {
Expand Down Expand Up @@ -133,6 +148,21 @@ func TestObserversNil(t *testing.T) {
})
}

func TestNotifyAt(t *testing.T) {
m := mapFrom("300x300.png")

// Create a new view
c := counter(0)
v := m.View(NewRect(0, 0, 99, 99), c.count)
assert.NotNil(t, v)
assert.Equal(t, 10000, int(c))

m.NotifyAt(1, 1)
update := <-v.Inbox
assert.Equal(t, int16(1), update.X)
assert.Equal(t, int16(1), update.Y)
}

type fakeView func(*Update)

func (f fakeView) onUpdate(e *Update) {
Expand Down

0 comments on commit 545865a

Please sign in to comment.