0% found this document useful (0 votes)
12 views6 pages

Python Hangman Game Development

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

Python Hangman Game Development

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Assignment-2

Name:Subiksha A R A

Sec:11

Roll no:60

Department:ECE

Objective and modules:

Develop a hangman game in Python that randomly generates a word and prompts
the user to guess one letter at a time, as shown in the sample run. Each letter in
the word is displayed as an asterisk. When the user makes a correct guess, the
actual letter is then displayed. When the user finishes a word, display the number
of misses and ask the user whether to continue playing. Create a list to store the
words, as follows:

# Use any words you wish

words = ["write", "that", "program", "rainbow", "computer", "science",


"programming",...]

The game should have the following functions:

a) Getting a random word from string of words # Returns a word


randomly

def pick_a_word():

b) Hiding the characters of chosen random word with * using

suitable iterative structure

c) Making a play function


# Returns win or lose of the game

def play():

d) Constraint: Fix the number of “turns” to be 15. If the guessing character


does not match the word then reduce the “turns” by -1. When turns reach 0, end
the game by displaying “You Loose”.

e) Also, use suitable flag variable to monitor the number of times a user fails
by guessing wrong character

Sample Run:

(Guess) Enter a letter in word *** > p

(Guess) Enter a letter in word p*** > r (Guess) Enter a letter in word prr* > p p is
already in the word

(Guess) Enter a letter in word pr*r* > o

(Guess) Enter a letter in word pro*r** > g (Guess) Enter a letter in word progr** >
n n is not in the word

(Guess) Enter a letter in word progr** > m

(Guess) Enter a letter in word progr*m > a

The word is "program".You missed 1 time

Do you want to guess another word? Enter y or n>


(i) Develop the user-defined functions for the modules designed in

(ii) Develop the application as a working model by invoking the functions.

(iii) Make use of conditional statements and looping constructs wherever


possible.

(iv) Make use of strings, lists or tuples to play the game.

Python Code:

import random

words = ["write", "that", "program", "rainbow", "computer", "science",


"programming"]

def pick_a_word():

return [Link](words)

def hide_word(word):

return '*' * len(word)

def play():

word = pick_a_word()

hidden_word = hide_word(word)

turns = 15

missed = 0

guessed_letters = []

while turns > 0 and hidden_word != word:


print("(Guess) Enter a letter in word", hidden_word, ">")

guess = input().lower()

if len(guess) != 1 or not [Link]():

print("Invalid input! Please enter a single letter.")

continue

if guess in guessed_letters:

print("You already guessed that letter! Try a different letter.")

continue

guessed_letters.append(guess)

if guess in word:

for i in range(len(word)):

if word[i] == guess:

hidden_word = hidden_word[:i] + guess + hidden_word[i+1:]

else:

missed += 1

turns -= 1

print(guess, "is not in the word.")

if turns == 0:

print("You lose! The word was", word)

else:

print("You win! The word was", word)

print("You missed", missed, "time(s).")


response = input("Do you want to guess another word? Enter y or n> ")

if [Link]() == 'y':

play()

play()

Output:

(Guess) Enter a letter in word ***** >

p is not in the word.

(Guess) Enter a letter in word ***** >

(Guess) Enter a letter in word *r*** >

You already guessed that letter! Try a different letter.

(Guess) Enter a letter in word *r*** >

m is not in the word.

(Guess) Enter a letter in word *r*** >

o is not in the word.

(Guess) Enter a letter in word *r*** >

u is not in the word.


(Guess) Enter a letter in word *r*** >

(Guess) Enter a letter in word *ri** >

(Guess) Enter a letter in word *ri*e >

n is not in the word.

(Guess) Enter a letter in word *ri*e >

(Guess) Enter a letter in word *rite >

You win! The word was write

You missed 5 time(s).

Do you want to guess another word? Enter y or n> n>

>

Common questions

Powered by AI

User input is checked to ensure it consists of a single alphabetic character. Invalid inputs prompt an error message and re-prompting. Additionally, previously guessed letters are tracked in a list to avoid repetition; attempts to re-guess letters also trigger a specific message and reprompting, ensuring that player actions adhere to game rules .

Conditional statements and loops are extensively used. A while loop iterates until the word is guessed or turns run out; inside, conditional checks determine if the entered letter is valid and if it is among guessed letters. For each incorrect guess, missed counts are incremented, and turns are decremented. Post-game, user input is queried to restart or exit, handled through another conditional check that invokes the play() function if replay is chosen .

The play function orchestrates the game's main loop, managing input from users, tracking guessed letters, and updating the obscured word as correct guesses are made. It checks for repetition in user guesses and adjusts the number of turns based on incorrect guesses. The function concludes by determining if the player has won (when all letters are guessed) or lost (when turns expire) and provides options for replay .

Loop constructs primarily facilitate repeated actions, such as continuous guessing until the game's win or lose conditions are met. The main while loop in the play function sustains the game activity, iteratively accepting user input and updating states based on guesses, thus efficiently managing turn-based gameplay dynamics .

Conditional statements direct program flow based on specific criteria, such as input validity, guessed letter correctness, and previously attempted letters. This enables logical branching essential for responding appropriately to user actions, providing real-time feedback, managing game state transitions (win/lose), and offering replay options .

Critical elements include functions for random word selection (pick_a_word()), obscuring the word with asterisks (hide_word()), and managing game flow with win/lose conditions (play()). The game employs looping constructs for multiple guesses, conditional statements for input validation and game results, as well as string manipulation for revealing correctly guessed letters. Use of data structures like lists is needed for word storage and tracking guessed letters .

Lists are used for efficient management and retrieval of data pertinent to the game. A predefined list stores all possible words for random selection, while another list tracks guessed letters to prevent redundant guesses. This structure supports dynamic interaction—allowing additions and existence checks—vital for smooth gameplay experience .

The game initially hides all the letters of the randomly chosen word using asterisks generated by multiplying the '*' character by the word's length. Correct guesses replace corresponding asterisks with the guessed letter, achieved by iterating over the word to find matches and update the obscured word. This approach ensures hidden and revealed letters are dynamically managed .

Upon game completion, the game evaluates if all letters were guessed (win) or turns exhausted (loss), providing respective messages. It then prompts for continuation based on player input. If the player opts for another round, the play function recursively invokes itself, effectively restarting the game loop while retaining previous function definitions and logic .

The game's balance is achieved through constraints such as limiting the number of turns to 15, which maintains tension. Feedback on incorrect or repeated guesses provides guidance without excessive penalty, while dynamic reveal of correct letters aids in user engagement and satisfaction, contributing to an approachable yet challenging experience .

You might also like