This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.tabak.jacob.war | |
class Game(private val deck1: Deck, private val deck2: Deck) { | |
fun play() : Int { | |
println("Starting game!") | |
printDecks() | |
var winner = 0 | |
while (deck1.isNotEmpty() && deck2.isNotEmpty()) { | |
winner = battle() | |
} | |
return winner | |
} | |
private fun battle(army1: List<Int> = ArrayList(), army2: List<Int> = ArrayList(), depth: Int = 0) : Int { | |
return if (deck1.isEmpty() && deck2.isEmpty()) { | |
0 | |
} else if (deck1.isEmpty() || deck2.isEmpty()) { | |
if (deck1.isNotEmpty()) 1 else 2 | |
} else { | |
val card1 = deck1.poll() | |
val card2 = deck2.poll() | |
val winner = when { | |
card1 > card2 -> 1 | |
card1 < card2 -> 2 | |
else -> war(depth + 1) | |
} | |
if (winner != 0) { | |
claim(winner, army1, army2, card1, card2) | |
} | |
return winner | |
} | |
} | |
private fun war(depth: Int = 0) : Int { | |
println("War!") | |
val army1 = ArrayList<Int>() | |
val army2 = ArrayList<Int>() | |
for (i in 1..3) { | |
if (deck1.size > 1 && deck2.size > 1) { | |
if (deck1.isEmpty() || deck2.isEmpty()) { | |
return if (deck1.isNotEmpty()) 1 else 2 | |
} else { | |
army1.add(deck1.poll()) | |
army2.add(deck2.poll()) | |
} | |
} | |
} | |
return battle(army1, army2, depth) | |
} | |
private fun claim(winner: Int, army1: List<Int>, army2: List<Int>, card1: Int, card2: Int = 0) { | |
val winningDeck = if (winner == 1) deck1 else deck2 | |
val (winningArmy, losingArmy) = if (winner == 1) army1 to army2 else army2 to army1 | |
val (winningCard, losingCard) = if (winner == 1) card1 to card2 else card2 to card1 | |
val spoils = ArrayList<Int>() | |
winningArmy.forEach { spoils.add(it) } | |
spoils.add(winningCard) | |
losingArmy.forEach { spoils.add(it) } | |
spoils.add(losingCard) | |
spoils.forEach { winningDeck.offer(it) } | |
println("Deck$winner won $spoils") | |
printDecks() | |
} | |
private fun printDecks() { | |
println("""Deck1: $deck1 | |
|Deck2: $deck2 | |
""".trimMargin()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment