Skip to content

Instantly share code, notes, and snippets.

@D0zee
Created February 16, 2023 00:05
Show Gist options
  • Save D0zee/061917223fd481efe0bb682f4f2f4e0f to your computer and use it in GitHub Desktop.
Save D0zee/061917223fd481efe0bb682f4f2f4e0f to your computer and use it in GitHub Desktop.
package hangman
fun isCorrectInput(userInput: String): Boolean {
return userInput.length == 1 && userInput[0].isLetter()
}
fun safeUserInput(): Char {
println("Please input your guess.")
var input = readln()
while (!isCorrectInput(input)) {
if (input.length == 1) {
println("Use only English Letters!")
} else {
println("Length must be 1!")
}
println("Please input your guess.")
input = readln()
}
return input[0].uppercaseChar();
}
fun generateNewUserWord(secret: String, guess: Char, currentUserWord: String): String {
val answer = StringBuilder()
for (i in 0 until WORD_LENGTH) {
if (secret[i] == guess) {
answer.append(guess + SEPARATOR)
} else {
answer.append(currentUserWord[i * 2] + SEPARATOR)
}
}
return answer.toString()
}
fun isComplete(secret: String, currentGuess: String): Boolean {
return secret == currentGuess.replace(SEPARATOR, "")
}
fun main() {
println(GREETING)
val secretWord = words.random()
var currentUserWord = (DASH + SEPARATOR).repeat(WORD_LENGTH)
println("I guessed a word: $secretWord")
var i = 0;
while (i < MAX_ATTEMPTS_COUNT && isComplete(secretWord, currentUserWord)) {
val guess: Char = safeUserInput()
val newUserWord = generateNewUserWord(secretWord, guess, currentUserWord)
if (currentUserWord != newUserWord) {
println("Great! This letter is in the word! The current word: $newUserWord")
} else {
println("Sorry, the secret does not contain the symbol: $guess")
}
currentUserWord = newUserWord
i++
}
if (isComplete(secretWord, currentUserWord)) {
println("Congratulations! You guessed!")
} else {
println("Sorry, you lost! My word is $secretWord")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment