-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathGame.kt
45 lines (40 loc) · 1.33 KB
/
Game.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package chapter3
/**
*
*/
fun main() {
val options = arrayOf("Rock", "Paper", "Scissors")
val gameChoice = getGameChoice(options)
val userChoice = getUserChoice(options)
printResult(gameChoice, userChoice)
}
fun getGameChoice(optionsParam: Array<String>) =
optionsParam[(Math.random() * optionsParam.size).toInt()]
fun getUserChoice(optionsParam: Array<String>): String {
var isValidChoice = false
var userChoice = ""
while (!isValidChoice) {
print("Please enter one of the following:")
for (item in optionsParam) print(" $item")
println(".")
val userInput = readLine()
if (userInput != null && userInput in optionsParam) {
isValidChoice = true
userChoice = userInput
}
if (!isValidChoice) println("You must enter a valid choice.")
}
return userChoice
}
fun printResult(gameChoice: String, userChoice: String) {
val result: String
if (userChoice == gameChoice) result = "Tie!"
else if (
(userChoice == "Rock" && gameChoice == "Scissors") ||
(userChoice == "Paper" && gameChoice == "Rock") ||
(userChoice == "Scissors" && gameChoice == "Paper"))
result = "You win!"
else
result = "You lose!"
println("You chose $userChoice. I chose $gameChoice. $result")
}