1
0
Fork 0
trevors-tutorials/0002-getting-started-with-ebitengine/game.go

89 lines
1.9 KiB
Go

package main
import (
"image"
"image/color"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
const (
screenW, screenH = 256, 144
playerW, playerH = 22, 42
groundH = 42
)
var (
backgroundColor = color.RGBA{255, 255, 255, 255}
groundColor = color.RGBA{71, 39, 2, 255}
playerColor = color.RGBA{6, 154, 46, 255}
)
type game struct {
// Player image.
playerImg *ebiten.Image
// Player attributes.
positionX, positionY float64
// Game attributes.
fullscreen bool
initialized bool
}
// initialize sets up the initial state of the game.
func (g *game) initialize() {
if g.initialized {
return
}
// Initialize player image.
g.playerImg = ebiten.NewImage(playerW, playerH)
g.playerImg.Fill(playerColor)
// Initialize player attributes.
g.positionX = screenW/2 - playerW/2
g.positionY = screenH - groundH
// Initialize game attributes.
g.fullscreen = true
g.initialized = true
}
// Layout is called each frame with the current size of the window.
func (g *game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
// Use fixed screen size.
return screenW, screenH
}
// Update is where we update the game state.
func (g *game) Update() error {
// Handle initialization.
if !g.initialized {
g.initialize()
}
// Handle fullscreen.
if inpututil.IsKeyJustPressed(ebiten.KeyEnter) && ebiten.IsKeyPressed(ebiten.KeyAlt) {
g.fullscreen = !g.fullscreen
ebiten.SetFullscreen(g.fullscreen)
}
return nil
}
// Draw is where we draw the game state.
func (g *game) Draw(screen *ebiten.Image) {
// Draw background.
screen.Fill(backgroundColor)
// Draw ground.
groundRect := image.Rect(0, screenH-groundH, screenW, screenH)
screen.SubImage(groundRect).(*ebiten.Image).Fill(groundColor)
// Draw player.
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(g.positionX, g.positionY-playerH)
screen.DrawImage(g.playerImg, op)
}