fig06_11.pl

来自「PERL语言资料 可以用于PERL程序设计」· PL 代码 · 共 75 行

PL
75
字号
#!/usr/bin/perl
# Fig. 6.11: fig06_11.pl
# The game of Craps.

$roll = rollDice();          # start the game

# determine if the game is a win or loss, 
# or if the game should continue
if ( $roll == 7 or $roll == 11 ) {                   # won?
   $status = "WON";
} 
elsif ( $roll == 2 or $roll == 3 or $roll == 12 ) {  # lost?
   $status = "LOST";
}
else {                       # game continues
   $status = "CONTINUE";     
   $myPoint = $roll;         # must roll this before 7 to win
   print "Point is $myPoint.\n";
}

while ( $status eq "CONTINUE" ) {  # game not won or lost
   $roll = rollDice();             # roll dice again

   if ( $roll == $myPoint ) {      # won?
      $status = "WON";
   }
   elsif ( $roll == 7 ) {          # lost?
      $status = "LOST";
   }
}   

print message( $status );  # display message with result

# subroutines to support the game of craps

# rollDice rolls two dice and returns the sum of the dice
sub rollDice
{
   ( $die1, $die2 ) = ( rollDie(), rollDie() );
   $sum = $die1 + $die2;
   print "Player rolled $die1 + $die2 = $sum.\n";
   return $sum;
}

# rollDie rolls one die and returns its value
sub rollDie
{
   return 1 + int( rand( 6 ) );
}

# prints a message based 
sub message
{
   $status = shift;  # get argument value
   return "Sorry, you lost.\n" if $status eq "LOST";
   return "Congratulations, you won!\n";
}


###########################################################################
#  (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall.     #
#  All Rights Reserved.                                                   #
#                                                                         #
#  DISCLAIMER: The authors and publisher of this book have used their     #
#  best efforts in preparing the book. These efforts include the          #
#  development, research, and testing of the theories and programs        #
#  to determine their effectiveness. The authors and publisher make       #
#  no warranty of any kind, expressed or implied, with regard to these    #
#  programs or to the documentation contained in these books. The authors #
#  and publisher shall not be liable in any event for incidental or       #
#  consequential damages in connection with, or arising out of, the       #
#  furnishing, performance, or use of these programs.                     #
###########################################################################

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?