While this might be too late for your submission of code, I still would like to propose a slightly different approach. At the center of my proposal is a list of all the possible lines (rows, columns and diagonals) that constitute a potential win. This way you can replace your if, elsif chain with a loop. Secondly, I would count the Xs, Os and blanks for each line and then decide whether or not there is a win or a draw situation. It could look like this:
use strict; use warnings; my @board = qw( O X O X X O O O X ); my @tests = ( # rows [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], # columns [ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ], # diagonals [ 0, 4, 8 ], [ 2, 4, 6 ] ); # testing for win and draw my $win = 0; my $draw = 1; for my $line ( @tests ) { my %symbols = ( _ => 0, X => 0, O => 0 ); # count occurences of each symbol $symbols{$board[$_]}++ for @$line; # test for winning if( $symbols{'X'}==3 or $symbols{'O'}==3 ) { $win = 1; $draw = 0; last; } # test for "open lines" if( $symbols{'X'}==0 or $symbols{'O'}==0 ) { $draw = 0; } } print "Win: $win, draw: $draw\n";
In reply to Re: TicTacToe Code Help.
by hdb
in thread TicTacToe Code Help.
by Jsamp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |