Game-TextMapper
view release on metacpan or search on metacpan
lib/Game/TextMapper/Schroeder/Hex.pm view on Meta::CPAN
# Copyright (C) 2009-2021 Alex Schroeder <alex@gnu.org>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
=encoding utf8
=head1 NAME
Game::TextMapper::Schroeder::Hex - a role for hex map generators
=head1 SYNOPSIS
# create a map
package World;
use Modern::Perl;
use Mojo::Base -base;
use Role::Tiny::With;
with 'Game::TextMapper::Schroeder::Base';
with 'Game::TextMapper::Schroeder::Hex';
# use it
package main;
my $map = World->new(height => 10, width => 10);
=head1 DESCRIPTION
This role provides basic functionality for map generation with hex maps: the
number of neighbours within one or two regions distance, how to pick a random
neighbour direction, how to compute the coordinates of these neighbours, how to
draw arrows towards these neighbours.
This inherits attributes and methods from L<Game::TextMapper::Schroeder::Base>,
such as C<width> and C<height>.
=cut
package Game::TextMapper::Schroeder::Hex;
use Modern::Perl '2018';
use Mojo::Base -role;
use POSIX qw(ceil);
=head1 METHODS
=head2 reverse
Reverses a direction.
=cut
sub reverse {
my ($self, $i) = @_;
return ($i + 3) % 6;
}
=head2 neighbors
The list of directions for neighbours one step away (0 to 5).
=cut
sub neighbors { 0 .. 5 }
=head2 neighbors2
The list of directions for neighbours two steps away (0 to 11).
=cut
sub neighbors2 { 0 .. 11 }
=head2 random_neighbor
A random direction for a neighbour one step away (a random integer from 0 to 5).
=cut
sub random_neighbor { int(rand(6)) }
=head2 random_neighbor2
A random direction for a neighbour two steps away (a random integer from 0 to
11).
=cut
sub random_neighbor2 { int(rand(12)) }
my $delta_hex = [
# x is even
[[-1, 0], [ 0, -1], [+1, 0], [+1, +1], [ 0, +1], [-1, +1]],
# x is odd
[[-1, -1], [ 0, -1], [+1, -1], [+1, 0], [ 0, +1], [-1, 0]]];
=head2 neighbor($hex, $i)
say join(",", $map->neighbor("0203", 1));
# 2,2
( run in 1.441 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )