// GuessAWord.kt Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2024-01-20 File created. /* This program is a simple computer game in which the player has to guess the characters of a word, or the player may also try to guess the whole word. This program demonstrates: - the use of the standard StringBuilder class. StringBuilder objects are strings that can be modified, i.e., their characters can be changed. Standard String objects cannot be modified once they have been created. - the use of string methods such as uppercase() */ fun main() { print( "\n This is a GUESS-A-WORD game. \n\n" ) val word_to_be_guessed = "VIENNA" val guessed_characters = StringBuilder( "_________________________________________" ) // We'll shorten the StringBuilder string so that its length is equal // to the length of the word to be guessed. guessed_characters.setLength( word_to_be_guessed.length ) // Now guessed_characters refers to a StringBuilder that contains // a string that has as many underscore characters as the // word to be guessed. var game_is_over = false while ( game_is_over == false ) { print( " " + guessed_characters + " " + "Give a character or word: " ) var player_input = readLine()!!.uppercase() if ( player_input.length == 1 ) { for ( character_index in 0 .. word_to_be_guessed.length - 1 ) { if ( word_to_be_guessed[ character_index ] == player_input[ 0 ] ) { guessed_characters[ character_index ] = player_input[ 0 ] } } if ( guessed_characters.indexOf( "_" ) == -1 ) { // "_" is not a substring in guessed characters. // This means that all characters have been guessed. game_is_over = true print( " " + guessed_characters + " Congratulations! \n\n" ) } } else if ( player_input.length > 1 ) { // The player tried to guess the whole word. if ( player_input.equals( word_to_be_guessed ) ) { game_is_over = true print( "\n Congratulations! \n\n" ) } } else { game_is_over = true ; print( " \n Game over. \n\n" ) } } }