Skip to content

Instantly share code, notes, and snippets.

@dtanner
Created May 8, 2019 21:27
Show Gist options
  • Save dtanner/54a8dc0e111d9b62d44fff6501266d1c to your computer and use it in GitHub Desktop.
Save dtanner/54a8dc0e111d9b62d44fff6501266d1c to your computer and use it in GitHub Desktop.
import java.lang.Math.ceil
import java.lang.Math.pow
import kotlin.math.log2
fun main() {
println("\n Welcome to Up-To-9-Cards Game!")
println("\n================================\n")
displayCards(getCards())
println("\n\nDone!\n")
}
fun getCards(): List<Int> {
var validCount = 0
val numbers = mutableListOf<Int>()
while (validCount < 9) {
print("Please enter a card or enter -1 to end: ")
val codedNumber = readLine()!!.toInt()
if (codedNumber == -1) {
return numbers
} else if (codedNumber < 0 || codedNumber > 51) {
println("Not a valid card entry.")
} else {
numbers.add(codedNumber)
validCount += 1
}
}
return numbers
}
fun getSuitNumber(codedNumber: Int): Int = codedNumber % 4
fun getSuitString(codedNumber: Int): String {
return when (getSuitNumber(codedNumber)) {
0 -> "Clubs"
1 -> "Spades"
2 -> "Diamonds"
3 -> "Hearts"
else -> ""
}
}
fun getCardValue(codedNumber: Int): Int = codedNumber / 4 + 1
fun displayCards(cards: List<Int>) {
println("Your hand is:\n")
cards.forEach {
println(" ${getCardValue(it)} of ${getSuitString(it)}")
}
println("")
val handValue = calculateHandValue(cards)
println("The Total value of your hand is:\n$handValue points")
}
fun calculateHandValue(cards: List<Int>): Int {
val baseScore = simpleSumCards(cards)
var totalValue = baseScore
if (hasThreeOrMoreNonNumberCards(cards)) {
totalValue = totalValue * totalValue + 7
}
if (isPrime(totalValue)) {
totalValue += nextHighestPowerOfTwo(totalValue)
}
return totalValue
}
fun nextHighestPowerOfTwo(value: Int): Int {
return pow(2.toDouble(), ceil(log2(value.toDouble()))).toInt()
}
fun simpleSumCards(cards: List<Int>): Int {
return cards.sumBy { getCardValue(it) - getSuitNumber(it) }
}
fun hasThreeOrMoreNonNumberCards(cards: List<Int>): Boolean {
return cards.count { getCardValue(it) >= 11 || getCardValue(it) == 1 } >= 3
}
fun isPrime(number: Int): Boolean {
return (2..number / 2).none { number % it == 0 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment