Games-Board

 view release on metacpan or  search on metacpan

lib/Games/Board/Grid.pm  view on Meta::CPAN

use strict;
use warnings;

package Games::Board::Grid 1.014;
use parent qw(Games::Board);
# ABSTRACT: a grid-shaped gameboard

use Carp;

#pod =head1 SYNOPSIS
#pod
#pod   use Games::Board::Grid;
#pod
#pod   my $chess = Games::Board->new(size => 8);
#pod
#pod   my $rook = Games::Board::Piece->new(id => 'KR')->move(to => '7 7');
#pod
#pod =head1 DESCRIPTION
#pod
#pod This module provides a base class for representing a board made up of spaces on
#pod a right-angled grid.
#pod
#pod =cut

#pod =method new
#pod
#pod   my $board = Games::Board::Grid->new(size => $size);
#pod
#pod This method constructs a new game board and returns it.  As constructed it has
#pod no spaces or pieces on it.  The C<size> argument may be an integer, to produce
#pod a square board, or an arrayref containing two integers, to produce a
#pod rectangular board.
#pod
#pod =cut

sub new {
  my ($class, %args) = @_;

  croak "no size given to construct grid" unless $args{size};

  $args{size} = [ ($args{size}) x 2 ] unless ref $args{size};

  my $board = { size => $args{size} };
  bless $board => $class;
  $board->init;
}

#pod =method init
#pod
#pod This method sets up the spaces on the board.
#pod
#pod =cut

sub init {
  my $board = shift;

  $board->{spaces} = {};

  for my $x (0 .. ($board->{size}[0] - 1)) {
  for my $y (0 .. ($board->{size}[1] - 1)) {
    my $id = $board->index2id([$x,$y]);
    $board->{spaces}{$id} = Games::Board::Grid::Space->new(id => $id, board => $board);
  }
  }

  $board;
}

#pod =method size
#pod
#pod =cut

sub size { (shift)->{size} }

#pod =method id2index
#pod
#pod   my $index = $board->id2index($id);
#pod
#pod This method returns the grid location of an identified space, in the format
#pod C<[$x, $y]>.  In Games::Board::Grid, the index C<[x,y]> becomes the id C<'x
#pod y'>.  Yeah, it's ugly, but it works.
#pod
#pod Reimplementing this method on a subclass can allow the use of idiomatic space
#pod identifiers on a grid.  (See, for example, the chess-custom.t test in this
#pod distribution.)
#pod
#pod =cut

sub id2index { [ split(/ /,$_[1]) ] }

#pod =method index2id
#pod
#pod   my $id = $board->index2id($index);
#pod
#pod This method performs the same translation as C<id2index>, but in reverse.
#pod
#pod =cut

sub index2id { join(q{ }, @{$_[1]}) }

#pod =method space
#pod
#pod   my $space = $board->space($id);
#pod

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 1.199 second using v1.00-cache-2.02-grep-82fe00e-cpan-72ae3ad1e6da )