Automationscribe.com
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us
No Result
View All Result
Automation Scribe
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us
No Result
View All Result
Automationscribe.com
No Result
View All Result

Implementing the Hangman Sport in Python

admin by admin
August 28, 2025
in Artificial Intelligence
0
Implementing the Hangman Sport in Python
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


, Hangman was a very enjoyable recreation in our house. We’d seize a pen and paper and take turns selecting phrases for the opposite to guess. Right this moment, it’s utilized in classroom settings to assist children follow their spellings, perceive strategic choice making by selecting vowels first, and brainstorm doable phrases from hints.

On this article, we are going to undergo the Hangman Sport by implementing it in Python. This can be a beginner-friendly challenge the place we are going to be taught the fundamentals of the Python language, reminiscent of defining variables, generally used capabilities, loops, and conditional statements.

Understanding the Venture

First, we are going to perceive the sport and get into the depths of how our code ought to work.

In a typical 2-player Hangman Sport, Participant 1 chooses a phrase, hiding it from Participant 2, and generates blanks comparable to the variety of letters within the phrase he selected for guessing. Participant 2 has to guess the phrase by guessing one letter at a time. Participant 2 has an outlined variety of lives at first, and with every flawed guess of letters, they lose a life (to the purpose the place the person is hanged). With every proper guess, the lives stay the identical as earlier than. If Participant 2 loses all their lives with out guessing the phrase, the sport is over, and so they lose. In the event that they handle to guess the phrase, they win the sport. That is the define of the sport in its conventional sense.

On this challenge, the pc can be Participant 1, producing the phrase to guess, whereas we, the person, can be Participant 2. Allow us to implement the above utilizing a flowchart for higher comprehension.

Picture by Writer

Drawing a flowchart and defining every step helps in turning our thought course of into code, so its at all times a superb follow to attract one. Now allow us to begin with coding the issue!

Step 1: Checklist of Phrases and the Random Module

Step one on this challenge is for the pc to decide on a random phrase that the person should guess. For this objective, we are going to want each an inventory of phrases from which the pc picks one phrase to be guessed, and a Python operate known as random, which is able to randomly select that phrase from the given record.

To generate the record, I googled the 100 most typical nouns used within the English language and located a record. I used these phrases and created a Python record with it for use on this challenge.

Because the title suggests, a Python Checklist is a datatype that shops in itself a group of things. A listing of colours can be outlined in Python as colours = ["red", "yellow", "green", "blue", "pink"]. You’ll be able to try the Checklist syntax and extra data from the Python official web page on Checklist.

word_list = [
    "time",
    "year",
    "people",
    "way",
    "day",
    "man",
    "thing",
    ...
    ]

You’ll be able to entry the challenge information from my GitHub repository. hangman_words.py is the Python file that comprises the record of phrases from which the pc will randomly select a phrase for the sport.

Now, as soon as our record is created, we’d like the pc to decide on a random phrase from the given record of phrases word_list. Python has a module particularly for this objective known as “random”. We’ll import the module and use it to permit the pc to randomly select a phrase word_to_guess from the record words_list. You’ll be able to print the word_to_guess whereas coding the challenge to reinforce understanding, and remark it out when taking part in with the pc!

import random
word_to_guess = random.alternative(word_list)
print(word_to_guess)

For extra data on the random.alternative() operate, click on right here.

Step 2: Producing Blanks

The subsequent step is to generate blanks equal to the variety of letters within the word_to_guess in order that the person will get an thought of the variety of letters within the phrase he has to guess. For this, we are going to outline a variable known as blanks which is able to act as a container for the unguessed letters of the phrase. It should include the variety of “_” equal to the variety of letters within the word_to_guess.

To calculate the variety of letters within the word_to_guess that has been randomly picked by the pc from the words_list, we are going to use the Python operate len()that calculates the size of a string. Extra data on this in-built operate will be accessed by way of this hyperlink.

blanks = ""
word_length = len(word_to_guess)

As we now know the variety of letters in word_to_guess, we are going to use this quantity so as to add an equal variety of “_” within the variable blanks. For this objective, we are going to use the for loop, a Python performance that enables us to iterate over objects in a sequence, in our case, the string that’s saved within the variable word_to_guess. Click on right here to be taught extra about for loop and its syntax.

for i in vary(word_length):
    blanks = blanks + " _"
print("Phrase to guess: " + blanks)

The above block of code will iterate over the variety of letters within the word_to_guess string and generate a clean for every letter. It should print out as many _ because the variety of letters, every clean as a placeholder for the letter of the phrase to guess. So for the phrase “time”, the output printed on the display can be :

Phrase to guess: _ _ _ _

Step 3: Prompting the Person to Guess a Letter

Now the sport really begins! The pc has picked a phrase, generated clean placeholders for the letters in that phrase. Now comes the time for the person to start out guessing the phrase by guessing one letter at a time.

To ask the person for a letter, we are going to use the enter operate in Python and retailer it within the variable guess:

guess = enter("Guess a letter").decrease()

Click on right here to be taught extra in regards to the Python built-in operate enter().

Step 4: Verify if the Letter is within the Phrase

As soon as the person has guessed a letter, we are going to examine whether or not the person has guessed it proper and examine whether it is within the word_to_guess.

To do that, we are going to use a for loop. Furthermore, we will even create one other variable, your_word, which is able to replace with the guessed letters and an empty record known as,letters_guessed which is able to retailer the letters guessed accurately by the person (this can be helpful as we are going to see later).

So, for instance, if the pc has picked the phrase “cheesecake”, as the sport progresses and the person has guessed the letters “c”, “e”, and “a”, that is what each your_word and letters_guessed would appear to be:

your_word = c_ee_eca_e

letters_guessed = [“c”, “e”, “a”]

letters_guessed = []
your_word = ""

for letter in word_to_guess:
    if letter == guess:
        your_word  = your_word + letter
        letters_guessed.append(guess)
    elif letter in letters_guessed:
        your_word  = your_word + letter
    else:
        your_word = your_word + "_"

So principally what the above loop does is that it iterates by way of the word_to_guess one letter at a time, and checks:

  • If the letter guessed by the person guess is within the word_to_guess, the code will replace the variable your_word so as to add the letter guessed at its acceptable location. We have to perceive that in Python, strings are in truth a sequence of characters, and plenty of record capabilities are relevant to strings as nicely. Furthermore, we will even add this letter guessed accurately to the record letters_guessed.
  • If the letter that the person has guessed, guess, is within the letters_guessed, which implies the person has already instructed this letter earlier than, then we received’t want so as to add this to the letters_guessed, however simply have so as to add the letter within the your_word at its acceptable location.
  • Else, if the letter guessed by the person isn’t within the word_to_guess, and subsequently won’t be within the letters_guessed, we are going to easy generate blanks in locations.

If the code above appears a bit overwhelming, be at liberty to only run the above for loop whereas defining the variables and printing every of the variables: word_to_guess, guess, guessed_letters, and your_word and printing the variables the place they’re modified.

Picture by AltumCode on Unsplash

Step 5: Creating the Whereas Loop that runs till the Sport is Over

Allow us to refer again to the flowchart we created to assist us perceive the challenge. With the intention to code this challenge, we’d like to bear in mind the next factors:

  • The person has an outlined variety of lives at first
  • For every letter guessed flawed, the lives are decreased by 1
    • If the person runs out of lives, the person loses and the sport is over
    • If the person has lives left, the pc will ask the person to guess one other letter
  • For every letter guessed proper, the lives stay unchanged, and a clean is changed by a letter within the placeholder blanks
    • If the variable your_word is all stuffed, the person wins the sport, and the sport is over
    • If the variable your_word has clean areas left, then the pc will once more ask the person to guess the subsequent letter

Since we’ve got created the for loop beforehand that caters to the guessed letter, now could be the time to include the concept of lives, and scale back it when the person has guessed a letter flawed.

Allow us to outline the variety of lives for the person with the variable number_of_lives. The person has 6 possibilities to counsel the flawed letter in guessing the phrase.

number_of_lives = 6

Now, contemplating the factors talked about above, we additionally want a variable or a situation that tells us to cease asking the person to guess when the sport is over. Allow us to code it with the assistance of a Boolean variable.

Merely stating, a Boolean is a datatype in Python that shops both True or False. We’ll use this Boolean variable to proceed the sport whereas it’s False and vice versa. Initially, whereas the sport begins, this variable can be False, that means the sport isn’t over.

game_over = False

Now we are going to introduce a whereas loop with the situation that it’s going to run so long as the sport isn’t over, and we are going to embrace the circumstances talked about above on this whereas loop. Try extra in regards to the whereas loop from the Python official documentation right here.

whereas not recreation over:
     print("nYou have ", number_of_lives, " lives remaining!")
     guess = enter("Guess a letter: ").decrease()

     your_word = ""

     for letter in word_to_guess:
        if letter == guess:
            your_word  = your_word + letter
            letters_guessed.append(guess)
        elif letter in letters_guessed:
            your_word  = your_word + letter
        else:
            your_word = your_word + "_"
     print("Phrase to guess: ", your_word)

Within the above piece of code, we’ve got added the enter assertion in addition to the print assertion, which is able to output the letters guessed to date based on their place within the word_to_guess.

Step 6: Dealing with Conditions

The final step is to deal with completely different circumstances. What occurs if the letter the person has guessed has already been instructed by the person, or the letter isn’t within the phrase? Additionally, what if all of the letters have been guessed and there aren’t any extra blanks in your_word? This might imply that the person has guessed the phrase and thus received.

We’ll add this example within the code with he following strains:

if guess in letters_guessed:
    print(f"nYou've already guessed {guess}")

if "_" not in your_word:
    game_over = True
    print("nYou have guessed the phrase! YOU WIN!")
Picture by Giorgio Trovato on Unsplash

Furthermore, if the letter guessed by the person isn’t within the word_to_guess, the person’s guess is inaccurate, then their lives can be decreased by 1, and we are going to inform the person that their guessed letter isn’t within the phrase. If lowering the lives by a flawed guess finishes all of the person’s lives, then our boolean variable game_over can be set as True , and the sport will finish, with the person shedding the sport.

if guess not in word_to_guess:
    number_of_lives -= 1
    print(f"nYou guessed {guess}, that is not within the phrase. You lose a life.")

    if number_of_lives == 0:
        game_over = True
        print(f"nIT WAS {word_to_guess}! YOU LOSE!")

Bear in mind so as to add the above blocks of code contained in the whereas loop that runs till the sport isn’t over. A whole code together with beneficial feedback will be accessed by way of this GitHub repository for a greater understanding.

Conclusion

The above coding challenge was accomplished with the fundamentals of the Python language. We got here throughout some built-in capabilities, like print(), and enter(), we used the random module to generate random phrases to guess and used for and whereas loops in varied iterations based on want. We additionally went by way of the conditional if, elif and else statements. These are all the essential instruments that each newbie should know earlier than they bounce into complicated coding. We might even have outlined and known as capabilities on this program, however this was meant to be a beginner-friendly introduction to the Python language. If you’re a professional in Python, be at liberty to share varied different methods we might have approached this challenge!

Tags: gameHangmanImplementingPython
Previous Post

How Infosys Topaz leverages Amazon Bedrock to rework technical assist desk operations

Next Post

Meet Boti: The AI assistant remodeling how the residents of Buenos Aires entry authorities data with Amazon Bedrock

Next Post
Meet Boti: The AI assistant remodeling how the residents of Buenos Aires entry authorities data with Amazon Bedrock

Meet Boti: The AI assistant remodeling how the residents of Buenos Aires entry authorities data with Amazon Bedrock

Leave a Reply Cancel reply

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

Popular News

  • How Aviva constructed a scalable, safe, and dependable MLOps platform utilizing Amazon SageMaker

    How Aviva constructed a scalable, safe, and dependable MLOps platform utilizing Amazon SageMaker

    402 shares
    Share 161 Tweet 101
  • Unlocking Japanese LLMs with AWS Trainium: Innovators Showcase from the AWS LLM Growth Assist Program

    401 shares
    Share 160 Tweet 100
  • Diffusion Mannequin from Scratch in Pytorch | by Nicholas DiSalvo | Jul, 2024

    401 shares
    Share 160 Tweet 100
  • Streamlit fairly styled dataframes half 1: utilizing the pandas Styler

    401 shares
    Share 160 Tweet 100
  • Proton launches ‘Privacy-First’ AI Email Assistant to Compete with Google and Microsoft

    401 shares
    Share 160 Tweet 100

About Us

Automation Scribe is your go-to site for easy-to-understand Artificial Intelligence (AI) articles. Discover insights on AI tools, AI Scribe, and more. Stay updated with the latest advancements in AI technology. Dive into the world of automation with simplified explanations and informative content. Visit us today!

Category

  • AI Scribe
  • AI Tools
  • Artificial Intelligence

Recent Posts

  • Meet Boti: The AI assistant remodeling how the residents of Buenos Aires entry authorities data with Amazon Bedrock
  • Implementing the Hangman Sport in Python
  • How Infosys Topaz leverages Amazon Bedrock to rework technical assist desk operations
  • Home
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms & Conditions

© 2024 automationscribe.com. All rights reserved.

No Result
View All Result
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us

© 2024 automationscribe.com. All rights reserved.