Golang
Golang

 

 

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:

  1. Word selection: A random word is chosen from a predefined list using the math/rand package.
  2. Hidden word: The word is initially hidden with underscores, representing unguessed letters.
  3. Player input: The player is prompted to guess one letter at a time. Input is read using the bufio.Scanner.
  4. 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.
  5. 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

  1. Install Go from the official Go website.
  2. Copy the code into a file named hangman.go.
  3. Run the program using the command:
                    go run hangman.go
    
  4. Follow the instructions in the terminal to play the game.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)