Skip to content

Instantly share code, notes, and snippets.

@deya-eldeen
Last active August 14, 2016 19:10
Show Gist options
  • Save deya-eldeen/3ddd3c968b7180f196b786f5a7421ff4 to your computer and use it in GitHub Desktop.
Save deya-eldeen/3ddd3c968b7180f196b786f5a7421ff4 to your computer and use it in GitHub Desktop.
/// METHOD 1 : simple thinking
var playerSelection = "" // possible values are r,p,s
var cpuSelection = "" // possible values are r,p,s
var resultString = ""
if(playerSelection == "r")
{
if(cpuSelection == "r")
{
resultString = "draw"
}
else if(cpuSelection == "p")
{
resultString = "lose"
}
else if(cpuSelection == "s")
{
resultString = "win"
}
}
else if(playerSelection == "p")
{
if(cpuSelection == "r")
{
resultString = "win"
}
else if(cpuSelection == "p")
{
resultString = "draw"
}
else if(cpuSelection == "s")
{
resultString = "lose"
}
}
else if(playerSelection == "s")
{
if(cpuSelection == "r")
{
resultString = "lose"
}
else if(cpuSelection == "p")
{
resultString = "win"
}
else if(cpuSelection == "s")
{
resultString = "draw"
}
}
/// METHOD 2 : nested trinary operator
resultString = ( playerSelection == "r") ? (cpuSelection == "r" ? "draw" : (cpuSelection == "p") ? "lose" : "win") : ((( playerSelection == "p") ? (cpuSelection == "r" ? "win" : ((cpuSelection == "p") ? "draw" : "lose")):((cpuSelection == "r" ? "lose" : ((cpuSelection == "p") ? "win" : "draw")))))
/// METHOD 3 : enums
enum GameResult : Int {
case None = 0
case Win = 1
case Draw = 2
case Lose = 3
}
enum Selection : Int {
case Paper = 1
case Rock = 2
case Scissor = 3
}
var pSelect = Selection.Paper;
var cSelect = Selection.Rock;
var result = GameResult.None
var playerRotation = (pSelect.rawValue) % 3 + 1;
if(pSelect.rawValue == cSelect.rawValue)
{
result = GameResult.Draw
}
else if(playerRotation == cSelect.rawValue)
{
result = GameResult.Win
}
else
{
result = GameResult.Lose
}
/// Method 4
if (playerSelection == cpuSelection)
{
resultString = "draw"
}
else if (playerSelection == "r" && cpuSelection == "p") || (playerSelection == "p" && cpuSelection == "s") || (playerSelection == "s" && cpuSelection == "r")
{
resultString = "lose"
}
else
{
resultString = "win"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment