mirror of
https://github.com/wahyd4/zombie.git
synced 2026-08-09 04:35:54 +10:00
114 lines
2.5 KiB
Go
114 lines
2.5 KiB
Go
package zombie
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/wahyd4/zombie/models"
|
|
)
|
|
|
|
// Application presents the actual the runner
|
|
type Application struct {
|
|
GridSize int
|
|
Zombie *models.Zombie
|
|
Creatures []*models.Creature
|
|
Commands []MoveCommand
|
|
|
|
NextZombie *TransformedZombie
|
|
FinishedZombies []*models.Zombie
|
|
Score int
|
|
}
|
|
|
|
type TransformedZombie struct {
|
|
Zombie *models.Zombie
|
|
Next *TransformedZombie
|
|
}
|
|
|
|
func (app *Application) Run() {
|
|
for _, command := range app.Commands {
|
|
command.Execute(app.Zombie)
|
|
collided, creature := app.checkCollisionWithCreature()
|
|
if collided {
|
|
app.transformCreatureToZombie(creature)
|
|
app.IncreaseScore()
|
|
}
|
|
}
|
|
app.updateFinishedZombies()
|
|
|
|
if app.NextZombie != nil {
|
|
app.updateCurrentZombie()
|
|
app.updateNextZombie()
|
|
app.Run()
|
|
}
|
|
}
|
|
|
|
// Stats prints out statistic information
|
|
func (app *Application) Stats() {
|
|
fmt.Printf("zombies score: %d \n", app.Score)
|
|
var locations string
|
|
for _, zombie := range app.FinishedZombies {
|
|
locations += fmt.Sprintf("%s ", zombie.PrintLocation())
|
|
}
|
|
|
|
fmt.Printf("zombies positions: %s \n", locations)
|
|
}
|
|
|
|
func (app *Application) checkCollisionWithCreature() (bool, *models.Creature) {
|
|
for _, creature := range app.Creatures {
|
|
if app.Zombie.Coordinate == creature.Coordinate {
|
|
return true, creature
|
|
}
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
func (app *Application) transformCreatureToZombie(creature *models.Creature) {
|
|
app.appendTransformedZombie(&models.Zombie{
|
|
GridSize: app.GridSize,
|
|
Coordinate: creature.Coordinate,
|
|
})
|
|
app.removeCreature(creature)
|
|
}
|
|
|
|
func (app *Application) removeCreature(creature *models.Creature) {
|
|
creatures := app.Creatures
|
|
var creatureIndex int
|
|
for index, tempCreature := range creatures {
|
|
if creature == tempCreature {
|
|
creatureIndex = index
|
|
}
|
|
}
|
|
// assign the last index item to the deleted index, then shrink the slice
|
|
creatures[creatureIndex] = creatures[len(creatures)-1]
|
|
creatures[len(creatures)-1] = nil
|
|
app.Creatures = creatures[:len(creatures)-1]
|
|
|
|
}
|
|
|
|
func (app *Application) appendTransformedZombie(zombie *models.Zombie) {
|
|
next := app.NextZombie
|
|
|
|
for next != nil {
|
|
next = next.Next
|
|
}
|
|
|
|
app.NextZombie = &TransformedZombie{
|
|
Zombie: zombie,
|
|
Next: nil,
|
|
}
|
|
}
|
|
|
|
func (app *Application) IncreaseScore() {
|
|
app.Score++
|
|
}
|
|
|
|
func (app *Application) updateFinishedZombies() {
|
|
app.FinishedZombies = append(app.FinishedZombies, app.Zombie)
|
|
}
|
|
|
|
func (app *Application) updateNextZombie() {
|
|
app.NextZombie = app.NextZombie.Next
|
|
}
|
|
|
|
func (app *Application) updateCurrentZombie() {
|
|
app.Zombie = app.NextZombie.Zombie
|
|
}
|