“We can only see a short distance ahead, but we can see plenty there that needs to be done..” – Alan Turing
This is a code made with Python, hangman. Hangman is a guessing game where two or more players are involved: One player writes a word, the other player(s) will consequently guess this. The guessing team have a maximum of eight wrong guesses before they are hung!
import random # Make player 1 input a word. word = input("Input your word and prepare to duel!\n") # Player 2's guessed word, the length of the variable word in underscores # For example, if player 1 said "hello", guessed_word is "_____". guessed_word = list(len(word) * "_") number_of_wrong_guesses = 0 maximum_wrong_guesses = 8 # List of phrases for guessing letters to add variety guess_letter_phrases = ["Guess a letter or you shall perish!", "Enquire a letter or burn!", "I'm gonna pressure you for a letter!"] # This checks the number of wrong guesses default and maximum guesses. while number_of_wrong_guesses < maximum_wrong_guesses: print("Your guess so far is %s." % "".join(guessed_word)) # Getting a letter from another player, get a random choice of phrase letter_guess = input("%s\n" % random.choice(guess_letter_phrases)) print("Only %d guesses remaining!" % (maximum_wrong_guesses - number_of_wrong_guesses)) # It verifies the user has only entered ONE letter, # else it repeats the loop. if len(letter_guess) != 1: print("Alrigh\' mate guess sensibly!\n") continue else: # Tracks whether a guess is correct/incorrect. correct_guess = False # Goes through the word, checking if letters == guessed letter. for letter_pos, letter in enumerate(word): if letter.upper() == letter_guess.upper(): correct_guess = True guessed_word[letter_pos] = letter # Adds to incorrect word total if guess is wrong. if correct_guess == False: number_of_wrong_guesses += 1 # Checks if they have correctly guessed the # word and therefore ends game if true. elif word == "".join(guessed_word): print("You are the winner, congratulations hero/heroine!\n") break # Checks if they have guessed too many times. if number_of_wrong_guesses >= maximum_wrong_guesses: print ("Sorry, you did not prevail this time...\n")
In addition you could add:
- A dictionary to verify the word exists.
- Sets to ensure a player does not enter a letter more than once.
- An option to also guess the word instead of individual letters.
(I may create a more advanced edition of this in the future)
In addition to myself, Daniel May (danielmayblog.wordpress.com) assisted me in the making and development of this game. Many thanks to you!
Code converted with hilite.me.