added in depth charge in perl

This commit is contained in:
drbaggy
2021-02-16 08:36:15 +00:00
parent c5e11d4d9d
commit c4e3f93b80
2 changed files with 69 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html)
Conversion to [Perl](https://www.perl.org/)
## Conversion
Not a difficult conversion - but a chance to throw in a few ways
Perl makes life easy.
* To get the sub permission which is a random location in the g x g x g grid we can use:
* assigning multiple variables in list form ($a,$b,$c) = (?,?,?)
* where the list on the right hand side is generated with a map function
* We use ternarys to generate the message if you miss the sub.
* We use join to stitch the pieces of the string together.
* If we have a ternary where we don't want to return anything we return an empty list rather than an empty string - if you return the latter you still get the padding spaces.

View File

@@ -0,0 +1,52 @@
#!/usr/bin/perl
use strict;
use warnings;
print ' Depth Charge
Creative Computing Morristown, New Jersey
Depth Charge Game
Dimensions of Search Area? ';
my $g = <STDIN>;
my $n = int( log($g) / log 2 ) + 1;
print '
You are the captain of the Destroyer USS Computer
an enemy sub has been causing you trouble. Your
mission is to destroy it. You have ',$n,' shots.
Specify depth charge explosion point with a
trio of number -- the first two are the surface
co-ordinates; the third is the depth.
';
while(1) { ## Repeat until we say no....
print "\nGood luck!\n\n";
my ($a,$b,$c) = map { int rand $g } 1..3; ## Get the location
my $hit = 0; ## Keep track if we have won yet!
foreach ( 1..$n ) {
print "\nTrial # $_ ? ";
my ( $x, $y, $z ) = split m{\D+}, <STDIN>;
if( $x==$a && $y==$b && $z==$c ) {
$hit = 1; ## We have won
print "\n\nB O O M ! ! You found it in $_ tries!\n";
last;
}
print join q( ), 'Sonar reports show was',
$y < $b ? 'South' : $y > $b ? 'North' : (),
$x < $a ? 'West' : $x > $a ? 'East' : (),
$x == $a && $y == $b ? () : 'and' ,
$z < $c ? 'too high' : $z > $c ? 'too low' : 'depth OK',
".\n";
}
## Only show message if we haven't won...
print "\nYou have been torpedoed! Abandon ship!\nThe submarine was at $a, $b, $c\n" unless $hit;
print "\n\nAnother game (Y or N)? ";
last unless <STDIN> =~ m{Y}i; ## Y or y not typed so leave loop
}
## Say good bye
print "OK. Hope you enjoyed yourself.\n\n";