Advertisement
Guest User

Rock-paper-scissors example in perl updated

a guest
Jul 2nd, 2014
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/perl
  2. #
  3. # Rock-paper-scissors example in perl by Scott Beardwood - This work is licensed under a Creative Commons
  4. # updated version posted at http://pastebin.com/g7BfBhcs
  5.  
  6. use strict;
  7. use warnings;
  8.  
  9. print "\n\nRock-paper-scissors\n\nBest of 3\nPlease Select...\n";
  10.  
  11. my $p1 = 0;
  12. my $p2 = 0;
  13. my $count = 0;
  14.  
  15. while ($count < 3) {
  16.  
  17. print "Game ",$count+1,"\n\n1.Rock\n2.Paper\n3.Scissors\n?"; # $count+1 add one as count starts at zero
  18.  
  19. my $selection = <>; #get users input
  20. chomp($selection); #remove newline
  21. my $computer = int(rand(2)) + 1; #generate random number for computer
  22.  
  23. #show computers choice
  24. if ($computer == 1) {
  25.     print "\nComputer picks $computer Rock\n";
  26. } elsif ($computer == 2) {
  27.     print "\nComputer picks $computer Paper\n";
  28. } elsif ($computer == 3) {
  29.     print "\nComputer picks $computer Scissors\n";
  30. } else {
  31.     print "\nComputer is trying to cheat";
  32. }
  33.  
  34. # Check for non-numeric characters
  35. if ($selection =~ /\D/){
  36.     print "\nPlease enter a number (1, 2, ,3 ) \n";
  37. }
  38.  
  39. my $x = $selection + $computer; # add users choice to computer to work out winner
  40.  
  41. # GAME
  42. if ($selection == $computer){
  43.     print "Its a draw\n";
  44.     $count ++;
  45.     next;
  46. }
  47. elsif ($x == 5) {
  48.     print "Scissors beats paper\n";
  49.     if ($selection eq 2) {print "You win\n";$p1 ++;} else {print "I win\n";$p2 ++;}
  50.     $count ++;
  51.     next;
  52. }
  53. elsif ($x == 3) {
  54.     print "Paper beats rock\n";
  55.     if ($selection eq 3) {print "You win\n";$p1 ++;} else {print "I win\n";$p2 ++;}
  56.     $count ++;
  57.     next;
  58. }
  59. elsif ($x == 4) {
  60.     print "Rock beats Scissors\n";
  61.     if ($selection eq 1) {print "You win\n";$p1 ++;} else {print "I win\n";$p2 ++;}
  62.     $count ++;
  63.     next;
  64. } else {
  65. print "Error did not compute ( debug = selection = $selection computer = $computer added valuer = $x )\n";
  66. }
  67.  
  68. } # end while loop
  69.  
  70. print "\n Final score Player 1 = $p1 Computer = $p2\n";
  71.  
  72. if ($p1 > $p2) {
  73.     print "Player one wins\n";
  74. }
  75. elsif ($p1 == $p2) {
  76.     print "It was a Draw\n";
  77. }
  78. else {
  79.     print "Computer Wins\n";
  80. }
  81. print "\n\nHit a Key to End";<>;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement