For my Computing Science controlled assessment I have been asked to create a Hangman game with Python. However, in creating the game, there has been an error message that specifies something not in my code.
Traceback (most recent call last):
File "Z:\Documents\hangman.py", line 40, in <module>
generated_word = random.choice(random)
File "Q:\Pywpygam.001\Python3.2.3\lib\random.py", line 249, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'module' has no len()
I don't see anything wrong in the code and it doesn't specify what's wrong. Here is my code:
import time
print('Lets play hangman')
print("""
_______
| |
| O
| |
| \- -/
| |
| / \\
| / \\
____|____
\n""")
print("""
you get 7 lives to guess the letters in the word. if you guess
incorrectly more of the hangman will appear and you lose a life. when you have
used your 7 lives, the man will have hung and you will have lost. If you guess a
correct letter, it will be show and if you guess the word without using the 7
turns, you win!
\n""")
easy_words = ['string', 'loop', 'python', 'print', 'run']
medium_words = ['module', 'input', 'logic', 'output']
hard_words = ['graphics window', 'variable', 'iteration', 'modules']
random_words = ['string', 'loop', 'python', 'print', 'run', 'graphics window', 'variable', 'iteration', 'modules', 'module', 'input', 'logic', 'output ']
time.sleep(2)
print ("What level would you like to play at? Easy, Medium or Hard or Random?")
level_of_difficulty = input()
time.sleep(2)
print ("The program is now generating your word...")
if level_of_difficulty == 'Easy':
generated_word = random.choice(easy_words)
elif level_of_difficulty == 'Medium':
generated_word = random.choice(medium_words)
elif level_of_difficulty == 'Hard':
generated_word = random.choice(hard_words)
elif level_of_difficulty == 'Random':
generated_word = random.choice(random_words)
else:
generated_word = random.choice(random_words)
guessed = ''
lives = 7
while lives > 0:
missed = 0
print()
for letter in generated_word:
if letter in guessed:
print (letter,end=' ')
else:
print ('_',end=' ')
missed = missed + 1
if missed == 0:
print ('\n\nYou win!')
quit()
break
guess=input("please guess a letter:")
guessed = guessed + guess
if guess not in generated_word:
print ('\n that letter is not in this word, your lives have been decreased by 1.')
print ('please try another letter.')
lives = lives - 1
missed = missed + 1
print('your new lives value is')
print(lives)
if lives < 7:
print(''' _______
| | ''')
if lives < 6:
print(' | O ')
if lives < 5:
print(' | | ')
if lives < 4:
print(' | \- -/ ')
if lives < 3:
print(' | | ')
if lives < 2:
print(' | / \\ ')
if lives < 1:
print(' | / \\ ')
if lives == 0:
print('___|___ ')
print('GAME OVER! You have run out of lives and lost the game')
print('the secret word was')
print(generated_word)
quit()
What I am trying to do is make it so the generated word is displayed in the window with a _, and when the letter is guessed correctly, the appropriate _ is filled with the letter.
Any ideas will be appreciated!
I think these lines are wrong:
generated_word = random.choice(random)
You are passing the module "random" as parameter. I think you should pass the variable "random_words"?
I see what I did wrong, thanks for pointing out the
generated_word = random.choice(random)
bit, but I also saw that on the
while lives > 0:
missed = 0
print()
for letter in generated_word:
if letter in guessed:
I have made a spelling mistake.
Thanks everyone!
Related
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")"
I'm trying to create a hangman game with python. I know there is still a lot to complete but I'm trying to figure out the main component of the game which is how to compare the user inputted string (one letter) with the letters in one of the three randomly selected words.
import random
print("Welcome to hangman,guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
guess = input(str("Enter your guess:"))
guess_left = 10
guess_subtract = 1
if guess == "":
guess_left = guess_left - guess_subtract
print("you have" + guess_left + "guesses left")
I think you need a skeleton and then spend some time to improve the game.
import random
print "Welcome to hangman, guess the five letter word"
words = ["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
for trial in range(trials):
guess = str(raw_input("Enter character: "))
if (len(guess) > 1):
print "You are not allowed to enter more than one character at time"
continue
if guess in correct_word:
print "Well done! '" + guess + "' is in the list!"
else:
print "Sorry " + guess + " does not included..."
Your next step could be print out something like c_i__ as well as the number of trials left. Have fun :)
When you finish with the implementation, take some time and re-implement it using functions.
I've completed this project yesterday; (to anyone else reading this question) take inspiration if needed.
import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
#used to choose random word
random_lst=['addition','adequate','adjacent','adjusted','advanced','advisory','advocate','affected','aircraft','alliance','although','aluminum','analysis','announce','anything','anywhere','apparent','appendix','approach','approval','argument','artistic','assembly']
chosen_word = random.choice(random_lst)
#used to create display list + guess var
print("Welcome to hangman! ")
print("--------------------")
print("you have 6 lives." )
print(" ")
print (stages[-1])
display = []
for letters in chosen_word:
display += "_"
print(display)
print(" ")
#used to check if guess is equal to letter, and replace pos in display if yes.
lives = 6
game_over = False
#use the var guesses to store guesses and print at every guess to let player know what letters they tried already.
guesses = ""
while not game_over:
guess = input("Guess a letter. ")
print(" ")
guesses += (guess + " , ")
for pos in range(len(chosen_word)):
letter = chosen_word[pos
if letter == guess:]
display[pos] = letter
print("√")
print("- - -")
print(" ")
if display.count("_") == 0:
print("Game over. ")
game_over = True
elif guess not in chosen_word:
lives -= 1
print(f"Wrong letter. {lives} lives left. ")
print("- - - - - - - - - - - - - - - - - - -")
print(" ")
if lives == 0:
print (stages[0])
elif lives == 1:
print (stages[1])
elif lives == 2:
print (stages[2])
elif lives == 3:
print(stages[3])
elif lives == 4:
print(stages[4])
elif lives == 5:
print(stages[5])
elif lives == 6:
print(stages[6])
elif lives == 0:
game_over = True
print("Game over. ")
print(f"letters chosen: {guesses}")
print(" ")
print(display)
print(" ")
if lives == 0 or display.count("_") == 0:
break
if lives == 0:
print("Game over. You lose.")
elif lives > 0:
print("Congrats, you win! ")
What you can do is treat the string like an array/list.
So if you use loops:
x = ""#let's assume this is the users input
for i in range(len(y)): #y is the string your checking against
if x == y[i]:
from here what I'm thinking is that if they are equal it would add that letter to a string
Let's say the string is "Today was fun" then would have an array like this, [""."" and so on but you'd have to find a way to factor in spaces and apostrophes. So if the letter is == to that part of the string
#this is a continuation of the code, so under if
thearray[theposition] == the letter
But looking a your code your game is diffrent from the regular one so, also consider using a while look
gamewon = False
number of trials = 10
while gamewon == False and number of trials > 0:
#the whole checking process
if x == guess:
gamewon == True
print ........# this is if your doing word for word else use
the code above
else:
number of trials = number of trials - 1
I think that's it I know its a bit all over the place but you can always ask for help and I'll explain plus I was referring to your code things i thought you could fix
First you should accept both a and A by using guess = guess.lower(). The you have to search the string for the character guessed and find the positions.
guess = guess.lower()
# Find the position(s) of the character guessed
pos = [idx for idx,ch in enumerate(correct_word) if ch == guess]
if pos:
print('Letter Found')
guess_left -= 1
Another way to understand the for-loop is:
pos = []
for idx,ch in enumerate(correct_word):
if ch == guess:
pos.append(idx)
I tried to add graphics to my code for a hangman game. The graphics didn't appeared and when you guess a letter it automatically says that the game is over. I am not sure what is wrong as I am very new to python and coding.
import random
Graphics=['''
------------
| |''','''
------------
| |
| O''','''
------------
| |
| O
| / |''','''
------------
| |
| O
| / |
| | ''','''
------------
| |
| O
| / |
| |
| / |
|
| ''']
start = str(input("Welcome to Hangman!"))
failures = 0
allowed = 6
guesses_left = 6
guessed = str()
wordlist = ['kittens' , 'keen', 'right', 'square', 'baseball','soccer', 'square','house', 'safe', 'pizza', 'pasta', 'Loyola', 'cat', 'dog', 'rambler', 'Chicago', 'Pittsburgh']
def correct(guess):
if guess in word:
if guess not in guessed:
print("Correct")
return(True)
else:
if guess not in word and len(guess) == 1 and guess in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
if guess not in guessed:
print("Incorrect!")
return(False)
print("Guess this word!")
print("You can input any letter from A to Z and the space key.")
wordnumber = random.randint(0, len(wordlist))
word = (wordlist[wordnumber])
guessed_letters = len(word) * ['_']
print(' '.join(guessed_letters))
while failures < allowed:
guess = str(input("Guess a letter!"))
if len(guess) != 1 or guess not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
print("That is not a letter, try again.")
if guess in guessed:
print("You have already guessed that letter, try again.")
iscorrect = correct(guess)
guessed = guessed, guess
if iscorrect == True:
for position, letter in enumerate(word):
if letter == guess:
guessed_letters[position] = letter
print(' '.join(guessed_letters))
if iscorrect == False:
print("Wrong!")
failures = failures+1
guesses_left -= 1 # Number of guesses left
print("You have", guesses_left , "guesses left.")
if (guessed_letters == word):
print('''
You have successfully guessed the word!
''')
else:
print('''
You have lost the game!
''')
break
The reason the game exists is due to a break that is called at the end of the very first loop. The else should also be based on the condition that there are no guesses left:
if (guessed_letters == word):
print('''
You have successfully guessed the word!
''')
break
elif not guesses_left:
print('''
You have lost the game!
''')
break
Regarding the "graphics". This can be printed each time you get a wrong answer. And I recommend using if/else instead of two ifs here:
if iscorrect == True:
for position, letter in enumerate(word):
if letter == guess:
guessed_letters[position] = letter
print(' '.join(guessed_letters))
else:
print("Wrong!")
failures = failures+1
guesses_left -= 1 # Number of guesses left
print(Graphics[6-guesses_left])
print("You have", guesses_left , "guesses left.")
Graphics[6-guesses_left] means go look up the index in Graphics that is equal to the original number of guesses (6), minus the number of remaining guesses.
I am getting this error. Please help me explain the cause and the meaning of the error
Traceback (most recent call last):
File "E:\Python\bagels.py", line 61, in <module>
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
TypeError: object of type 'builtin_function_or_method' has no len()
I am doing lessons from invent with python and stuck on this lesson
https://inventwithpython.com/chapter11.html
here is my code
import random
def getSecretNum(numDigits):
numbers = list(range(10))
random.shuffle(numbers)
secretNum = ''
for i in range(numDigits):
secretNum += str(numbers[i])
return secretNum
def getClues(guess, secretNum):
if guess == secretNum:
return 'You got it!'
clue = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clue.append('fermi')
elif guess[i] in secretNum:
clue.append('Pico')
if len(clue) == 0:
return 'Bagels'
clue.sort()
return ' '.join(clue)
def isOnlyDigits(num):
if num == '':
return False
for i in num:
if i not in '0 1 2 3 4 5 6 7 8 9'.split():
return False
return True
def playAgain():
print('Do you want to play again?(yes or no)')
return input().lower().startswith('y')
NUMDIGITS = 3
MAXGUESS = 10
print('I am thinking of a %s-digit number. Try to guess what it is.' %(NUMDIGITS))
print('here are some clues:')
print('When I say: That means:')
print(' Pico One digit is correct but in the wrong position.')
print(' Fermi One digit is correct and in right position.')
print(' Bagels No digit is correct.')
while True:
secretNum = getSecretNum(NUMDIGITS)
print('I have thought of a number. You have %s guesses to guess it' %(MAXGUESS))
numGuesses = 1
while numGuesses <= MAXGUESS:
guess = ''
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
print('Guess #%s: ' % (numGuesses))
guess = input
clue = getClues(guess, secretNum)
print(clue)
numGuesses ++ 1
if guess == secretNum:
break
if numGuesses > MAXGUESS:
print('You ran out of guesses. The answer was %s. ' %(secretNum))
if not playAgain():
break
In the while loop you overwrite guess with the builtin function input.
You need to call the input function (please notice the extra pair of parentheses).
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
print('Guess #%s: ' % (numGuesses))
guess = input()
The problem is here:
guess = input
clue = getClues(guess, secretNum)
guess is now a reference to input, which is a python built-in function (like the error said).
You might want to do
guess = int(input("please enter guess"))
So I'm new to python and went trough a tutorial to write a hangman game in python 2.7 on my new pi. Well, anyway I liked the code and everything, and it ran fine but then I wanted to add something to make it ask ,"if you wanted to continue playing", and I did a lot of research and talked on some chat rooms about it and came up with/found this script to exit:
while keep_playing == False:
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
if not again:
break
raw_input ("\n\n\nPress enter to exit")
but I get this error:
Traceback (most recent call last):
File "/home/pi/Desktop/Scripts/scrappy/ls/ls/hangman3.py", line 40, in <module>
while keep_playing == False:
NameError: name 'keep_playing' is not defined
when its ran with this script
import random
import urllib
print 'time to play hangman'
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print letter,
else:
print '_',
missed += 1
print
if missed == 0:
print 'You win!'
break
guess = raw_input('guess a letter: ')
guesses += guess
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
while keep_playing == False:
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
if not again:
break
raw_input ("\n\n\nPress enter to exit")
Can anyone help me?
****edit*****
someone can close this tread using the tips provided i have solved my problem this is the final code
import random
import urllib
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
while True:
print 'time to play hangman'
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print letter,
else:
print '_',
missed += 1
print
if missed == 0:
print 'You win!'
break
guess = raw_input('guess a letter: ')
guesses += guess
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
break
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if not again:
raw_input ("\n\n\nPress enter to exit")
break
I'm not into python, but I can see you're indeed trying to compare an empty/undefined variable "keep_playing" to false. To my knowledge, you can't compare a variable to something, if you haven't declared the variable before the comparison, not sure if this is different in Python though.
What happens if you write this line along the other variables:
keep_playing = False
so you'll get :
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
keep_playing = False
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
keep_playing = False
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
keep_playing = False
This should do it