#!/usr/bin/perl

print qq{Content-type: text/html\n\n<html><body bgcolor="white">}; 

#--------------------------(reads the data)----------------------

$input = $ENV{"QUERY_STRING"}; 

@pairs = split(/&/, $input); 

foreach $pair (@pairs) {
  ($name, $value) = split(/=/, $pair); 
  $data{$name} = $value; # builds a hashtable 
}

#--------------------------(define your state)-------------------

$computerScore = $data{computerScore}; 
$userScore = $data{userScore}; 
$computerChoice = $data{computerChoice}; 
$ticket = $data{ticket}; 

@choices = ("paper", "rock", "scissors"); 

#-------------------------(check state)--------------------------

if ($ticket) { #----------(you're in the game)-------------------

  $userInput = $data{userInput}; 
  
  if (($userInput + 1) % 3 == $computerChoice) {
    $message = "You won."; 
    $userScore += 1;     
  } elsif (($computerChoice + 1) % 3  == $userInput) {
    $message = "Computer wins."; 
    $computerScore += 1; 
  } else {
    $message = "This is a tie."; 
  } 
  $computerChoice = int(rand(3)); 
} else { #----------------(new player)---------------------------
  
  $message = "You are a new player. Welcome."; 
  $computerScore = 0; 
  $userScore = 0; 
  $computerChoice = int(rand(3)); 
  $ticket = "game on"; 
} 

#------------------------ (store state get ready for more input)-

$me = $ENV{"SCRIPT_NAME"}; 

$choice = $choices[$computerChoice]; 

print qq{<form method="GET" action="$me">
  $message <p>
  Computer's choice was: $choice <p>
  Please choose: <select name="userInput">
    <option value="0"> Paper 
    <option value="1"> Rock 
    <option value="2"> Scissors 
  </select> <p>
  Score currently: $computerScore - $userScore <p>
  <input type="hidden" name="computerScore" value="$computerScore">
  <input type="hidden" name="computerChoice" value="$computerChoice">
  <input type="hidden" name="userScore" value="$userScore">
  <input type="hidden" name="ticket" value="$ticket">
  Then press <input type="submit" value="Proceed">
</form>
}; 

print qq{</body></html>};