Created
February 16, 2023 00:05
-
-
Save D0zee/061917223fd481efe0bb682f4f2f4e0f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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