Watkins Web 3: Blog

Exercise 8: Rock Paper Scissors

Write a program that lets a human user play Rock Paper Scissors against the computer. Playing the game should have the computer choose a random throw and then echo a string like this:

You threw Rock. Computer threw Paper. Computer wins.

In Terminal, type cd ~/Desktop and hit return. Now type ls and hit return. That should list all the files and folders on the Desktop, so you’re ready to run PHP files that are saved there. (You can review other Terminal commands on the Web 2 blog).

We want to run our script (say it’s called myscript.php) but also pass it a string that represents our “throw”. If you want to want play Scissors, type this:

php myscript.php "Scissors"

And here’s the beginning of the script we did in class:

<?php
// capture the user input (whatever they put after the filename in Terminal)
$user_throw = $argv[1];
// store possiblities in an array
$throws[0] = "Rock";
$throws[1] = "Paper";
$throws[2] = "Scissors";
$random_number = rand(0,2);
$computer_throw =  $throws[$random_number];
echo "\n\n\n\n";
echo "The user threw $user_throw";
echo "\n\n\n\n";
echo "And the Computer threw $computer_throw";
echo "\n\n\n\n";
?>

Bonus Round: Now convert your program into a function which picks a random throw for both User and Computer, plays them against each other, and keeps track of who won. It will look something like this:

function playgame($user_throw, $comp_throw) {
[code goes here]
}

Embed your function in a loop that runs the game 100 times. Output the winner of each game and also announce the total at the end (“User won 35, Computer won 35, and their were 30 ties”).

Update: Below are some possible solutions. There are probably many more ways to do this.

Exercise 8 Solution