TicTacToe.pm

filter: Statementstmt 50.0% 54 / 108 Branchbran 15.3% 4 / 26 Conditioncond 12.1% 4 / 33 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 64.0% 16 / 25 Podpod 92.3% 12 / 13 totaltotal 40.1% 90 / 224 SCAR 53.4
CC
27
Cov
37%
isValidMove
30.0
play
25.7
isGameOver
13.0
CRAP 208.2
« TicTacToe/Move.pm ↑ Summary TicTacToe/Board.pm »
1 package Games::TicTacToe;
2  
3 10 $Games::TicTacToe::VERSION = '0.24';
4 10 $Games::TicTacToe::AUTHOR = 'cpan:MANWAR';
5  
6 =head1 NAME
7  
8 Games::TicTacToe - Interface to the TicTacToe (nxn) game.
9  
10 =head1 VERSION
11  
12 Version 0.24
13  
14 =cut
15  
16 10 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 10 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 10 ▶use Games::TicTacToe::Move;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 10 ▶use Games::TicTacToe::Board;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 10 ▶use Games::TicTacToe::Player;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 10 ▶use Games::TicTacToe::Params qw(Board PlayerType Players);
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 10 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 10 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 10 has 'board' => (is => 'rw', isa => Board);
27 7 ▶has 'current' => (is => 'rw', isa => PlayerType, default => sub { return 'H'; });
Subroutine __ANON__: called CC=1 SCAR=0.0
28 10 has 'players' => (is => 'rw', isa => Players, predicate => 1);
29 6 ▶has 'size' => (is => 'ro', default => sub { return 3 });
Subroutine __ANON__: called CC=1 SCAR=0.0
30 10 has 'winner' => (is => 'rw', predicate => 1, clearer => 1);
31  
32 =head1 DESCRIPTION
33  
34 A console based TicTacToe game to play against the computer. A simple TicTacToe
35 layer supplied with the distribution in the script sub folder. Board arranged as
36 nxn, where n>=3. Default size is 3,For example 5x5 would be something like below:
37  
38 +------------------------+
39 | TicTacToe |
40 +----+----+----+----+----+
41 | 1 | 2 | 3 | 4 | 5 |
42 +----+----+----+----+----+
43 | 6 | 7 | 8 | 9 | 10 |
44 +----+----+----+----+----+
45 | 11 | 12 | 13 | 14 | 15 |
46 +----+----+----+----+----+
47 | 16 | 17 | 18 | 19 | 20 |
48 +----+----+----+----+----+
49 | 21 | 22 | 23 | 24 | 25 |
50 +----+----+----+----+----+
51  
52 =head1 SYNOPSIS
53  
54 Below is the working code for the TicTacToe game using the L<Games::TicTacToe>
55 package. The game script C<play-tictactoe> is supplied with the distribution and
56 on install is available to play with.
57  
58 use strict; use warnings;
59 use Games::TicTacToe;
60  
61 $|=1;
62  
63 $SIG{'INT'} = sub { print {*STDOUT} "\n\nCaught Interrupt (^C), Aborting\n"; exit(1); };
64  
65 my $tictactoe = Games::TicTacToe->new;
66  
67 my ($size);
68 do {
69 print {*STDOUT} "Please enter game board size (type 3 if you want 3x3): ";
70 $size = <STDIN>;
71 chomp($size);
72 } until ($tictactoe->isValidGameBoardSize($size));
73  
74 $tictactoe->setGameBoard($size);
75  
76 my ($symbol);
77 do {
78 print {*STDOUT} "Please select the symbol [X / O]: ";
79 $symbol = <STDIN>;
80 chomp($symbol);
81 } until ($tictactoe->isValidSymbol($symbol));
82  
83 $tictactoe->setPlayers($symbol);
84  
85 my ($response);
86 do {
87 print {*STDOUT} $tictactoe->getGameBoard;
88 my $index = 1;
89 my $board = $tictactoe->board;
90 do {
91 my $move = undef;
92 if ($tictactoe->needNextMove) {
93 my $available = $board->availableIndex;
94 if ($tictactoe->isLastMove) {
95 $move = $available;
96 }
97 else {
98 do {
99 print {*STDOUT} "What is your next move [$available] ? ";
100 $move = <STDIN>;
101 chomp($move);
102 } until ($tictactoe->isValidMove($move));
103 }
104 }
105  
106 $tictactoe->play($move);
107  
108 print {*STDOUT} $tictactoe->getGameBoard
109 unless (($index % 2 == 1) || $tictactoe->isGameOver);
110  
111 $index++;
112  
113 } until ($tictactoe->isGameOver);
114  
115 print {*STDOUT} $tictactoe->getGameBoard;
116 print {*STDOUT} $tictactoe->getResult;
117  
118 $board->reset;
119  
120 do {
121 print {*STDOUT} "Do you wish to continue (Y/N)? ";
122 $response = <STDIN>;
123 chomp($response);
124 } until (defined $response && ($response =~ /^[Y|N]$/i));
125  
126 } until ($response =~ /^N$/i);
127  
128 print {*STDOUT} "Thank you.\n";
129  
130 Once it is installed, it can be played on a terminal/command window as below:
131  
132 $ play-tictactoe
133  
134 =cut
135  
136 sub BUILD {
137 6 ▶ my ($self) = @_;
Subroutine BUILD: called CC=1 SCAR=0.0
Pod undocumented
138  
139 6 $self->setGameBoard($self->size);
140 }
141  
142 =head1 METHODS
143  
144 =head2 setGameBoard($size)
145  
146 It sets up the game board of the given C<$size>.
147  
148 =cut
149  
150 sub setGameBoard {
151 6 ▶ my ($self, $size) = @_;
Subroutine setGameBoard: called CC=1 SCAR=0.0
Pod documented
152  
153 6 my $cell = [ map { $_ } (1..($size * $size)) ];
154 6 $self->board(Games::TicTacToe::Board->new(cell => $cell));
155 }
156  
157 =head2 getGameBoard()
158  
159 Returns game board for TicTacToe (3x3) by default.
160  
161 =cut
162  
163 sub getGameBoard {
164 0 ▶ my ($self) = @_;
Subroutine getGameBoard: not called CC=1 SCAR=6.9
Pod documented
165  
166 0 return $self->board->as_string;
167 }
168  
169 =head2 setPlayers($symbol)
170  
171 Adds a player with the given C<$symbol>. The other symbol would be given to the
172 opposite player i.e. Computer.
173  
174 =cut
175  
176 sub setPlayers {
177 1 ▶ my ($self, $symbol) = @_;
Subroutine setPlayers: called CC=5 SCAR=24.7
Pod documented
178  
179 1 ▶ if (($self->has_players) && (scalar(@{$self->players}) == 2)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_players and scalar @{$self->players;} == 2) 1 0 1
Condition33%1/3
$self->has_players and scalar @{$self->players;} == 2
!ll&&!rl&&r
001
MC/DC0%0/2
$self->has_players and scalar @{$self->players;} == 2
$self->has_players scalar @{$self->players;} == 2
Truth table33%1/3
A and B
A= $self->has_playersB= scalar @{$self->players;} == 2
ABresult
0X0
100
111
180 1 warn("WARNING: We already have 2 players to play the TicTacToe game.");
181 1 return;
182 }
183  
184 0 ▶ die "ERROR: Missing symbol for the player.\n" unless defined $symbol;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $symbol 0 0 0
185  
186 # Player 1
187 0 push @{$self->{players}}, Games::TicTacToe::Player->new(type => 'H', symbol => uc($symbol));
188  
189 # Player 2
190 0 ▶ $symbol = (uc($symbol) eq 'X')?('O'):('X');
Branch: 1 branch
BranchTrueFalseTotal
uc $symbol eq 'X' ? : 0 0 0
191 0 push @{$self->{players}}, Games::TicTacToe::Player->new(type => 'C', symbol => $symbol);
192 }
193  
194 =head2 getPlayers()
195  
196 Returns the players information with their symbol.
197  
198 =cut
199  
200 sub getPlayers {
201 1 ▶ my ($self) = @_;
Subroutine getPlayers: called CC=4 SCAR=20.7
Pod documented
202  
203 1 ▶ if (!($self->has_players) || scalar(@{$self->players}) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->has_players or scalar @{$self->players;} == 0) 1 0 1
Condition33%1/3
not $self->has_players or scalar @{$self->players;} == 0
l!l&&r!l&&!r
100
MC/DC0%0/2
not $self->has_players or scalar @{$self->players;} == 0
not $self->has_players scalar @{$self->players;} == 0
Truth table33%1/3
not(A) or B
A= not $self->has_playersB= scalar @{$self->players;} == 0
ABresult
1X1
011
000
204 1 warn("WARNING: No player found to play the TicTacToe game.");
205 1 return;
206 }
207  
208 0 my $players = sprintf("+-------------+\n");
209 0 foreach (@{$self->{players}}) {
210 0 $players .= sprintf("|%9s: %s |\n", $_->desc, $_->symbol);
211 }
212 0 $players .= sprintf("+-------------+\n");
213  
214 0 return $players;
215 }
216  
217 =head2 play($move)
218  
219 Makes the given C<$move>, if provided, otherwise make next best possible moves on
220 behalf of opponent.
221  
222 =cut
223  
224 sub play {
225 1 ▶ my ($self, $move) = @_;
Subroutine play: called CC=6 SCAR=32.5
Pod documented
226  
227 die("ERROR: Please add player before you start the game.\n")
228 1 ▶ unless (($self->has_players) && (scalar(@{$self->players}) == 2));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_players and scalar @{$self->players;} == 2 1 0 1
Condition33%1/3
$self->has_players and scalar @{$self->players;} == 2
!ll&&!rl&&r
100
MC/DC0%0/2
$self->has_players and scalar @{$self->players;} == 2
$self->has_players scalar @{$self->players;} == 2
Truth table33%1/3
A and B
A= $self->has_playersB= scalar @{$self->players;} == 2
ABresult
0X0
100
111
229  
230 0 my $player = $self->_getCurrentPlayer;
231 0 my $board = $self->board;
232 0 ▶ if (defined $move && ($self->_getCurrentPlayer->type eq 'H')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $move and $self->_getCurrentPlayer->type eq 'H') { } 0 0 0
Condition0%0/3
defined $move and $self->_getCurrentPlayer->type eq "H"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $move and $self->_getCurrentPlayer->type eq "H"
defined $move $self->_getCurrentPlayer->type eq "H"
Truth table0%0/3
A and B
A= defined $moveB= $self->_getCurrentPlayer->type eq "H"
ABresult
0X0
100
111
233 0 --$move;
234 }
235 else {
236 0 $move = Games::TicTacToe::Move::now($player, $board);
237 }
238  
239 0 $board->setCell($move, $player->symbol);
240 0 ▶ $self->_resetCurrentPlayer unless ($self->isGameOver);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->isGameOver 0 0 0
241 }
242  
243 =head2 getResult()
244  
245 Returns the result message.
246  
247 =cut
248  
249 sub getResult {
250 0 ▶ my ($self) = @_;
Subroutine getResult: not called CC=3 SCAR=24.8
Pod documented
251  
252 0 my $result;
253 0 ▶ if ($self->has_winner) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_winner) { } 0 0 0
254 0 $result = $self->winner->getMessage;
255 }
256 else {
257 0 ▶ die "ERROR: Game is not finished yet.\n" unless $self->board->isFull;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->board->isFull 0 0 0
258 0 $result = "<cyan><bold>Game drawn, better luck next time.</bold></cyan>\n";
259 }
260  
261 0 $self->clear_winner;
262 0 $self->current('H');
263  
264 0 return Term::ANSIColor::Markup->colorize($result);
265 }
266  
267 =head2 needNextMove()
268  
269 Returns 0 or 1 depending on whether it needs to prompt for next move.
270  
271 =cut
272  
273 sub needNextMove {
274 0 ▶ my ($self) = @_;
Subroutine needNextMove: not called CC=1 SCAR=6.9
Pod documented
275  
276 0 return ($self->_getCurrentPlayer->type eq 'H');
277 }
278  
279 =head2 isLastMove()
280  
281 Returns 0 or 1 depending on whether it is the last move.
282  
283 =cut
284  
285 sub isLastMove {
286 0 ▶ my ($self) = @_;
Subroutine isLastMove: not called CC=1 SCAR=6.9
Pod documented
287  
288 0 return ($self->board->availableIndex !~ /\,/);
289 }
290  
291 =head2 isGameOver()
292  
293 Returns 0 or 1 depending whether the TicTacToe game is over or not.
294  
295 =cut
296  
297 sub isGameOver {
298 1 ▶ my ($self) = @_;
Subroutine isGameOver: called CC=5 SCAR=25.7
Pod documented
299  
300 1 ▶ if (!($self->has_players) || scalar(@{$self->players}) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->has_players or scalar @{$self->players;} == 0) 1 0 1
Condition33%1/3
not $self->has_players or scalar @{$self->players;} == 0
l!l&&r!l&&!r
100
MC/DC0%0/2
not $self->has_players or scalar @{$self->players;} == 0
not $self->has_players scalar @{$self->players;} == 0
Truth table33%1/3
not(A) or B
A= not $self->has_playersB= scalar @{$self->players;} == 0
ABresult
1X1
011
000
301 1 warn("WARNING: No player found to play the TicTacToe game.");
302 1 return;
303 }
304  
305 0 my $board = $self->board;
306 0 foreach my $player (@{$self->players}) {
307 0 ▶ if (Games::TicTacToe::Move::foundWinner($player, $board)) {
Branch: 1 branch
BranchTrueFalseTotal
if (Games::TicTacToe::Move::foundWinner($player, $board)) 0 0 0
308 0 $self->winner($player);
309 0 return 1;
310 }
311 }
312  
313 0 return $board->isFull;
314 }
315  
316 =head2 isValidMove($move)
317  
318 Returns 0 or 1 depending on whether the given C<$move> is valid or not.
319  
320 =cut
321  
322 sub isValidMove {
323 0 ▶ my ($self, $move) = @_;
Subroutine isValidMove: not called CC=5 SCAR=34.0
Pod documented
324  
325 0 ▶ return (defined($move)
Condition0%0/12
defined $move && $move =~ /^\d+$/ && $move >= 1 && $move <= $self->board->getSize && $self->board->isCellEmpty($move - 1)
!ll&&!rl&&r
000
defined $move and $move =~ /^\d+$/ and $move >= 1 and $move <= $self->board->getSize
!ll&&!rl&&r
000
defined $move and $move =~ /^\d+$/ and $move >= 1
!ll&&!rl&&r
000
defined $move and $move =~ /^\d+$/
!ll&&!rl&&r
000
MC/DC0%0/5
defined $move && $move =~ /^\d+$/ && $move >= 1 && $move <= $self->board->getSize && $self->board->isCellEmpty($move - 1)
defined $move $move =~ /^\d+$/ $move >= 1 $move <= $self->board->getSize $self->board->isCellEmpty($move - 1)
Truth table0%0/6
A and B and C and D && E
A= defined $moveB= $move =~ /^\d+$/C= $move >= 1D= $move <= $self->board->getSizeE= $self->board->isCellEmpty($move - 1)
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
326 && ($move =~ /^\d+$/)
327 && ($move >= 1) && ($move <= $self->board->getSize)
328 && ($self->board->isCellEmpty($move-1)));
329 }
330  
331 =head2 isValidSymbol($symbol)
332  
333 Returns 0 or 1 depending on whether the given C<$symbol> is valid or not.
334  
335 =cut
336  
337 sub isValidSymbol {
338 0 ▶ my ($self, $symbol) = @_;
Subroutine isValidSymbol: not called CC=2 SCAR=17.9
Pod documented
339  
340 0 ▶ return (defined $symbol && ($symbol =~ /^[X|O]$/i));
Condition0%0/3
defined $symbol && $symbol =~ /^[X|O]$/i
!ll&&!rl&&r
000
MC/DC0%0/2
defined $symbol && $symbol =~ /^[X|O]$/i
defined $symbol $symbol =~ /^[X|O]$/i
Truth table0%0/3
A && B
A= defined $symbolB= $symbol =~ /^[X|O]$/i
ABresult
0X0
100
111
341 }
342  
343 =head2 isValidGameBoardSize($size)
344  
345 Returns 0 or 1 depending on whether the given C<$size> is valid or not.
346  
347 =cut
348  
349 sub isValidGameBoardSize {
350 0 ▶ my ($self, $size) = @_;
Subroutine isValidGameBoardSize: not called CC=2 SCAR=17.9
Pod documented
351  
352 0 ▶ return (defined $size && ($size >= 3));
Condition0%0/3
defined $size && $size >= 3
!ll&&!rl&&r
000
MC/DC0%0/2
defined $size && $size >= 3
defined $size $size >= 3
Truth table0%0/3
A && B
A= defined $sizeB= $size >= 3
ABresult
0X0
100
111
353 }
354  
355 #
356 #
357 # PRIVATE METHODS
358  
359 sub _getCurrentPlayer {
360 0 ▶ my ($self) = @_;
Subroutine _getCurrentPlayer: not called CC=2 SCAR=17.9
361  
362 ($self->{players}->[0]->type eq $self->current)
363 ?
364 (return $self->{players}->[0])
365 :
366 0 ▶ (return $self->{players}->[1]);
Branch: 1 branch
BranchTrueFalseTotal
$self->{'players'}[0]->type eq $self->current ? : 0 0 0
367 }
368  
369 sub _resetCurrentPlayer {
370 0 ▶ my ($self) = @_;
Subroutine _resetCurrentPlayer: not called CC=2 SCAR=17.9
371  
372 ($self->{players}->[0]->type eq $self->current)
373 ?
374 ($self->current($self->{players}->[1]->type))
375 :
376 0 ▶ ($self->current($self->{players}->[0]->type));
Branch: 1 branch
BranchTrueFalseTotal
$self->{'players'}[0]->type eq $self->current ? : 0 0 0
377 }
378  
379 =head1 AUTHOR
380  
381 Mohammad S Anwar, C<< <mohammad.anwar at yahoo.com> >>
382  
383 =head1 REPOSITORY
384  
385 L<https://github.com/manwar/Games-TicTacToe>
386  
387 =head1 BUGS
388  
389 Please report any bugs / feature requests to C<bug-games-tictactoe at rt.cpan.org>
390 or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Games-TicTacToe>.
391 I will be notified & then you'll automatically be notified of progress on your bug
392 as I make changes.
393  
394 =head1 SUPPORT
395  
396 You can find documentation for this module with the perldoc command.
397  
398 perldoc Games::TicTacToe
399  
400 You can also look for information at:
401  
402 =over 4
403  
404 =item * RT: CPAN's request tracker
405  
406 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Games-TicTacToe>
407  
408 =item * AnnoCPAN: Annotated CPAN documentation
409  
410 L<http://annocpan.org/dist/Games-TicTacToe>
411  
412 =item * CPAN Ratings
413  
414 L<http://cpanratings.perl.org/d/Games-TicTacToe>
415  
416 =item * Search CPAN
417  
418 L<http://search.cpan.org/dist/Games-TicTacToe/>
419  
420 =back
421  
422 =head1 LICENSE AND COPYRIGHT
423  
424 Copyright (C) 2011 - 2016 Mohammad S Anwar.
425  
426 This program is free software; you can redistribute it and/or modify it under
427 the terms of the the Artistic License (2.0). You may obtain a copy of the full
428 license at:
429  
430 L<http://www.perlfoundation.org/artistic_license_2_0>
431  
432 Any use, modification, and distribution of the Standard or Modified Versions is
433 governed by this Artistic License.By using, modifying or distributing the Package,
434 you accept this license. Do not use, modify, or distribute the Package, if you do
435 not accept this license.
436  
437 If your Modified Version has been derived from a Modified Version made by someone
438 other than you,you are nevertheless required to ensure that your Modified Version
439 complies with the requirements of this license.
440  
441 This license does not grant you the right to use any trademark, service mark,
442 tradename, or logo of the Copyright Holder.
443  
444 This license includes the non-exclusive, worldwide, free-of-charge patent license
445 to make, have made, use, offer to sell, sell, import and otherwise transfer the
446 Package with respect to any patent claims licensable by the Copyright Holder that
447 are necessarily infringed by the Package. If you institute patent litigation
448 (including a cross-claim or counterclaim) against any party alleging that the
449 Package constitutes direct or contributory patent infringement,then this Artistic
450 License to you shall terminate on the date that such litigation is filed.
451  
452 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
453 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
454 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
455 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
456 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
457 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
458 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
459  
460 =cut
461  
462 10 1; # End of Games::TicTacToe
« TicTacToe/Move.pm ↑ Summary TicTacToe/Board.pm »