in reply to logic problem with perl game
Hi mynameisG,
s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
A couple of suggestions about simplifying this part of your code:
if($game eq "Fight") { if($response eq "arrow" && $correctryhm eq "sparrow") { $correctryhm=$correctryhm; $response=param('response'); $win=param('win'); $win=$win+1; } elsif($response ne "arrow" && $correctryhm eq "sparrow") { $correctryhm=$correctryhm; $response=param('response'); $lose=param('lose'); $lose=$lose+1; } if($response eq "axe" && $correctryhm eq "wax") { $correctryhm=$correctryhm; $response=param('response'); $win=param('win'); $win=$win+1; } elsif($response ne "axe" && $correctryhm eq "wax") { $correctryhm=$correctryhm; $response=param('response'); $lose=param('lose'); $lose=$lose+1; }code: ...
- The line $correctryhm=$correctryhm; doesn't do anything useful (it assigns variable $correctryhm to its current value). You can safely remove it.
- The line $win=param('win'); can safely be done outside of the if...elsif...else clause, to avoid the repetition. Same thing with $response=param('response');
- A common shorthand for $X = $X + 1 is ++$X. Same thing for $x = $X - 1 => --$X.
Just the above changes will already significantly reduce the complexity of the one big conditional clause:
$response = param('response'); $win = param('win'); $lose = param('lose'); if($game eq "Fight") { if($response eq "arrow" && $correctryhm eq "sparrow") { ++$win; } elsif($response ne "arrow" && $correctryhm eq "sparrow") { ++$lose; } if($response eq "axe" && $correctryhm eq "wax") { ++$win; } elsif($response ne "axe" && $correctryhm eq "wax") { ++$lose; } if($response eq "shield" && $correctryhm eq "field") { ++$win; } elsif($response ne "shield" && $correctryhm eq "field") { ++$lose; } if($response eq "spear" && $correctryhm eq "tear") { ++$win; } elsif($response ne "spear" && $correctryhm eq "tear") { ++$lose; } if ($win <= 9 && $lose <= 10) { # Removed for brevity ... } }
And if you want to generalize further, you could create a hash (see perldata for more on hashes) containing the expected, correct rhyme for each word:
$response = param('response'); $win = param('win'); $lose = param('lose'); my %correct_rhyme = ( 'arrow' => 'sparrow', 'axe' => 'wax', 'shield' => 'field', 'spear' => 'tear', ); if($game eq "Fight") { my $correct = $correct_rhyme{$response}; if ($response eq $correct) { ++$win; } else { ++$lose; } if ($win <= 9 && $lose <= 10) { # Removed for brevity ... } }
Now, when you want to add a new word/rhyme pair, it's a straightforward matter of just adding the key/value pair to the %correct_rhyme hash.
s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: logic problem with perl game
by mynameisG (Novice) on Dec 05, 2010 at 23:26 UTC | |
by mynameisG (Novice) on Dec 05, 2010 at 23:38 UTC |
In Section
Seekers of Perl Wisdom