Skip to content

Instantly share code, notes, and snippets.

@pouyan-ghasemi
Last active December 29, 2015 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pouyan-ghasemi/7590485 to your computer and use it in GitHub Desktop.
Save pouyan-ghasemi/7590485 to your computer and use it in GitHub Desktop.
This is the Rock, Scissor, Paper, written in Scala! I am not sure about the rules but what is cool about it is the Pattern Matching in Scala.
package game
import Math.random
object RSPGame {
abstract class Choice
case object Rock extends Choice
case object Paper extends Choice
case object Scissor extends Choice
abstract class Result {
override def toString = this match{
case NonDeterment => "Cannot find a winner"
case YouWon => "You are the winner"
case ComputerWon => "Computer is the winner"
case _ => "Invalid Entry"
}
}
case object NonDeterment extends Result
case object YouWon extends Result
case object ComputerWon extends Result
protected val options = List(Rock, Paper, Scissor)
protected def rand(x: Int):Int = (random * x).toInt
protected def playTheGame(played: Choice): Result ={
val computerChoice = options(rand(3))
(computerChoice, played) match {
case (Rock, Scissor) => ComputerWon
case (Scissor, Rock) => YouWon
case (Scissor, Paper) => ComputerWon
case (Paper, Scissor) => YouWon
case (Rock, Paper) => YouWon
case (Paper, Rock) => ComputerWon
case (_, _) => NonDeterment
}
}
/**
* @param Rock, Scissor or Paper!
*/
def play(input: String): String = input match{
case "Rock" => playTheGame(Rock) toString
case "Scissor" => playTheGame(Scissor) toString
case "Paper" => playTheGame(Paper) toString
case _ => "Invalid Entry"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment