1#first i have to say, i didn't develope this all by myself. I tried, but with the "display_hangman" function i needed help.
2import random
3word_list = ["insert", "your", "words", "in", "this", "python", "list"]
4
5def get_word(word_list):
6 word = random.choice(word_list)
7 return word.upper()
8
9
10def play(word):
11 word_completion = "_" * len(word)
12 guessed = False
13 guessed_letters = []
14 guessed_words = []
15 tries = 6
16 print("Let's play Hangman")
17 print(display_hangman(tries))
18 print(word_completion)
19 print("\n")
20 while not guessed and tries > 0:
21 guess = input("guess a letter or word: ").upper()
22 if len(guess) == 1 and guess.isalpha():
23 if guess in guessed_letters:
24 print("you already tried", guess, "!")
25 elif guess not in word:
26 print(guess, "isn't in the word :(")
27 tries -= 1
28 guessed_letters.append(guess)
29 else:
30 print("Nice one,", guess, "is in the word!")
31 guessed_letters.append(guess)
32 word_as_list = list(word_completion)
33 indices = [i for i, letter in enumerate(word) if letter == guess]
34 for index in indices:
35 word_as_list[index] = guess
36 word_completion = "".join(word_as_list)
37 if "_" not in word_completion:
38 guessed = True
39 elif len(guess) == len(word) and guess.isalpha():
40 if guess in guessed_words:
41 print("You already tried ", guess, "!")
42 elif guess != word:
43 print(guess, " ist nicht das Wort :(")
44 tries -= 1
45 guessed_words.append(guess)
46 else:
47 guessed = True
48 word_completion = word
49 else:
50 print("invalid input")
51 print(display_hangman(tries))
52 print(word_completion)
53 print("\n")
54 if guessed:
55 print("Good Job, you guessed the word!")
56 else:
57 print("I'm sorry, but you ran out of tries. The word was " + word + ". Maybe next time!")
58
59
60
61
62def display_hangman(tries):
63 stages = [ """
64 --------
65 | |
66 | O
67 | \\|/
68 | |
69 | / \\
70 -
71 """,
72 """
73 --------
74 | |
75 | O
76 | \\|/
77 | |
78 | /
79 -
80 """,
81 """
82 --------
83 | |
84 | O
85 | \\|/
86 | |
87 |
88 -
89 """,
90 """
91 --------
92 | |
93 | O
94 | \\|
95 | |
96 |
97 -
98 """,
99 """
100 --------
101 | |
102 | O
103 | |
104 | |
105 |
106 -
107 """,
108 """
109 --------
110 | |
111 | O
112 |
113 |
114 |
115 -
116 """,
117 """
118 --------
119 | |
120 |
121 |
122 |
123 |
124 -
125 """
126 ]
127 return stages[tries]
128
129def main():
130 word = get_word(word_list)
131 play(word)
132 while input("Again? (Y/N) ").upper() == "Y":
133 word = get_word(word_list)
134 play(word)
135
136if __name__ == "__main__":
137 main()
1 1. import random
2 2. HANGMAN_PICS = ['''
3 3. +---+
4 4. |
5 5. |
6 6. |
7 7. ===''', '''
8 8. +---+
9 9. O |
10 10. |
11 11. |
12 12. ===''', '''
13 13. +---+
14 14. O |
15 15. | |
16 16. |
17 17. ===''', '''
18 18. +---+
19 19. O |
20 20. /| |
21 21. |
22 22. ===''', '''
23 23. +---+
24 24. O |
25 25. /|\ |
26 26. |
27 27. ===''', '''
28 28. +---+
29 29. O |
30 30. /|\ |
31 31. / |
32 32. ===''', '''
33 33. +---+
34 34. O |
35 35. /|\ |
36 36. / \ |
37 37. ===''']
38 38. words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar
39 coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk
40 lion lizard llama mole monkey moose mouse mule newt otter owl panda
41 parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep
42 skunk sloth snake spider stork swan tiger toad trout turkey turtle
43 weasel whale wolf wombat zebra'.split()
44 39.
45 40. def getRandomWord(wordList):
46 41. # This function returns a random string from the passed list of
47 strings.
48 42. wordIndex = random.randint(0, len(wordList) - 1)
49 43. return wordList[wordIndex]
50 44.
51 45. def displayBoard(missedLetters, correctLetters, secretWord):
52 46. print(HANGMAN_PICS[len(missedLetters)])
53 47. print()
54 48.
55 49. print('Missed letters:', end=' ')
56 50. for letter in missedLetters:
57 51. print(letter, end=' ')
58 52. print()
59 53.
60 54. blanks = '_' * len(secretWord)
61 55.
62 56. for i in range(len(secretWord)): # Replace blanks with correctly
63 guessed letters.
64 57. if secretWord[i] in correctLetters:
65 58. blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
66 59.
67 60. for letter in blanks: # Show the secret word with spaces in between
68 each letter.
69 61. print(letter, end=' ')
70 62. print()
71 63.
72 64. def getGuess(alreadyGuessed):
73 65. # Returns the letter the player entered. This function makes sure the
74 player entered a single letter and not something else.
75 66. while True:
76 67. print('Guess a letter.')
77 68. guess = input()
78 69. guess = guess.lower()
79 70. if len(guess) != 1:
80 71. print('Please enter a single letter.')
8172. elif guess in alreadyGuessed:
82 73. print('You have already guessed that letter. Choose again.')
83 74. elif guess not in 'abcdefghijklmnopqrstuvwxyz':
84 75. print('Please enter a LETTER.')
85 76. else:
86 77. return guess
87 78.
88 79. def playAgain():
89 80. # This function returns True if the player wants to play again;
90 otherwise, it returns False.
91 81. print('Do you want to play again? (yes or no)')
92 82. return input().lower().startswith('y')
93 83.
94 84.
95 85. print('H A N G M A N')
96 86. missedLetters = ''
97 87. correctLetters = ''
98 88. secretWord = getRandomWord(words)
99 89. gameIsDone = False
100 90.
101 91. while True:
102 92. displayBoard(missedLetters, correctLetters, secretWord)
103 93.
104 94. # Let the player enter a letter.
105 95. guess = getGuess(missedLetters + correctLetters)
106 96.
107 97. if guess in secretWord:
108 98. correctLetters = correctLetters + guess
109 99.
110100. # Check if the player has won.
111101. foundAllLetters = True
112102. for i in range(len(secretWord)):
113103. if secretWord[i] not in correctLetters:
114104. foundAllLetters = False
115105. break
116106. if foundAllLetters:
117107. print('Yes! The secret word is "' + secretWord +
118 '"! You have won!')
119108. gameIsDone = True
120109. else:
121110. missedLetters = missedLetters + guess
122111.
123112. # Check if player has guessed too many times and lost.
124113. if len(missedLetters) == len(HANGMAN_PICS) - 1:
125114. displayBoard(missedLetters, correctLetters, secretWord)
126115. print('You have run out of guesses!\nAfter ' +
127 str(len(missedLetters)) + ' missed guesses and ' +
128 str(len(correctLetters)) + ' correct guesses,
129 the word was "' + secretWord + '"')
130116. gameIsDone = True
131117.
132118. # Ask the player if they want to play again (but only if the game is
133 done).
134119. if gameIsDone:
135120. if playAgain():
136121. missedLetters = ''
137122. correctLetters = ''
138123. gameIsDone = False
139124. secretWord = getRandomWord(words)
140125. else:
141126. break
142
143
1# i know its very messy but it was my first try to make something with python ~regards vga
2import random
3
4words = ['tree', 'mango', 'coding', 'human', 'python', 'java',
5 'hangman', 'amazon', 'help', 'football', 'cricket', 'direction', 'dress', 'apology', 'driver', 'ship', 'pilot']
6guess = words[random.randint(0, len(words)-1)].upper()
7display = []
8for x in guess:
9 display.append("_")
10print("*** GAME STARTED ****")
11print("")
12print("Guess the word ! ", end=" ")
13indexes = []
14limbs = 6
15userWon = False
16userLost = False
17guessedLetters = []
18
19
20def start(word, indexes, display, limbs, userWon, userLost, guessedLetters):
21 chance = False # to stop recursion
22 wrong_guess = False
23 word_found = "" # change it to True or False based on word found in the word array
24 if userLost == False:
25 if len(indexes) > 0: # check on recursion if user entered any correct letter
26 for val in indexes:
27 # loop to change "_" with the correct letter in array
28 display[val] = word[val]
29 if len(guessedLetters) > 0:
30 # display how many limbs left
31 print("You have ", limbs, " chances left")
32 print("")
33 print("Wrong Guesses", guessedLetters)
34 print("")
35 for dash in display:
36 # print the display of "_" or the correct letter in the array
37 print(dash, end=" ")
38 print("")
39 print("")
40 user_guessed = input(
41 "Guess by entering a letter or the complete word to win!: ").upper()
42 if len(user_guessed) == 1: # if user entered only a letter
43 word_found = False
44 for i in range(len(word)): # to get the index of word array
45 if(word[i] == user_guessed): # match every single letter
46 if i in indexes: # if user already guessed correct letter
47 print("You already guessed the letter ", word[i])
48 chance = True
49 word_found = True
50 break
51 else:
52 indexes.append(i)
53 print("Nice guess it was ", word[i])
54 word_found = True
55 elif len(user_guessed) > 1: # if used tried to guess by a word
56 if(word == user_guessed):
57 print("Woah luck is on your side, You won !")
58 print("The correct word was ", word)
59 userWon = True
60 else:
61 wrong_guess = True
62 if user_guessed in guessedLetters: # if user guessed wrong again with the same word/letter
63 print("You already tried ", user_guessed)
64 chance = True
65 elif wrong_guess == True or word_found == False: # when user guessed wrong reduce limbs
66 guessedLetters.append(user_guessed)
67 print("Eh, Wrong guess")
68 limbs -= 1
69 if limbs == 0:
70 userLost = True
71 else: # when limbs are not 0 user can still play with chance = true
72 chance = True
73 if chance == True:
74 start(word, indexes, display, limbs,
75 userWon, userLost, guessedLetters)
76 chance = False # to stop recursion :X aryan
77 elif len(indexes) > 0 and userWon == False and userLost == False and chance == False:
78 if len(indexes) == len(word): # if user guessed all letters
79 print("Woah, You won ! :)")
80 print("The correct word was ", word)
81 else:
82 start(word, indexes, display, limbs,
83 userWon, userLost, guessedLetters)
84 elif userLost == True: # all limbs are 0 so user lost
85 print("You have ", limbs, " chances left")
86 print("Sorry, You lost :(")
87 print("The correct word was ", word)
88
89
90start(guess, indexes, display, limbs, userWon, userLost, guessedLetters)
91
1#This game has pre-specified input
2import time
3name = input("What is your name? ")
4print("Hello, " + name, "Time to play hangman!")
5print("")
6time.sleep(1)
7print("Start guessing...")
8time.sleep(0.5)
9word = "secret"
10guesses = ''
11turns = 10
12while turns > 0:
13 failed = 0
14 for char in word:
15 if char in guesses:
16 print(char)
17 else:
18 print("_")
19 failed += 1
20 if failed == 0:
21 print("You won")
22 break
23 print('')
24 guess = input("guess a character:")
25 guesses += guess
26 if guess not in word:
27 turns -= 1
28 print("Wrong")
29 print("You have", + turns, 'more guesses')
30 if turns == 0:
31 print("You Lose")
32