Perl: Random dice game using array, case, and for Windows with Perl installed
I had a bit of free time, so I created this craps game for Windows. You can also run it on Linux and Unix by changing the path to where your Perl is located on the system. The application uses variable, a pre-defined array length, functions, and a do – while loop with a sentinal value to terminate the loop.
I was a little tired of looking for examples of how to use Perl functionality and not seeing anything with practical usage. You can download Active Perl for free at: http://www.activestate.com/activeperl/downloads .
Enjoy!
#!C:\Perl64\bin\perl -w #Crap Shoot is a fun dice game #Programmer: Mike Kniaziewicz #Version: 1.0.0 #Revision Date: 3/3/2012 use strict; use warnings; #Declare variables my $counter; my $x; my $rand_number; my $answer; my $totalroll; my @dice = (1..3); my $dice; #Using a do - while loop because everyone would want to play at least
# once. do { print "\n\nRoll #:\t" . ++$counter . "\n\n"; #Generate the random number and total for the roll. $totalroll = 0; for ($x = 1; $x < $#dice + 1 ; $x++) { $dice[$x] = &random_number; print "Roll # " . $x . ":\t" . $dice[$x] . "\n\n"; $totalroll = $dice[$x] + $totalroll; &draw_dice; print "\n"; } print "Total roll is:\t" . $totalroll . "\n"; &makepoint; &Instructions; #Get the response to playing again $answer = <STDIN>; chomp($answer); } while ($answer eq "y"); sub Instructions { print "\nEnter y to roll again: "; } sub random_number { my $rand_dice = int( rand(6)) + 1; return $rand_dice ; } sub draw_dice { if ($dice[$x] == 1) { print "\t\t.......\n"; print "\t\t. .\n"; print "\t\t. * .\n"; print "\t\t. .\n"; print "\t\t.......\n"; } elsif ($dice[$x] == 2) { print "\t\t.......\n"; print "\t\t. .\n"; print "\t\t. * * .\n"; print "\t\t. .\n"; print "\t\t.......\n"; } elsif ($dice[$x] == 3) { print "\t\t.......\n"; print "\t\t. * .\n"; print "\t\t. * .\n"; print "\t\t. * .\n"; print "\t\t.......\n"; } elsif ($dice[$x] == 4) { print "\t\t.......\n"; print "\t\t. * * .\n"; print "\t\t. .\n"; print "\t\t. * * .\n"; print "\t\t.......\n"; } elsif ($dice[$x] == 5) { print "\t\t.......\n"; print "\t\t. * * .\n"; print "\t\t. * .\n"; print "\t\t. * * .\n"; print "\t\t.......\n"; } elsif ($dice[$x] == 6) { print "\t\t.......\n"; print "\t\t. * * .\n"; print "\t\t. * * .\n"; print "\t\t. * * .\n"; print "\t\t.......\n"; } } sub makepoint { if ($counter == 1) { if($totalroll == 7) { print "YOU WON!!!\n"; $counter = 0; } } if ($counter == 1) { if ($totalroll == 11) { print "YOU WON!!!\n"; $counter = 0; } } if ($counter > 1) { if ($totalroll == 7) { print "YOU LOSE! Craps\n"; $counter = 0; } if ($totalroll == 11) { print "YOU WIN!!!\n"; $counter = 0; } } }
You can see how to actually create an array and us it for math.