How To Build A Classic Game using Python: A Friend Taught Me This - Hive Programmers

avatar

Greetings to my favorite Science community online, StemSocial.

It's @skyehi and I'm back with another very awesome blog on programming. Well sadly yesterday I couldn't share an episode because I was a bit under the weather and had a lot of friends come over to my place.

I'm excited to be back though but today's episode is not exactly going to be about building another awesome Android App.

Yesterday some friends came over to my place to visit me. I'm a programmer so I definitely have a lot of programmer friends.

One of my friends we call Buzz just like the space cartoon character Buzz Light-year taught me some cool programming tricks and even showed me the fastest way to create a game using Python.

Polish_20240108_143404383.pngOriginal Image Source by JohnsonMartin from Pixabay

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Now as programmers Python and perhaps C Programming are basic languages that we know but because of how much time I've spent working with Android Apps and blogging, I have become a little bit rusty with my Python coding.

Buzz said he hadn't given me a new year's gift yet despite the fact that the year is already old to me anyways, he wanted to teach me one very fast way to build a game using Python as my New Year's gift.

So he pulled out his laptop, Open Visual Studio software which is an IDE for Python programming just like how Android Studio is IDE for Android App development.

He taught me how to build a Hangman game where the user guesses the full word after being given a couple of letters and spaces in between.

If the user picks the right letters, the full word is completed and the user wins, but if the user picks the wrong letters, the word is spelled wrongly and the user would lose.

It was a pretty fun game though and I wanted to redo the game today and share it with my followers.

Of course we're still going to continue our series on Android App development tutorials for beginners but this is more like a bonus episode for anyone that is interested in starting out with Python.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Now if this blog gets great feedback, I might consider starting an entire series with Python that is if I'm even able to complete such a long series as Android App development.

So guys to go through with this particular tutorial, you'll need to properly install a great IDE for Python programming.

One of the best and highly recommended IDE is Visual Studio. It's got an easy to use interface and most of the work you need to do can be done using this particular software.

I'll share the complete code with you and then explain afterwards - so here's the code guys

import random

def choose_word():
    words = ["python", "hangman", "programming", "developer", "computer"]
    return random.choice(words)

def display_word(word, guessed_letters):
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += "_"
    return display

def hangman():
    max_attempts = 6
    guessed_letters = []
    word_to_guess = choose_word()

    print("Welcome to Hangman!")
    print(display_word(word_to_guess, guessed_letters))

    attempts = 0
    while "_" in display_word(word_to_guess, guessed_letters) and attempts < max_attempts:
        guess = input("Guess a letter: ").lower()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a valid single letter.")
            continue

        if guess in guessed_letters:
            print("You already guessed that letter. Try again.")
            continue

        guessed_letters.append(guess)

        if guess not in word_to_guess:


            attempts += 1
            print(f"Incorrect! Attempts remaining: {max_attempts - attempts}")
        else:
            print("Correct!")

        print(display_word(word_to_guess, guessed_letters))

    if "_" not in display_word(word_to_guess, guessed_letters):
        print("Congratulations! You guessed the word.")
    else:
        print(f"Sorry, you ran out of attempts. The word was: {word_to_guess}")

if __name__ == "__main__":
    hangman()

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

See guys, it's really that easy to do and to think of the fact that we created the entire program on just one page. If this was an episode of Android App Developer, this would be just our main activity page alone.

I wonder if you'd like for us to create the same game for Android studio though🤔. Would love to hear your thoughts on that in the comments.

So guys in the above code, we chose the words we would like to include in the game. The words were python, hangman, programming, developer and computer in an array.

We used the function return random.choice(words) so a random word in no padticular order or whatsoever will show to the user.

We designed the program to start by saying "Welcome to Hangman!" Using the function called print. That's how to display text to the screen in Python language.

We made the user have a maximum of 6 number of attempts using the code max_attempts = 6 .

We also created responses for when the user tries to put in a value that's not valid like perhaps putting in a number and not a letter or trying to guess with the same letter again.

This is necessary to make the game easier and in a way it's like handling errors too.

So when the user uses an invalid value as a guess we use this if clause to handle it; if len(guess) != 1 or not guess.isalpha(): print("Please enter a valid single letter.") continue

And also if the user attempts the same letter again as an input, we use this if clause to handle it; if guess in guessed_letters: print("You already guessed that letter. Try again.") continue

Now to determine whether the user has completed the guess word or not, we have to check if the number of empty dash spaces to fill is complete and the words are right.

This is the code we used;

if "_" not in display_word(word_to_guess, guessed_letters):
        print("Congratulations! You guessed the word.")

To check if it's wrong, well anything either than what's above is probably wrong so we use the else function.

Here's how it looked like;

else:
        print(f"Sorry, you ran out of attempts. The word was: {word_to_guess}")

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

So when you run the game, it will start by randomly choosing a word, and you can start guessing letters.

The game ends when you correctly guess the word or run out of attempts. You have 6 attempts though.

Congratulations guys, see how fast and easy it was to build your own game using Python?

Feel free to modify and expand the code to add more features or improve the user interface. You could also increase the number of attempts if you're feeling generous to your players or you could also include as many words as you wish to make thr game more interesting.

Thank you so much for taking the time to read today's blog. I hope you enjoyed Python Programming as much as you enjoy Android App Development.

Of course guys, I'm definitely going to continue my series tomorrow. This was like I said, a bonus episode taught to me by my friend. I hope to see you next time guys.

Have a Great Day and catch you next time on StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000