Implement main game loop
This commit is contained in:
parent
fad1c38b65
commit
eb37cd64e5
|
@ -1,7 +1,9 @@
|
|||
package rps
|
||||
|
||||
import kotlin.random.Random
|
||||
|
||||
fun main() {
|
||||
println("Hello, world")
|
||||
println(playGame(100))
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -35,8 +37,18 @@ fun determineOutcome(first: Move, second: Move): Outcome = when {
|
|||
}
|
||||
|
||||
// Note: This would be slightly more efficient (but a lot less elegant) with an imperative loop and three mutable integers.
|
||||
fun calculateGameSummary(turns: List<Outcome>) = GameSummary(
|
||||
wins = turns.count { it == Outcome.WIN },
|
||||
draws = turns.count { it == Outcome.DRAW },
|
||||
losses = turns.count { it == Outcome.LOSS },
|
||||
fun List<Outcome>.calculateGameSummary() = GameSummary(
|
||||
wins = count { it == Outcome.WIN },
|
||||
draws = count { it == Outcome.DRAW },
|
||||
losses = count { it == Outcome.LOSS },
|
||||
)
|
||||
|
||||
fun playGame(turns: Int): GameSummary = generateSequence { randomMove() }
|
||||
.take(turns)
|
||||
.map { determineOutcome(it, Move.ROCK) }
|
||||
.toList()
|
||||
.calculateGameSummary()
|
||||
|
||||
fun randomMove(): Move = Move.values().let { allMoves ->
|
||||
allMoves[Random.nextInt(allMoves.size)]
|
||||
}
|
|
@ -9,10 +9,10 @@ class GameTest {
|
|||
@Test
|
||||
fun testOutcomeCalculation() {
|
||||
val games = listOf(
|
||||
Triple(PAPER, ROCK, WIN),
|
||||
Triple(ROCK, PAPER, LOSS),
|
||||
Triple(PAPER, SCISSORS, LOSS),
|
||||
Triple(ROCK, ROCK, DRAW),
|
||||
Triple(PAPER, ROCK, WIN),
|
||||
Triple(ROCK, PAPER, LOSS),
|
||||
Triple(PAPER, SCISSORS, LOSS),
|
||||
Triple(ROCK, ROCK, DRAW),
|
||||
)
|
||||
for ((first, second, expected) in games) {
|
||||
assertEquals(determineOutcome(first, second), expected)
|
||||
|
@ -22,13 +22,21 @@ class GameTest {
|
|||
@Test
|
||||
fun `game summary should count outcomes`() {
|
||||
val gameLists = listOf(
|
||||
listOf(WIN, WIN, WIN) to GameSummary(3, 0, 0),
|
||||
listOf(WIN, DRAW, LOSS) to GameSummary(1, 1, 1),
|
||||
listOf(WIN, LOSS, WIN) to GameSummary(2, 0, 1),
|
||||
listOf(WIN, DRAW, DRAW, DRAW) to GameSummary(1, 3, 0),
|
||||
listOf(WIN, WIN, WIN) to GameSummary(3, 0, 0),
|
||||
listOf(WIN, DRAW, LOSS) to GameSummary(1, 1, 1),
|
||||
listOf(WIN, LOSS, WIN) to GameSummary(2, 0, 1),
|
||||
listOf(WIN, DRAW, DRAW, DRAW) to GameSummary(1, 3, 0),
|
||||
)
|
||||
for ((outcomes, expectedSummary) in gameLists) {
|
||||
assertEquals(calculateGameSummary(outcomes), expectedSummary)
|
||||
assertEquals(outcomes.calculateGameSummary(), expectedSummary)
|
||||
}
|
||||
}
|
||||
|
||||
// We can’t test the outcome because it’s random,
|
||||
// but at least we can verify that the total number is correct.
|
||||
@Test
|
||||
fun `game summary should have correct number of outcomes`() {
|
||||
val summary = playGame(50)
|
||||
assertEquals(summary.wins + summary.draws + summary.losses, 50)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue