foo
[gitmo/Moose-Autobox.git] / examples / tic_tac_toe.pl
CommitLineData
7fc99864 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Moose::Autobox;
7use Moose::Autobox::Undef;
8
c11e6a74 9sub print_board {
7fc99864 10 my ($b) = @_;
11 my $count = 0;
12 $b->map(sub {
13 print("$_ \t");
14 print("\n") unless ((++$count) % 3);
15 });
16}
17
c11e6a74 18my $board = [ ('.') x 9 ];
7fc99864 19
c11e6a74 20print_board($board);
7fc99864 21
7fc99864 22my $choice = [ 1 .. 9 ]->any;
23
24my $player = 'X';
c11e6a74 25while ($board->any eq '.') {
7fc99864 26
27 INPUT: {
c11e6a74 28 print("Player ($player), enter the Position [1-9]: ");
7fc99864 29 my $in = <>;
30
31 unless ($in == $choice) {
32 print "\n\tPlease enter a value within 1-9\n\n";
33 redo INPUT;
34 }
35
36 my $idx = $in - 1;
c11e6a74 37 if ($board->[$idx] ne '.') {
7fc99864 38 print "\n\tElement already entered at $in\n";
39 redo INPUT;
40 }
41
c11e6a74 42 $board->[$idx] = $player;
7fc99864 43 }
44
c11e6a74 45 print_board($board);
7fc99864 46
47 [
48 [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ],
49 [ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ],
50 [ 0, 4, 8 ], [ 2, 4, 6 ],
c11e6a74 51 ]->map(sub {
52
53 my $row = $board->slice($_);
54
55 if (($row->all eq 'X') || ($row->all eq 'O')) {
56 print("\n\tPlayer ($player) Wins\n");
7fc99864 57 exit;
58 }
c11e6a74 59
7fc99864 60 });
61
62 $player = $player eq 'X' ? 'O' : 'X';
63}
64
65
66=pod
67
68=head1 NAME
69
70tic_tac_toe.p6 - Tic-Tac-Toe
71
72=head1 DESCRIPTION
73
74This is a Moose::Autobox port of a perl6 implementation
75of the classic Tic-Tac-Toe game.
76
77This uses a modified version of the one Rob Kinyon created
78L<http://www.perlmonks.org/index.pl?node_id=451302>.
79
c11e6a74 80=head1 AUTHOR
81
82Stevan Little, E<lt>stevan@iinteractive.comE<gt>
83
84=head1 ACKNOLEDGEMENTS
85
86This code was ported from the version in the Pugs examples/
87directory. The authors of that were:
7fc99864 88
89mkirank L<http://www.perlmonks.org/index.pl?node_id=451261>
90
91Rob Kinyon L<http://www.perlmonks.org/index.pl?node_id=451302>
92
93Stevan Little, E<lt>stevan@iinteractive.comE<gt>
94
95Audrey Tang
96
97=cut
98