Last active
December 29, 2015 01:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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