Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assignment04 (Shamil Nakokhov) #131

Open
wants to merge 1 commit into
base: assignment04
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added assignments/04/game-fat-1.0-SNAPSHOT.jar
Binary file not shown.
41 changes: 41 additions & 0 deletions assignments/04/src/main/kotlin/game/Game.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package game

import java.util.Random

class Game(val Words: List<String>) {
var currentWord: String = ""
val STEPS = 10
fun run() {
println("Welcome to Bulls and Cows game!")
var isFinished = false
while (!isFinished) {
currentWord = Words[Random().nextInt(Words.size - 1)]
println("I offered a ${currentWord.length}-letter word, your guess?")
print("> ")
for (i in 0..STEPS) {
val input = readLine() ?: ""
if (input == currentWord) {
println("You won!")
isFinished = true
break
}
val (cows, bulls) = getBullsAndCows(input)
println("Bulls: $bulls")
println("Cows: $cows")
}
if (!isFinished) {
println("You lose!")
}
println("Wanna play again? Y/N")
print("> ")
isFinished = (readLine() == "N")
}
}

private fun getBullsAndCows(word: String): Pair<Int, Int> {
return word.foldIndexed(Pair(0, 0)) { i, bc, ch ->
Pair(bc.first + if (ch == currentWord[i]) 1 else 0,
bc.second + if (ch != currentWord[i] && ch in currentWord) 1 else 0)
}
}
}
14 changes: 14 additions & 0 deletions assignments/04/src/main/kotlin/game/Main.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package game

fun loadResource(resource: String): String =
try {
object {}.javaClass.getResource(resource)
.readText(Charsets.UTF_8)
} catch (all: Exception) {
throw RuntimeException("Failed to load resource=$resource!", all)
}

fun main(args: Array<String>) {
val game = Game(loadResource("/dictionary.txt").split("\n"))
game.run()
}
Loading