How to write the 7 Boom game. If a number is divided by 7 or includes the digit 7, the user writes Boom in Kotlin

1 Answer

0 votes
fun containsSeven(num: Int): Boolean =
    num.toString().contains('7')

fun isBoom(num: Int): Boolean =
    num % 7 == 0 || containsSeven(num)

fun getUserInput(prompt: String): String {
    print(prompt)
    return readLine()?.trim().orEmpty()
}

fun processTurn(expected: Int, input: String): Boolean {
    val lower = input.lowercase()
    val shouldBoom = isBoom(expected)

    return if (shouldBoom) {
        if (lower != "boom") {
            println("$input (should be Boom)")
            println("YOU LOSE!")
            false
        } else true
    } else {
        if (lower == "boom") {
            println("Wrong move! It was $expected")
            println("YOU LOSE!")
            false
        } else {
            val value = input.toIntOrNull()
            if (value == expected) {
                true
            } else {
                println("Wrong move! It was $expected")
                println("YOU LOSE!")
                false
            }
        }
    }
}

fun runGame() {
    val startInput = getUserInput("Enter a number from which you want to start the game (-1 to exit): ")
    val startNum = startInput.toIntOrNull() ?: return

    if (startNum == -1) return

    var current = startNum

    while (true) {
        val input = getUserInput("Enter a number (or Boom): ")

        if (input == "-1") {
            println("Game Over!")
            break
        }

        if (!processTurn(current, input)) break

        current++
    }
}

fun main() {
    runGame()
}




/*
run:

Enter a number from which you want to start the game (-1 to exit): 6
Enter a number (or Boom): 6
Enter a number (or Boom): Boom
Enter a number (or Boom): 8
Enter a number (or Boom): 9
Enter a number (or Boom): 10
Enter a number (or Boom): 11
Enter a number (or Boom): 12
Enter a number (or Boom): 13
Enter a number (or Boom): Boom
Enter a number (or Boom): 15
Enter a number (or Boom): 16
Enter a number (or Boom): Boom
Enter a number (or Boom): 18
Enter a number (or Boom): 19
Enter a number (or Boom): 20
Enter a number (or Boom): 21
21 (should be Boom)
YOU LOSE!

*/

 



answered Mar 15 by avibootz
...