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