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