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)]
|
||||
}
|
|
@ -28,7 +28,15 @@ class GameTest {
|
|||
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
Block a user