carotidartillery/creep.go

84 lines
1.3 KiB
Go
Raw Normal View History

2021-10-06 04:05:02 +00:00
package main
import (
"math/rand"
"sync"
"github.com/hajimehoshi/ebiten/v2"
)
2021-10-06 14:18:38 +00:00
type gameCreep struct {
2021-10-06 04:05:02 +00:00
x, y float64
sprite *ebiten.Image
moveX, moveY float64
tick int
nextAction int
2021-10-06 14:18:38 +00:00
level *Level
2021-10-06 15:03:13 +00:00
health int
2021-10-07 00:29:28 +00:00
killScore int
2021-10-06 04:05:02 +00:00
sync.Mutex
}
2021-10-06 14:18:38 +00:00
func NewCreep(sprite *ebiten.Image, level *Level) *gameCreep {
return &gameCreep{
2021-10-07 00:29:28 +00:00
x: float64(1 + rand.Intn(108)),
y: float64(1 + rand.Intn(108)),
sprite: sprite,
level: level,
health: 1,
killScore: 50,
2021-10-06 14:18:38 +00:00
}
}
func (c *gameCreep) doNextAction() {
2021-10-06 15:03:13 +00:00
c.moveX = (rand.Float64() - 0.5) / 7
c.moveY = (rand.Float64() - 0.5) / 7
if c.x <= 2 && c.moveX < 0 {
c.moveX *= 1
} else if c.x >= float64(c.level.w-3) && c.moveX > 0 {
c.moveX *= 1
}
if c.y <= 2 && c.moveY > 0 {
c.moveY *= 1
} else if c.y >= float64(c.level.h-3) && c.moveY < 0 {
c.moveY *= 1
}
2021-10-06 04:05:02 +00:00
2021-10-06 15:03:13 +00:00
c.nextAction = 400 + rand.Intn(400)
2021-10-06 04:05:02 +00:00
}
2021-10-06 14:18:38 +00:00
func (c *gameCreep) Update() {
2021-10-06 04:05:02 +00:00
c.Lock()
defer c.Unlock()
2021-10-06 15:03:13 +00:00
if c.health == 0 {
return
}
2021-10-06 04:05:02 +00:00
c.tick++
if c.tick >= c.nextAction {
c.doNextAction()
c.tick = 0
}
2021-10-06 15:03:13 +00:00
x, y := c.x+c.moveX, c.y+c.moveY
clampX, clampY := c.level.Clamp(x, y)
c.x, c.y = clampX, clampY
if clampX != x || clampY != y {
c.nextAction = 0
}
2021-10-06 04:05:02 +00:00
}
2021-10-06 14:18:38 +00:00
func (c *gameCreep) Position() (float64, float64) {
2021-10-06 04:05:02 +00:00
c.Lock()
defer c.Unlock()
return c.x, c.y
}