Hangman program with python - python

I need to make a hangman program with python program but i don't know how to continue.
in the program
i are given 6 chances, otherwise known as a “life line”, to guess the letters in the word. Every wrong guess will shorten the “life line”. The game will end when you guess the word correctly or you have used up all your “life line”. Here is the sample output:
['_', '_', '_', '_']
***Life Line***
-+-+-+-+-+-+
$|$|$|$|$|$|
-+-+-+-+-+-+
Enter your guess: a
['_', '_', '_', '_']
***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+
Incorrect Guess: ['a']
...................................
Enter your guess: b
['b', '_', '_', '_']
***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+
Incorrect Guess: ['a']
...................................
Enter your guess: l
['b', 'l', '_', '_']
***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+
Incorrect Guess: ['a']
...................................
Enter your guess: o
['b', 'l', '_', '_']
***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+
Incorrect Guess: ['a', 'o']
...................................
Enter your guess: u
['b', 'l', 'u', '_']
***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+
Incorrect Guess: ['a', 'o']
...................................
Enter your guess: e
['b', 'l', 'u', 'e']
***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+
Incorrect Guess: ['a', 'o']
...................................
You Got it Right! Well Done!
i have already typed in the first few codes but got stuck.
import random
wordList = ["Mary","Tian Pei","Pong"]
randname = random.choice ( wordList)
print randname
resultList = [ ]
for i in range(len(randname)):
resultList.append("_")
print resultList

Create the blank list:
>>> name = "Mary"
>>> blanks = ["_" for letter in name]
>>> blanks
['_', '_', '_', '_']
Create a list of incorrect guesses:
>>> incorrect_guesses = # you figure this one out
Set up your life-lines:
>>> life_lines = # you figure this one out
Prompt for a guess:
>>> guess = raw_input("Guess: ")
Guess: a
>>> guess
'a'
Save a variable which says whether or not the guess was incorrect:
>>> incorrect = # you figure this one out
Iterate over the name and replace the respective blank line in blanks with the letter if the respective letter in name is the same as the guess:
>>> for i in range(len(name)):
... if name[i] == guess:
... incorrect = # you figure this one out
... blanks[i] = # you figure this one out
...
>>> blanks
['_', 'a', '_', '_']
If incorrect is True, add the guess to the incorrect_guesses (in this case, since the guess was correct, it wouldn't update) and subtract a life-line:
>>> if incorrect:
... incorrect_guesses.append( # you figure this one out )
... life_lines -= # you figure this one out
...
To check for equivalence, join the letters in blanks to re-form the original word so that you can compare the two:
>>> final = ''.join(blanks) # this connects each letter with an empty string
>>> final
'_a__'
The general control structure could be the following:
choose random word
create blanks list
set up life-lines
while life_lines is greater than 0 and word not completed:
print blanks list
print life_lines graphic
if there are incorrect guesses:
print incorrect guesses
prompt for guess
check if correct and fill in blanks
if incorrect:
add to incorrect guesses and subtract a life-line
if word completed:
you win
else:
you lose
It's up to you to fill in the blanks I wrote here (and to write your own routines for printing the life-line graphics and such).

You can do something like this. See the comments in the code for explanations about the logic.
#!/usr/bin/env python
import random
wordList = ["Mary","Tian Pei","Pong"]
randname = random.choice ( wordList)
resultList = []
# When creating the resultList you will want the spaces already filled in
# You probably don't want the user to guess for spaces, only letters.
for letter in randname:
if letter == ' ':
resultList.append(' ')
else:
resultList.append("_")
# We are storing the number of lifeline 'chances' we have here
# and the letters that have already been guessed
lifeline = 6
guesses = []
# The game does not end until you win, on run out of guesses
while guesses != 0:
# This prints the 'scoreboard'
print resultList
print '***Life Line***'
print '-+' * lifeline
print '$|' * lifeline
print '-+' * lifeline
print 'Incorrect Guess: %s' % guesses
# If the win condition is met, then we break out of the while loop
# I placed it here so that you see the scoreboard once more before
# the game ends
if ''.join(resultList) == randname:
print 'You win!'
break
# raw_input because I'm using 2.7
g = raw_input("What letter do you want to guess?:")
# If the user has already guessed the letter incorrectly,
# we want to forgive them and skip this iteration
if g in guesses:
print 'You already guessed that!'
continue
# The lower port here is important, without it guesses are
# case sensitive, which seems wrong.
if g.lower() in [letter.lower() for letter in randname]:
# this goes over each letter in randname, then flips
# the appropriate postions in resultList
for pos, letter in enumerate(randname):
if g.lower() == letter.lower():
resultList[pos] = letter
# If the letter is not in randname, we reduce lifeline
# add the guess to guesses and move on
else:
lifeline -= 1
guesses.append(g)
Let me know if you need anything clarified.

import random
"""
Uncomment this section to use these instead of life-lines
HANGMAN_PICS = ['''
+---+
|
|
|
===''', '''
+---+
O |
|
|
===''', '''
+---+
O |
| |
|
===''', '''
+---+
O |
/| |
|
===''', '''
+---+
O |
/|\ |
|
===''', '''
+---+
O |
/|\ |
/ |
===''', '''
+---+
O |
/|\ |
/ \ |
===''']
"""
HANGMAN_PICS = ['''
-+-+-+-+-+-+
$|$|$|$|$|$|
-+-+-+-+-+-+ ''','''
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+ ''','''
-+-+-+-+
$|$|$|$|
-+-+-+-+ ''','''
-+-+-+
$|$|$|
-+-+-+ ''','''
-+-+
$|$|
-+-+ ''','''
-+
$|
-+ ''','''
-+
|
-+''']
words = '''ant baboon badger bat bear beaver camel kangaroo chicken panda giraffe
raccoon frog shark fish cat clam cobra crow deer dog donkey duck eagle ferret fox frog
goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot
pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork
swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'''.split()
# List of all the words
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1) # Random index
# Indexes in python start from 0, therefore len(wordList) - 1
return wordList[wordIndex] # Chooses a random word from the list which is a passed through the function
# Returns the random word
def displayBoard(missedLetters, correctLetters, secretWord):
print(HANGMAN_PICS[len(missedLetters)])
print()
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
# Displaying each letter of the string 'missedLetters'
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
# Checking for characters that match and replacing the blank with the character
for letter in blanks:
print(letter, end=' ')
print()
# Printing the blanks and correct guesses
def getGuess(alreadyGuessed):
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1: # more than 1 letters entered
print('Please enter a single letter.')
elif guess in alreadyGuessed: # letter already guessed
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz': # not a letter
print('Please enter a LETTER.')
else:
return guess
# Taking a guess as input and checking if it's valid
# The loop will keep reiterating till it reaches 'else'
def playAgain():
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
# Returns a boolean value
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words) # Calls the 'getRandomWord' function
gameIsDone = False
while True:
displayBoard(missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
# if any letter of the 'secretWord' is not in 'correctLetters', 'foundAllLetters' is made False
# If the program doesn't enter the if statement, it means all the letters of the 'secretWord' are in 'correctLetters'
if foundAllLetters: # if foundAllLetters = True
print('Yes! The secret word is "' + secretWord +
'"! You have won!')
# Printing the secret word
gameIsDone = True
else:
missedLetters = missedLetters + guess
if len(missedLetters) == len(HANGMAN_PICS) - 1:
displayBoard(missedLetters, correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' +
str(len(missedLetters)) + ' missed guesses and ' +
str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
# Prints the answer and the all guesses
gameIsDone = True
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
# Restarts Game
else:
break
# Program finishes

Related

Hangman written in python doesnt recognise correct letters guessed :/

So I'm working my first project which hangman written in python every works like the visuals and the incorrect letters. However, It is unable to recognise the correct letter guessed.
import random
from hangman_visual import lives_visual_dict
import string
# random word
with open('random.txt', 'r') as f:
All_Text = f.read()
words = list(map(str, All_Text.split()))
WORD2GUESS = random.choice(words).upper()
letters = len(WORD2GUESS)
print("_" * letters)
word_letters = set(WORD2GUESS)
alphabet = set(string.ascii_uppercase)
lives = 7
used_letters = set()
# user input side
while len(word_letters) > 0 and lives > 0:
# letters used
# ' '.join(['a', 'b', 'cd']) --> 'a b cd'
print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
user_letter = input('Guess a letter: ').upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in WORD2GUESS:
used_letters.remove(user_letter)
print('')
else:
lives = lives - 1 # takes away a life if wrong
print('\nYour letter,', user_letter, 'is not in the word.')
elif user_letter in used_letters:
print('\nYou have already used that letter. Guess another letter.')
else:
print('\nThat is not a valid letter.')
if lives == 0:
print(lives_visual_dict[lives])
print('You died, sorry. The word was', WORD2GUESS)
else:
print('YAY! You guessed the word', WORD2GUESS, '!!')
I've tried this, but it still wont recognise the correct guess.
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
Your error is this: When checking if the user_letter is in the WORD2GUESS, you falsely remove it from used_letters, but it has to stay in the set.
Also you are missing some way of escaping the while loop when fully guessing the word. That could be done at the same spot by checking if used_letters contain all the letters in WORD2GUESS.
Something like this:
import random
from hangman_visual import lives_visual_dict
import string
# random word
with open('random.txt', 'r') as f:
All_Text = f.read()
words = list(map(str, All_Text.split()))
WORD2GUESS = random.choice(words).upper()
letters = len(WORD2GUESS)
print("_" * letters)
word_letters = set(WORD2GUESS)
alphabet = set(string.ascii_uppercase)
lives = 7
used_letters = set()
# user input side
while len(word_letters) > 0 and lives > 0:
# letters used
# ' '.join(['a', 'b', 'cd']) --> 'a b cd'
print('You have', lives, 'lives left and you have used these letters: ', ' '.join(used_letters))
# what current word is (ie W - R D)
word_list = [letter if letter in used_letters else '-' for letter in WORD2GUESS]
print(lives_visual_dict[lives])
print('Current word: ', ' '.join(word_list))
user_letter = input('Guess a letter: ').upper()
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in WORD2GUESS:
print('\nThat is a correct letter.')
if set(WORD2GUESS).issubset(used_letters):
break
else:
lives = lives - 1 # takes away a life if wrong
print('\nYour letter,', user_letter, 'is not in the word.')
elif user_letter in used_letters:
print('\nYou have already used that letter. Guess another letter.')
else:
print('\nThat is not a valid letter.')
if lives == 0:
print(lives_visual_dict[lives])
print('You died, sorry. The word was', WORD2GUESS)
else:
print('YAY! You guessed the word', WORD2GUESS, '!!')

Hangman game duplicates and sorting python errors

I am trying to write an Hangman game in Python, which I almost figure it out for simple words but when there is a duplicate it mess up with the return indexing. Here is the code:
def hangman_game():
words = ["aback", "abaft", "abandoned", "abashed", "aberrant", "abhorrent", "abiding", "abject", "ablaze", "able",
"abnormal", "aboard", "aboriginal", "abortive", "abounding", "abrasive", "abrupt", "absent", "absorbed",
"absorbing", "abstracted", "absurd", "abundant", "abusive", "acceptable", "accessible", "accidental",
"accurate", "acid", "acidic", "acoustic", "acrid", "actually", "ad hoc", "adamant", "adaptable", "addicted",
"adhesive", "adjoining", "adorable", "adventurous", "afraid", "aggressive", "agonizing", "agreeable", "ahead",
"ajar", "alcoholic", "alert", "alike", "alive", "alleged", "alluring", "aloof", "amazing", "ambiguous",
"ambitious", "amuck", "amused", "amusing", "ancient", "angry", "animated", "annoyed", "annoying", "anxious",
word = random.choice(words)
print(f'Random word = {word} (backtesting)')
letter_set = []
word_set = []
for i in word:
word_set.append(i)
print(f'Letter remaining to be found ={word_set}')
while len(letter_set) < len(word_set):
for i in word:
letter = input("Guess a letter: ")
if letter in word_set:
letter_set.insert(word.index(letter)), letter) # issue here
word_set.remove(letter)
print(f'Word with letters removed: {word}')
print(f"Letter {letter} found at word index: {word.index(letter)}")
print(f'Letters found in word: {letter_set}')
print(f'Word set = {word_set}')
else:
print(f'Letter not found in word: {word}')
print(letter_set)
print("".join(map(str, letter_set)))
When it find duplicates in word, it removes the letter who is a duplicate from word_set but not from word. So when it finds a word like "letter" it will insert "e" always at index[1]. So it will print like "leettr". I found out that sometimes it mess up with the index even if there are no duplicates, usually on longer words, but couldn't really figure out why.
I was thinking to make it so letter_set have a i number of "_" depending on the word by default, and than replacing it using word_set.
Any advice on how to return letter always to the right index?
You can refactor the code a little bit. For example you can make a list hidden_word that will contain the same amount of # as letters in word. User will be guessing the letter and you will reveal the letter in hidden word untill there isn't anything left to reveal. For example:
def hangman_game():
word = "letter" # <-- chose a random word here instead of hardcoding it
hidden_word = list("#" * len(word))
while "#" in hidden_word:
print("STATUS")
print("------")
print(word)
print(hidden_word)
print("------")
letter = input("Guess a letter: ")
for idx, (w, h) in enumerate(zip(word, hidden_word)):
if w == letter and h == "#":
hidden_word[idx] = letter
print("Letter found!")
break
else:
print("Letter not found!")
hangman_game()
Prints:
STATUS
------
letter
['#', '#', '#', '#', '#', '#']
------
Guess a letter: e
Letter found!
STATUS
------
letter
['#', 'e', '#', '#', '#', '#']
------
Guess a letter: e
Letter found!
STATUS
------
letter
['#', 'e', '#', '#', 'e', '#']
------
Guess a letter: t
Letter found!
STATUS
------
letter
['#', 'e', 't', '#', 'e', '#']
------
Guess a letter: t
Letter found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', '#']
------
Guess a letter: r
Letter found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', 'r']
------
Guess a letter: x
Letter not found!
STATUS
------
letter
['#', 'e', 't', 't', 'e', 'r']
------
Guess a letter: l
Letter found!
I copy my code here in case someone will need something similar in the future. `
`
def hangman_game():
new_game = input("Press enter for new game")
word = random.choice(words)
print(f'Random word = {word} (testing)')
letter_set = list("_" * len(word))
lives = 3
while "_" in letter_set:
letter = input("Guess a letter: ").upper()
letter_count = word.count(letter)
if letter.isnumeric() or len(letter) > 1:
print("Insert valid character: a-z")
for index, (find_word, hidden) in enumerate(zip(word, letter_set)): # create new list with "_"*len(word)
if find_word == letter.lower() and hidden == "_": # check if letter is found in word, and if it is already revealed
letter_set[index] = letter # change "_" at the found indexes with letter
print(f'Letter found!')
if len(letter) > 1:
lives += 1
print(f"One letter at the time! ")
if letter.lower() not in word and letter.isnumeric() == False:
lives -= 1
print(f"Letter not found! Lives = {lives}")
if lives == 0:
print(f"YOU LOST! \n")
hangman_game()
if letter_count >= 1:
letter_set[index] = letter.upper()
print(f'Your word is: {" ".join(map(str, letter_set))}')
print("YOU WON \n")
hangman_game()
hangman_game() #wrong copied indentation

Loop breaks without executing the last print statement

I've written a hangman program in python. The program is finished, but I have a problem with my main function. If I set a win or loss, it no longer execute my print statements from before. This means that if I have to guess a word, for example, it doesn't fill in the last letter in the placeholder, it just breaks out the loop without filling in the last letter. The same goes with my hangman. If I don't have any more attempts left, it won't finish drawing my hangman (just leave out the last part). Who knows why that is? Please help
Here is my code:
##### HANGMAN IN PYTHON #####
count_attempts = 0
guess_word = []
def guidance():
print('Welcome to Hangman in Python!')
print('''The point here is to guess a word by trying out letter combinations and
defining them with ENTER.''')
print('''For each word, you have 10 tries! If you can not solve the word,
the game is over.''')
print('You have 9 attempts to guess the word.')
print('Have fun!')
print('')
def user_word():
userinput = str(input("Type in the word you want to be guessed: "))
for character in userinput:
if character.isdigit():
print('There is a number in your word!')
userinput = str(input('Please try again: '))
return userinput.upper()
def change(userinput):
global guess_word
list_WordToBeGuessed = list(userinput)
for characters in list_WordToBeGuessed:
guess_word.append(' _')
def play_game(userinput):
global count_attempts
length_word = len(userinput)
user_guessed = []
print('Word to guess: ', *guess_word)
print("")
list_WordToBeGuessed = list(userinput)
guess = str(input('Guess a letter: ')).upper()
for number in guess:
if number.isdigit():
guess = str(input('Input not valid. Guess a letter: ')).upper()
if guess in user_guessed:
print('You have already given this letter. ')
elif guess in list_WordToBeGuessed:
user_guessed.append(guess)
print("You've guessed a letter correctly!")
for i in range(0, length_word):
if list_WordToBeGuessed[i] == guess:
guess_word[i] = guess
else:
count_attempts += 1
user_guessed.append(guess)
print('Sry your given letter is not in the word!')
print("You have failed", count_attempts, "of 5 attempts")
def draw_hangman(count_attempts):
print('-------' )
print(' | ' + ('|' if count_attempts > 0 else ''))
print(' | ' + ('O' if count_attempts > 1 else ''))
print(' | ' + ('/ \\' if count_attempts > 2 else ''))
print(' | ' + ('|' if count_attempts > 3 else ''))
print('--- ' + ('/ \\' if count_attempts > 4 else ''))
print("")
def main():
guidance()
userinput = user_word()
change(userinput)
while True:
draw_hangman(count_attempts)
play_game(userinput)
if count_attempts >= 5:
print("You haven't any attempts left. Bad luck")
break
elif ' _' not in guess_word:
print("")
print('You won, congratulation!')
break
main()
you are breaking out of a loop before it can draw the hangman and word.
in the endgame conditions, you can simply call draw_hangman(count_atttempts) before each print statement and change(userinput) as well.
Edit:
You will have to redraw the word as well. Since this is built into your play_game() function it is difficult, but you can use
for i in guess_word:
guess = guess + i + " "
print(guess)
before the print statements along with the draw_hangman(count_attempts) change you made before. Please note you will need to create a new variable called guess in your main() function prior to adding this code.
Since you have a "break" in your endgame condition, the loop stops and last "draw_hangman(count_attempts)" is not called. You can simply add "draw_hangman(count_attempts)" before "print("You haven't any attempts left. Bad luck")"

Generating a New Random Word After a Condition is Met

I am trying to create a Lingo game in Python where the user has 2 minutes to guess as many correct 5 letter words as possible. I use the random class and a text file to generate a random 5 letter word. However, after the user correctly guesses the word, I do not know how to generate a new 5 letter word. I am thinking I generate it inside the while loop for the timer, but I am not sure. I am still learning about python and this is my first time writing a "game" program. Any ideas or suggestions?
import random
from collections import Counter
import time
file = "words.txt" #File with 5 letter words
f = open(file, 'r')
lines = f.readlines()
randomword = random.choice(lines) #generate random 5 letter word from file
numletters = Counter(randomword)
word = [randomword[0], '_', '_', '_', '_']#part of word that is being shown to user
score = 0 #user score
print(randomword[0])
#print(randomword)
timer = 120 #amount of time game runs for
start_time = time.time() #remember when game started
while(time.time() - start_time < timer): #2 minutes is given to guess as many 5 letter words as possible
for i in range(1,6): #take 5 guesses at what random word is
guess = input("Guess the word: ")
for j in range(1,5): #check to see if other 4 letters of random word match the letters in the user guess word
numguess = Counter(guess)
if(guess[j] == randomword[j] and word[j] == '_'): #replace empty character with letter of random word if correctly guessed
word[j] = randomword[j]
elif(guess[j] in randomword and word[j] == '_'): #replace empty character with uppercase letter of guessed letter if that letter is in the randomword
word[j] = guess[j].upper()
elif(guess[j] in randomword and numguess[guess[j]] > numletters[guess[j]] and word[j] == '_'): #guessed letter gets replaced with '_' if max number of that letter is already in word
word[j] = '_'
elif(guess[j] == randomword[j] and word[j] != '_'): #replace uppercase letter with correctly guessed letter in word
word[j] = randomword[j]
elif(guess[j] == randomword[j] and guess[j].upper() in word): #upper case letter is guessed in correct spot, but no other letters are correcty guessed
word[word.index(word[j].upper())] = '_'
else: #no correct letters are guessed
word[j] = '_'
answer = word[0] + ' ' + word[1] + ' ' + word[2] + ' ' + word[3] + ' ' + word[4]
print(answer)
if(answer == randomword[0] + ' ' + randomword[1] + ' ' + randomword[2] + ' ' + randomword[3] + ' ' + randomword[4]):
print("You are correct!")
score += 100 #user scores 100 points for each correctly guessed word
break
if(answer != randomword[0] + ' ' + randomword[1] + ' ' + randomword[2] + ' ' + randomword[3] + ' ' + randomword[4]):
print("You are incorrect! You get 0 points for this word")
print("The correct word is: " + randomword.strip())
print("Your final score is " + str(score)) #print final score
enter this code into python. it uses an if statement to re-create the same variable with random.randint
import random
condition = True #saying the condition is true
randomthing = random.randint(1,10) # selecting a random number
print(randomthing, "is the first digit") #printing out the first randomly generated digit
if condition == True:
randomthing = random.randint(1,10)# regenerating the number
print(randomthing, "is the second number. if it is the same re run it") # printing out the second generated number
let me know if i can do more help

Guess the Word Game: Guesses For Secret Word Aren't Being Accepted

I'm working in Python 3.x and am fairly new, so I hope what I am asking makes sense. I am supposed to be focusing on for loops and strings for this word-guessing game.
Here's the (jumbled/lengthy/cluttered) code I have so far:
import sys
import random
def Main():
PlayAgain = "y"
print("COP 1000 Project 4 - Courtney Kasonic - Guess the Word Game")
print("I'm thinking of a word; can you guess what it is?")
while PlayAgain == "y":
Words = "apple alphabet boomarang cat catharsis define decide elephant fish goat horizon igloo jackelope ketchup loop limousine monkey night octopus potato quick rebel separate test underway violin world yellow zebra".split()
SecretWord = random.choice(Words)
MissedLetters = ""
CorrectLetters = ""
ChosenWord = GetWord(Words)
Guess = FiveLetters(CorrectLetters+MissedLetters)
for Guess in ChosenWord:
CorrectLetters = CorrectLetters + Guess
ShowWord(CorrectLetters, ChosenWord)
for i in ChosenWord:
CLetters = ""
if Guess in ChosenWord:
Blanks = "_" * len(SecretWord)
for i in range(len(SecretWord)):
if SecretWord[i] in CLetters:
Blanks = Blanks[i] + SecretWord[i]
print(Blanks)
print(CLetters)
def GetWord(List):
SecretWord = random.choice(List)
return(SecretWord)
**def FiveLetters(LettersGuessed):
a = 2
if a > 1:
print("Enter five letters to check: ",end="")
Guess = input()
if len(Guess) != 5:
print("Please enter five letters.")
elif Guess in LettersGuessed:
print("You already guessed that letter.")
elif Guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please enter a letter.")
else:
return(Guess)**
def ShowWord(CLetters, SecretWord):
print("\nHere is the word showing the letters that you guessed:\n")
CLetters = ""
Blanks = "_" * len(SecretWord)
for i in range(len(SecretWord)):
if SecretWord[i] in CLetters:
Blanks = Blanks[i] + SecretWord[i]
print(Blanks)
print(CLetters)
return(Blanks, SecretWord, CLetters)
def CheckLetters(Letters):
Letters = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split()
for Letters in Word:
print(Letters)
return(Letters)
Main()
The bolded area is where I am having problems. Only five letters can be entered to "check" to see if they are in the secret word. It will only accept input like "abcde". It will not accept input like "aaaaa" or "muihi" i.e. it won't accept guesses that are not in order or have more than one of the same letter.
I am also having trouble with the underscores. Not sure if the code I have for it up there is correct or not. The letters that are guessed correctly will not replace the appropriate underscore.
Ex: Secret Word = dog. If I guess the letters "mopfe" (though I can't because of issue above) then it will print out "_ _ _" without the "o".
You will inevitably ask more questions, assuming you don't want to fail. If you ask those questions on StackOverflow you should probably read the FAQ. Since you are using python you should probably also read the style guide (i.e. PEP 8), it was mentioned in the comments. This code, while incomplete, will get you started.
import sys
import random
def main():
play_again = "y"
print("COP 1000 Project 4 - Courtney Kasonic - Guess the Word Game")
print("I'm thinking of a word; can you guess what it is?")
words = "apple alphabet boomarang cat catharsis define decide elephant fish goat horizon igloo jackelope ketchup loop limousine monkey night octopus potato quick rebel separate test underway violin world yellow zebra".split()
secret_word = random.choice(words)
correct_letters = ""
while play_again == "y":
guess = five_letters(correct_letters)
for letter in guess:
if letter in secret_word:
correct_letters += letter
show_word(correct_letters, secret_word)
def five_letters(letters_guessed):
guess = raw_input("Enter five letters to check: ")
if len(guess) != 5:
print("Please enter five letters.")
elif guess in letters_guessed:
print("You already guessed that letter.")
elif guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please enter a letter.")
else:
return guess
def show_word(correct_letters, secret_word):
print("\nHere is the word showing the letters that you guessed:\n")
word_display = ""
for index, letter in enumerate(secret_word):
if letter in correct_letters:
word_display += letter
else:
word_display += "_"
print word_display
if __name__ == "__main__":
main()

Categories

Resources