ebiten/example/game.go

100 lines
2.1 KiB
Go
Raw Normal View History

2013-12-08 08:19:24 +01:00
package main
2013-07-02 18:27:04 +02:00
import (
2013-07-04 16:57:53 +02:00
"fmt"
2013-10-14 04:34:58 +02:00
"github.com/hajimehoshi/go-ebiten/graphics"
"github.com/hajimehoshi/go-ebiten/graphics/matrix"
"github.com/hajimehoshi/go-ebiten/ui"
2013-07-02 18:27:04 +02:00
)
2013-12-08 08:19:24 +01:00
var TexturePaths = map[string]string{
"ebiten": "images/ebiten.png",
"text": "images/text.png",
}
type Game struct {
textures map[string]graphics.TextureId
inputStateUpdatedCh chan ui.InputStateUpdatedEvent
2013-11-29 20:24:52 +01:00
x int
y int
2013-07-02 18:27:04 +02:00
}
2013-12-08 08:19:24 +01:00
func NewGame() *Game {
return &Game{
textures: map[string]graphics.TextureId{},
inputStateUpdatedCh: make(chan ui.InputStateUpdatedEvent),
2013-11-29 20:24:52 +01:00
x: -1,
y: -1,
2013-11-29 19:21:10 +01:00
}
}
2013-12-08 08:19:24 +01:00
func (game *Game) OnTextureCreated(e graphics.TextureCreatedEvent) {
if e.Error != nil {
panic(e.Error)
}
game.textures[e.Tag.(string)] = e.Id
}
func (game *Game) OnInputStateUpdated(e ui.InputStateUpdatedEvent) {
2013-12-01 13:23:03 +01:00
go func() {
e := e
game.inputStateUpdatedCh <- e
}()
2013-07-02 18:27:04 +02:00
}
2013-12-08 08:19:24 +01:00
func (game *Game) Update() {
2013-11-29 19:21:10 +01:00
events:
for {
select {
2013-11-29 20:24:52 +01:00
case e := <-game.inputStateUpdatedCh:
2013-11-29 19:21:10 +01:00
game.x, game.y = e.X, e.Y
default:
break events
}
}
2013-07-02 18:27:04 +02:00
}
2013-12-08 08:19:24 +01:00
func (game *Game) Draw(g graphics.Canvas) {
if len(game.textures) < len(TexturePaths) {
return
}
2013-10-11 20:20:13 +02:00
g.Fill(128, 128, 255)
2013-07-04 16:57:53 +02:00
str := fmt.Sprintf(`Input State:
X: %d
2013-11-29 19:21:10 +01:00
Y: %d`, game.x, game.y)
2013-07-04 16:57:53 +02:00
game.drawText(g, str, 5, 5)
2013-07-02 18:27:04 +02:00
}
2013-12-08 08:19:24 +01:00
func (game *Game) drawText(g graphics.Canvas, text string, x, y int) {
2013-07-04 16:57:53 +02:00
const letterWidth = 6
const letterHeight = 16
parts := []graphics.TexturePart{}
textX := 0
textY := 0
for _, c := range text {
if c == '\n' {
textX = 0
textY += letterHeight
continue
}
code := int(c)
x := (code % 32) * letterWidth
y := (code / 32) * letterHeight
source := graphics.Rect{x, y, letterWidth, letterHeight}
parts = append(parts, graphics.TexturePart{
LocationX: textX,
LocationY: textY,
Source: source,
})
textX += letterWidth
}
geometryMatrix := matrix.IdentityGeometry()
geometryMatrix.Translate(float64(x), float64(y))
colorMatrix := matrix.IdentityColor()
2013-12-08 08:19:24 +01:00
g.DrawTextureParts(game.textures["text"], parts,
2013-07-04 16:57:53 +02:00
geometryMatrix, colorMatrix)
2013-07-02 18:27:04 +02:00
}