Introduction
Hangman is a classic word-guessing game where players try to figure out a hidden word by guessing one letter at a time. This implementation uses the Go programming language to build a simple, interactive command-line version of the game.
Objective
The objective of this program is to provide a fun and interactive experience while demonstrating fundamental programming concepts in Go, such as loops, conditional statements, and handling user input.
Code
package main import ( "bufio" "fmt" "math/rand" "os" "strings" "time" ) func main() { // List of words to choose from words := []string{"programming", "hangman", "golang", "developer", "education"} // Seed the random number generator rand.Seed(time.Now().UnixNano()) // Select a random word word := words[rand.Intn(len(words))] hiddenWord := strings.Repeat("_", len(word)) attempts := 6 guessedLetters := make(map[rune]bool) fmt.Println("Welcome to Hangman!") fmt.Printf("Guess the word: %s\n", hiddenWord) scanner := bufio.NewScanner(os.Stdin) for attempts > 0 { fmt.Printf("\nRemaining attempts: %d\n", attempts) fmt.Print("Enter a letter: ") if !scanner.Scan() { fmt.Println("Error reading input. Exiting.") return } guess := strings.ToLower(scanner.Text()) if len(guess) != 1 { fmt.Println("Please enter a single letter.") continue } letter := rune(guess[0]) if guessedLetters[letter] { fmt.Println("You already guessed that letter.") continue } guessedLetters[letter] = true if strings.ContainsRune(word, letter) { fmt.Println("Good guess!") hiddenWord = updateHiddenWord(word, hiddenWord, letter) if hiddenWord == word { fmt.Printf("Congratulations! You guessed the word: %s\n", word) return } } else { fmt.Println("Wrong guess!") attempts-- } fmt.Printf("Current word: %s\n", hiddenWord) } fmt.Printf("Game over! The word was: %s\n", word) } func updateHiddenWord(word, hiddenWord string, letter rune) string { result := []rune(hiddenWord) for i, ch := range word { if ch == letter { result[i] = letter } } return string(result) }
Explanation
This program works as follows:
- Word selection: A random word is chosen from a predefined list using the
math/rand
package. - Hidden word: The word is initially hidden with underscores, representing unguessed letters.
- Player input: The player is prompted to guess one letter at a time. Input is read using the
bufio.Scanner
. - Game logic: The program checks if the guessed letter is in the word. If correct, the hidden word is updated to reveal the guessed letter. If incorrect, the number of attempts decreases.
- Win or lose: The player wins by guessing the entire word before running out of attempts. If attempts reach zero, the game ends.
How to Run
- Install Go from the official Go website.
- Copy the code into a file named
hangman.go
. - Run the program using the command:
go run hangman.go
- Follow the instructions in the terminal to play the game.