110 lines
2.2 KiB
Go
110 lines
2.2 KiB
Go
package internal
|
|
|
|
import (
|
|
"fmt"
|
|
"image"
|
|
|
|
"github.com/hajimehoshi/ebiten/v2"
|
|
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
|
|
)
|
|
|
|
const (
|
|
BaseWidth = 640
|
|
BaseHeight = 360
|
|
)
|
|
|
|
type Game struct {
|
|
width int
|
|
height int
|
|
match *match
|
|
debug bool
|
|
img *ebiten.Image
|
|
}
|
|
|
|
var _ ebiten.Game = (*Game)(nil)
|
|
|
|
func NewGame(width, height int, debug bool) (*Game, error) {
|
|
f, err := newFonts()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("couldn't parse fonts: %w", err)
|
|
}
|
|
|
|
return &Game{
|
|
width: width,
|
|
height: height,
|
|
match: newMatch(width, height, f),
|
|
debug: debug,
|
|
}, nil
|
|
}
|
|
|
|
func (g *Game) Update() error {
|
|
bounds := image.Rect(0, 0, g.width, g.height)
|
|
|
|
if err := g.match.update(bounds); err != nil {
|
|
return fmt.Errorf("couldn't update match: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (g *Game) Draw(screen *ebiten.Image) {
|
|
if g.img == nil {
|
|
g.img = ebiten.NewImage(g.width, g.height)
|
|
}
|
|
|
|
g.match.draw(g.img)
|
|
|
|
if g.debug {
|
|
g.drawDebug()
|
|
}
|
|
|
|
screen.DrawImage(g.img, nil)
|
|
}
|
|
|
|
func (g *Game) drawDebug() {
|
|
ebitenutil.DebugPrint(
|
|
g.img,
|
|
fmt.Sprintf(
|
|
"FPS: %0.2f"+
|
|
"\nBall: x=%v, y=%v, speedX=%v, speedY=%v, radius=%v"+
|
|
"\nLeft paddle: x=%v, y=%v, speed=%v, width=%v, height=%v, isControlledByPlayer=%v"+
|
|
"\nRight paddle: x=%v, y=%v, speed=%v, width=%v, height=%v, isControlledByPlayer=%v",
|
|
ebiten.ActualFPS(),
|
|
g.match.ball.x,
|
|
g.match.ball.y,
|
|
g.match.ball.speedX,
|
|
g.match.ball.speedY,
|
|
g.match.ball.r,
|
|
g.match.leftPaddle.x,
|
|
g.match.leftPaddle.y,
|
|
g.match.leftPaddle.speed,
|
|
g.match.leftPaddle.width,
|
|
g.match.leftPaddle.height,
|
|
g.match.leftPaddle.isControlledByPlayer,
|
|
g.match.rightPaddle.x,
|
|
g.match.rightPaddle.y,
|
|
g.match.rightPaddle.speed,
|
|
g.match.rightPaddle.width,
|
|
g.match.rightPaddle.height,
|
|
g.match.rightPaddle.isControlledByPlayer,
|
|
),
|
|
)
|
|
}
|
|
|
|
//nolint:nonamedreturns
|
|
func (g *Game) Layout(outsideWidth, outsideHeight int) (_screenWidth, _screenHeight int) {
|
|
if g.width != outsideWidth || g.height != outsideHeight {
|
|
g.match.resize(float32(outsideWidth)/float32(g.width), float32(outsideHeight)/float32(g.height))
|
|
|
|
if g.img != nil {
|
|
g.img.Dispose()
|
|
g.img = nil
|
|
}
|
|
|
|
g.width = outsideWidth
|
|
g.height = outsideHeight
|
|
}
|
|
|
|
return outsideWidth, outsideHeight
|
|
}
|