Maintain at least 1 food on board at all times.

This commit is contained in:
bvanvugt 2020-02-01 10:47:15 -08:00
parent 6edb4ce5d4
commit ccd7a4e47d
2 changed files with 13 additions and 11 deletions

View file

@ -174,7 +174,7 @@ func (r *StandardRuleset) ResolveMoves(prevState *BoardState, moves []SnakeMove)
}
// TODO: LOG?
err = r.maybeSpawnFood(nextState, 1)
err = r.maybeSpawnFood(nextState)
if err != nil {
return nil, err
}
@ -361,9 +361,9 @@ func (r *StandardRuleset) feedSnakes(b *BoardState) error {
return nil
}
func (r *StandardRuleset) maybeSpawnFood(b *BoardState, n int) error {
if rand.Float32() <= FoodSpawnChance {
return r.spawnFood(b, n)
func (r *StandardRuleset) maybeSpawnFood(b *BoardState) error {
if len(b.Food) == 0 || rand.Float32() <= FoodSpawnChance {
return r.spawnFood(b, 1)
}
return nil
}

View file

@ -1091,15 +1091,16 @@ func TestGetUnoccupiedPoints(t *testing.T) {
func TestMaybeSpawnFood(t *testing.T) {
tests := []struct {
Seed int64
Food []Point
ExpectedFood []Point
}{
// Use pre-tested seeds and results
{123, []Point{}},
{456, []Point{}},
{789, []Point{}},
{1024, []Point{{2, 1}}},
{511, []Point{{2, 0}}},
{165, []Point{{3, 1}}},
{123, []Point{}, []Point{{2, 2}}},
{456, []Point{{4, 4}}, []Point{{4, 4}}},
{789, []Point{{4, 4}}, []Point{{4, 4}}},
{1024, []Point{}, []Point{{4, 1}}},
{511, []Point{{4, 4}}, []Point{{4, 4}, {2, 0}}},
{165, []Point{{4, 4}}, []Point{{4, 4}, {3, 1}}},
}
r := StandardRuleset{}
@ -1111,10 +1112,11 @@ func TestMaybeSpawnFood(t *testing.T) {
{Body: []Point{{1, 0}, {1, 1}}},
{Body: []Point{{0, 1}, {0, 2}, {0, 3}}},
},
Food: test.Food,
}
rand.Seed(test.Seed)
err := r.maybeSpawnFood(b, 1)
err := r.maybeSpawnFood(b)
require.NoError(t, err)
require.Equal(t, len(test.ExpectedFood), len(b.Food), "Seed %d", test.Seed)
for i, e := range test.ExpectedFood {