2019年4月1日月曜日

開発環境

Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 3(functions - Getting Out of Main)、Pool Puzzle(85)の解答を求めてみる。

コード

fun main() {
    val options = arrayOf("Rock", "Paper", "Scissors")
    while (true) {
        val gameChoice = getGameChoice(options)
        val userChoice = getUserChoice(options)
        printResult(userChoice, gameChoice)
    }
}

// kotlinのrandomを利用
fun getGameChoice(optionsParam: Array<String>) =
    optionsParam[kotlin.random.Random.nextInt(optionsParam.size)]

fun getUserChoice(options: Array<String>): String {
    var isValidChoice = false
    var userChoice = ""
    while (!isValidChoice) {
        print("Please enter one of the following:")
        for (item in options) print(" $item")
        println(".")
        val userInput = readLine()
        if (userInput != null && userInput in options) {
            isValidChoice = true
            userChoice = userInput
        }
        if (!isValidChoice) println("You must enter a valid hoice.")
    }
    return userChoice
}
fun printResult(userChoice: String, gameChoice: 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")
}

入出力結果

Please enter one of the following: Rock Paper Scissors.
Kotlin
You must enter a valid hoice.
Please enter one of the following: Rock Paper Scissors.
Rock
You chose Rock. I chose Rock. Tie!
Please enter one of the following: Rock Paper Scissors.
Rock
You chose Rock. I chose Scissors. You win!
Please enter one of the following: Rock Paper Scissors.
Paper
You chose Paper. I chose Rock. You win!
Please enter one of the following: Rock Paper Scissors.
Paper
You chose Paper. I chose Rock. You win!
Please enter one of the following: Rock Paper Scissors.
Scissors
You chose Scissors. I chose Rock. You lose!
Please enter one of the following: Rock Paper Scissors.
Sissors
You must enter a valid hoice.
Please enter one of the following: Rock Paper Scissors.

Process finished with exit code 130 (interrupted by signal 2: SIGINT)

0 コメント:

コメントを投稿