Skip to main content

The Driver Function

Now, after looking into important function let's take the number of inputs from the user for incorrect attempts and lets get started
def get_num_attempts():
    
    while True:
        num_attempts = input('How many incorrect attempts do you want? [1-5] ')
        try:
            num_attempts = int(num_attempts)
            if 1 <= num_attempts <= 5:
                return num_attempts
            else:
                print('{0} is not between 1 and 5'.format(num_attempts))
        except ValueError:
            print('{0} is not an integer between 1 and 5'.format(num_attempts))
As we can see we'll give user max number of 5 attempts and min. number of 1 attempt
After looking into all the function and learning every bit of information needed to create this game now its time to look into the main function which calls all the other function when required and does the game play smooth and systematic.
we'll look into code in parts for easy understanding..
lets, jump right into code:
def play_hangman():
   
"""Play a game of hangman."""
   
# Let player specify difficulty
   
print('Starting a game of Hangman...')
    attempts_remaining = get_num_attempts()
    min_word_length = get_min_word_length()

In the above code as we can see the main function is called as play_hangman() this will be called whenever we start the game, after starting first it will display "Starting a hangman of hangman". Then, it will ask the user for number of attempts he/she feel needed to successfully guess the word.
Then, it will ask the user for minimum word length he wants for the word and both of these will be done by respectively calling the get_num_attempts and get_min_word_length functions respectively.
# Randomly select a wordprint('Selecting a word...')
word = get_random_word(min_word_length)
print()

# Initialize game state variablesidxs = [letter not in ascii_lowercase for letter in word]
remaining_letters = set(ascii_lowercase)
wrong_letters = []
word_solved = False

 Now, a random letter will be selected from the database and the game variables will be initialised. 

while attempts_remaining > 0 and not word_solved:
    # Print current game state    print('Word: {0}'.format(get_display_word(word, idxs)))
    print('Attempts Remaining: {0}'.format(attempts_remaining))
    print('Previous Guesses: {0}'.format(' '.join(wrong_letters)))

    # Get player's next letter guess    next_letter = get_next_letter(remaining_letters)
This part of the code will show the player the current status of his game like his remaining attempts, his/her previous guesses and displays the word.

# Check if letter guess is in wordif next_letter in word:
    # Guessed correctly    print('{0} is in the word!'.format(next_letter))

    # Reveal matching letters    for i in range(len(word)):
        if word[i] == next_letter:
            idxs[i] = Trueelse:
    # Guessed incorrect    print('{0} is NOT in the word!'.format(next_letter))

    # Decrement num of attempts left and append guess to wrong guesses    attempts_remaining -= 1    hangman_graphic(attempts_remaining)
    wrong_letters.append(next_letter)

# Check if word is completely solvedif False not in idxs:
    word_solved = Trueprint()

In this piece of code the checking of user inputted word will be done. If correctly guessed within the number of attempts allowed then if other letters of a same word will be revealed and if incorrectly guesses then his one life will be taken away and again he's is asked  to guess the word...

# The game is over: reveal    print('The word is {0}'.format(word))

    #  Win or lose    if word_solved:
        print('Congratulations! You won!')
    else:
        print('Try again next time!')

    # Ask player if he wants to try again    try_again = input('Would you like to try again? [y/Y] ')
    return try_again.lower() == 'y'

if __name__ == '__main__':
    while play_hangman():
        print()


This, is the last part where you won or you lost will be declared!
if you win then "Congratulations! you won!" message will be displayed. if not then "Try again next time!" will be displayed . and then player will be asked to whether he wants to play again or not! if yes then the game will start again!

So! it's Done the coding part is done!
We'll see how the output part looks in the next blog, until then Stay tuned and stay safe.
                                                                                                    -Shreepad Sapate L-60















































































































Comments

Post a Comment

Popular posts from this blog

The output!

So here we arrive at the OUTPUT ! When you run the code in any Python IDE you will get results as follows: We are planning to put a video explaining each part of the source code in the next and final post for this blog. So, do visit again! Happy Learning!                                                             -Kartik Mehetre

Project Documentation

Course Project Title: HANGMAN GAME in Python Description: An interactive game of Hangman developed using python(an object programming language).The project consists of a number of functions used in the game by making use of inbuilt Python libraries.The game offers the user to choose number of attempts and also shows a graphical output. Link for project report: here Final Code File :  Python Code Topic 1: Hangman graphic function Presentor's info:  Name: Siddhesh Ramajgol Div: TY-L Roll no: 57 GR.no : 1710081 Video Link:   Hangman Graphic Function Topic 2: Get no.of attempts and word length Presentor's info:  Name:  Kartik Mehetre Div: TY-L Roll no: 47 GR.no :  1710382 Video Link:  No.of attempts and word length Topic 3: Get next letter and display words Presentor's info:  Name: Shreya Uttarwar Div: TY-L Roll no: 69 GR.no :  1710360 Video Link:  Get next letter and display ...

Getting started with coding

It's been while since we posted! So,let's continue our project. One of the essential data structures that we'll be using extensively is "SETS" in python. Just for the essence,here's a quick look at it: ******** CODE *********       my_list = [] my_set = set() my_list.append('a') my_set.add('a') print(my_list)  # Output: ['a'] print(my_set)  # Output: {'a'} my_list.append('b') my_set.add('b') print(my_list)  # Output: ['a', 'b'] print(my_set)  # Output: {'b', 'a'} my_list.append('a') my_set.add('a') print(my_list)  # Output: ['a', 'b', 'a'] print(my_set)  # Output: {'b', 'a'} ******** END ********** The reason behind using SETS over LISTS is elements in a set are unique and unordered. By using this data structure,we can build our vocabulary for the application. Learn more about SETS in python : https://...