Rock Paper Scissors
December 10, 2013
Today’s exercise is our five hundredth! It’s hard to believe. I remember writing the fiftieth exercise and thinking I would never get to a hundred. Even after all this practice it is hard to write two exercises every week, but your comments and private emails and referrals from other web sites sustain me. Many thanks to all my readers.
Our tradition for these milestone exercises is to have a party, which means we need a game: so we write one. Today’s exercise is to write an interactive rock-paper-scissors game: rock blunts scissors, paper wraps rock, scissors cut paper.
Your task is to write a program to play rock-paper-scissors with a human player, keeping score as you go. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Bonus points if the program uses a webcam to receive input?
Haskell version (requires GHC, doesn’t run in codepad :( ). Not the most beautiful program in Haskell, but nevertheless
http://codepad.org/3oEk8lKq
https://github.com/notsoluckycharm/samples/tree/master/php/rock-paper-scissors
In Python.
Badly written Clojure… /
Not keeping score, so I lose, but anyway:
#! /usr/bin/env gsi-script
(display "Content-Type: text/plain") (newline)
(newline)
(random-source-randomize! default-random-source)
(define parser '(("move=rock" . 0) ("move=paper" . 1) ("move=scissors" . 2)))
(define writer
'((0 . ((0 . "rock ties with rock") (1 . "paper wraps rock") (2 . "rock blunts scissors")))
(1 . ((1 . "paper ties with paper") (2 . "scissors cut paper")))
(2 . ((2 . "scissors tie with scissors")))))
(define (judge client server)
(cond
((= client server) " - it's a tie")
((= (modulo (+ client 1) 3) server) " - server wins")
((= client (modulo (+ server 1) 3)) " - client wins")))
(define client-move (cdr (assoc (getenv "QUERY_STRING") parser)))
(define server-move (random-integer 3))
(define lesser (cdr (assoc (min client-move server-move) writer)))
(display (list-ref '("rock! " "paper! " "scissors! ") server-move))
(display (cdr (assoc (max client-move server-move) lesser)))
(display (judge client-move server-move))
(newline)
It’s a Gambit CGI script. With a web server running locally in port 8080 and accepting CGI programs in cwd, play like this:
$ curl http://localhost:8080/rock.cgi'?'move=paper
rock! paper wraps rock - client wins
any java code for rock paper scissors.. it would be two clients and a server?
Here’s a Racket version with a bunch of different AIs to play against (or against each other): Rock-paper-scissors on jverkamp.com.
Granted, none of them are that smart (I’m considering writing one based on a Hidden Markov Model), but it’s still pretty neat.
Here is a PHP version.
Not too happy with a couple of sections, but overall not bad. https://github.com/lmon/samples/blob/master/RockPaperScissors.php