function feasible?

B

Blah

I keep getting errors if I leave the elsif section in...is there a
better way of doing conditionals?

thanks...


sub victory
{
if ($board[0] eq 'O' && $board[2] eq 'O' && $board[4] eq 'O'
|| $board[5] eq 'O' && $board[7] eq 'O' && $board[9] eq 'O'
|| $board[10] eq 'O' && $board[12] eq 'O' && $board[14] eq 'O'
|| $board[0] eq 'O' && $board[7] eq 'O' && $board[14] eq 'O'
|| $board[4] eq 'O' && $board[7] eq 'O' && $board[10] eq 'O')
{
print "Player 1 Wins\n";
}


elsif ($board[0] eq 'X' && $board[2] eq 'X' && $board[4] eq
'X'
|| $board[5] eq 'X' && $board[7] eq 'X' && $board[9] eq 'X'

|| $board[10] eq 'X' && $board[12] eq 'X' && $board[14] eq
'X'
|| $board[0] eq 'X' && $board[7] eq 'X' && $board[14] eq
'X'
|| $board[4] eq 'X' && $board[7] eq 'X' && $board[10] eq
'X'
)
{
print "Player 2 Wins\n";
}


else
{
decider();
}
}
 
U

usenet

Blah said:
I keep getting errors if I leave the elsif section in...is there a
better way of doing conditionals?

Your code works fine for me. But, if you look more closely, you will
see that you are doing the same group of operations twice (once for "X"
and once for "O"). That screams loop. And you are doing the same basic
sort of operations within each block. That screams loop.

Consider something like this:

foreach my $group( [0,2,4],[5,7,9],[10,12,14],[0,7,14],[4,7,10] ) {
foreach my $player('X','O') {
if ( (join '', @board[@$group]) eq $player x 3 ) {
print "Player $player Wins!\n";
}
}
}
 
U

usenet

<snip not-very-well-thought-out code>

Ya know, since the conditionals are identical for X and O, all you
really need to do is see if you match three-in-a-row, so the inside
loop is not really needed (ie, you don't need to check "is there XXX"
and then check "Is there OOO" - all you need to do is check if the
value of the first element is repeated two more times, and, if it is,
that value determines the winner). So you could instead do something
even more simple like this:

foreach my $group( [0,2,4],[5,7,9],[10,12,14],[0,7,14],[4,7,10] ) {
if ( (join '', @board[@$group]) eq $board[ $group->[0] ] x 3 ) {
print "Player $board[ $group->[0] ] Wins!\n";
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top