NAME
Game::Snake::Bot - a snake steered once a tick, at one of three levels
VERSION
Version 0.13
SYNOPSIS
use Game::Snake;
use Game::Snake::Bot;
my $game = Game::Snake->new(seed => $seed);
while ($game->status ne 'finished') {
my $direction = Game::Snake::Bot->choose($game, level => 2);
$game->turn($direction) if $direction ne $game->heading;
$game->tick;
}
DESCRIPTION
Asked once a tick, this answers the heading the snake should take next. Two levels share one look at the board and differ in what they do with it:
- 1 greedy
-
Of the safe headings, the one that closes on the food. A heading is safe when the next cell will not kill it, and that is all it looks at.
- 2 flood-fill
-
Greedy, but it counts the free cells reachable behind each safe heading and never takes a space smaller than its own length while a bigger one is open.
Two levels, not three, and both were measured. A reflex level that merely avoids the next fatal cell was tried first: alone on an empty board it circles the edge for ever and never eats. A third level that looked one step ahead and kept a way back to its tail was tried after: it scored a little above flood-fill on a small board and below it on the full 40 by 28 one. A level that is better everywhere needs a search over several ticks, which this module does not do.
A cell is fatal when it is off the board or on the snake, except the tail when the tail is about to leave it. A tie is broken by the heading the snake already has, then by a hash of the game's seed and tick, so the same seed plays the same game twice and nothing here calls rand.
The bot is a set of class methods and keeps nothing between ticks.
METHODS
choose
my $direction = Game::Snake::Bot->choose($game, level => 2);
The heading to take, one of up, down, left and right. The level is 1 or 2 and defaults to 2. Returns the heading the snake already has when nothing is safe, and undefined once the game has finished. A level that is not on the ladder is a programmer error and dies.
safe
my @safe = Game::Snake::Bot->safe($game);
The headings the snake may take this tick without dying: straight on and the two sides, less the fatal ones.
room
my $cells = Game::Snake::Bot->room($game, 'up');
How many free cells the snake could reach after stepping that way, 0 when the step itself is fatal.
levels
The ladder, (1, 2).
describe
print Game::Snake::Bot->describe(3);
One line on what a level does.
AUTHOR
LNATION, <email at lnation.org>
LICENSE AND COPYRIGHT
This software is Copyright (c) 2024 by LNATION.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)