I need a simple Python Hangman program without using Lists - It is just one word
HAPPY - this program works - BUT...
This is what I did, with Lists - but teacher said Lists are not allowed
We do not have to draw hangman - we just prompt for the letters - print the "-" for each letter to show length of word.
def main():
secretword = "HAPPY"
displayword=[]
displayword.extend(secretword)
for I in range (len(displayword)):
displayword[I]="_"
print ('current word
')
print (' '.join(displayword))
count = 0
while count < len(secretword):
guess = input('Please guess a etter: ')
for I in range(len(secretword)):
if secretword[I] == guess:
displayword[I] = guess
countr - count + 1
print (' '.join(displayword))
print (congratulations you guess the word')
main()
If you don't like the code - that's fine. This is how our teacher is requiring us to do this. I can see it is not like others do it. I only left out the comments - that are also required on every line of code
One solution to your problem would be to use two strings, secretword, which is the word you're looking for and displayword which is what the user sees so far, the combination of letters and -. Every time you enter a letter, the program checks if the secretword contains that letter and if it does, it updates the character of the specific index in displayword:
def main():
secretword = "HAPPY"
length = len(secretword)
displayword = '-' * length
count = 0
while count < length:
guess = input("Please guess a letter: ")
for i in range(length):
if secretword[i] == guess:
displayword[i] = guess
count += 1
print(displayword)
print("Congratulations, you guessed the word.")
main()
I'm trying to create a little game.
The rules are very straightforward: you give an English word, and the computer will try to guess this word letter by letter.
The thing is, I'm trying to make the computer guess the letters in a smart way. Let me give you a simple example of what I'm trying to build so you can understand:
You give the word "cat" to the computer to guess.
The 130K words list I have is narrowed to only the words who have 3 characters, which makes up to 805 words only. And from this list of words, an alphabet is created, containing only 25 letters (not the whole 26) because the new 805 words list contains all the letters of the alphabet but the "z". So we now have a list containing 25 (different) letters.
-- As I can't upload anything here on SO, we will say for this example that the massive 130K words list is a 10 words list (variable name "fullDice") --
If you try to run my code, pick a word from inside this list or else
it's not going to work
The computer now guesses a random letter from this 25 letters list.
If the letter is not in the word, he doesn't do anything and re-guess a letter from the list.
But if the letter is in the word, that's where things become more complicated. Let's say the computer guess the letter "c". I want the computer to re-narrow the possible words list, to only those having a "c" in the first character. That way, the 805-words list become now an only 36 words list. Because there are only 36 words who are 3 characters and starts with a "c", a new alphabet is created. And the new alphabet is now made of only 14 letters, making it easier for the computer to guess the next letter and be correct about it. And so on until he finds all the letters.
I'm stuck on part 5. If you try to run my code just below, you'll see that the dictionnary list is never narrowed. That's my problem.
import time
from random import randint
fullDice = ["panda", "tiger", "cat", "elephant", "whale", "leopard", "gorilla", "fish", "snake", "eagle"]
askForWord = input("Please enter an english word: ")
while True:
updatedDice = []
for k in range (0, len(fullDice)):
if len(askForWord) == len(fullDice[k]):
updatedDice += [fullDice[k]]
alphabet = []
for i in range (0, len(updatedDice)):
for n in range (0, len(updatedDice[i])):
if updatedDice[i][n] not in alphabet:
alphabet += [updatedDice[i][n]]
guessRandomLetter = alphabet[randint(0, len(alphabet) - 1)]
print("I guess the letter: " + guessRandomLetter)
print("From this dice: " + str(len(updatedDice)))
print("From this amount of letters: " + str(len(alphabet)) + "\n")
time.sleep(0.75)
guessedWordUnderlined = "_" * len(askForWord)
if guessRandomLetter in askForWord:
for m in range(0, len(askForWord)):
if askForWord[m] == guessRandomLetter: # CHECKING IF THE GUESSED LETTER IS INSIDE THE WORD
guessedWordUnderlined = list(guessedWordUnderlined)
guessedWordUnderlined[m] = guessRandomLetter
guessedWordUnderlined = ''.join(map(str, guessedWordUnderlined))
if guessedWordUnderlined == askForWord: # CHECK IF USER HAS WON
print("YOU WON")
break
you just asked a qs including that code.
i tryed to make it work only with the available words in the dictionnary you gave as "python".
from random import randint
import random
import time
import datetime
random.seed(datetime.datetime.now())
wordOfTheUser = input("ENTER ENGLISH WORD HERE: ")
if wordOfTheUser in ("abracadabra", "python", "coding", "soup", "paper", "list", "leader", "program", "software", "eating","abcdefghigklmnopqrstuvwxyz"):
pass
else:
print("your word is not on the list, still devlopping.")
raise
diceList1 = ["abracadabra", "python", "coding", "soup", "paper", "list", "leader", "program", "software", "eating","abcdefghigklmnopqrstuvwxyz"]
diceList2 = []
for k in range (0, len(diceList1) - 1):
if len(diceList1[k]) == len(wordOfTheUser):
diceList2 += [diceList1[k]]
makeAlphabet = []
for b in range (0, len(diceList2)):
for x in range (0, len(diceList2[b])):
if diceList2[b][x] not in makeAlphabet:
makeAlphabet += [diceList2[b][x]]
computerWordSize = "_" * int(len(wordOfTheUser))
a= len(makeAlphabet)
while True:
try:
randomIndex = randint(0, a)
except ValueError:
randomIndex = randint(0, a)
pass
try:
letterChosenRandomly = makeAlphabet[randomIndex]
except IndexError as e:
try:
randomIndex = randint(0, int(len(makeAlphabet)))
letterChosenRandomly = makeAlphabet[randomIndex]
except:
pass
print("I guess the letter -> " + letterChosenRandomly)
diceList3 = []
if letterChosenRandomly in wordOfTheUser:
print("\n=== WON ===> " + letterChosenRandomly)
print("=== ALPHABET ===> " + str(len(makeAlphabet)))
print("=== HDW1 ===> " + str(len(diceList1)))
print("=== hdw2 ===> " + str(len(diceList2)))
print("=== hdw3 ===> " + str(len(diceList3)) + "\n\n")
k=-1
makeAlphabet = []
for i in range (0, len(wordOfTheUser) ):
if letterChosenRandomly == wordOfTheUser[i]:
computerWordSize = list(computerWordSize)
computerWordSize[i] = letterChosenRandomly
for l in range (0, len(diceList2)):
if computerWordSize[i] == diceList2[l][i]:
diceList3 += [diceList2[l]]
for d in range(0, len(diceList3)):
for h in range(0, len(diceList2[b])):
if diceList2[d][h] not in makeAlphabet:
makeAlphabet += [diceList2[d][h]]
won = False
computerWordSize = ''.join(map(str, computerWordSize))
print(computerWordSize)
if computerWordSize == wordOfTheUser:
won = True
if won is True:
print("YOU WON")
break
time.sleep(1)
else:
print("\n=== LOOSE ===> " + letterChosenRandomly)
print("=== ALPHABET ===> " + str(len(makeAlphabet)))
print("=== HDW1 ===> " + str(len(diceList1)))
print("== hdw2 ===> " + str(len(diceList2)))
print("=== hdw3 ===> " + str(len(diceList3)) + "\n\n")
try:
makeAlphabet.remove(letterChosenRandomly)
except:
print ("Letters not in list")
break
k=0
diceList3 = []
for q in range (0, len(wordOfTheUser) - 1):
for l in range(0, len(diceList2)):
if computerWordSize[q] == diceList2[l][q]:
diceList3 += [diceList2[l]]
for d in range(0, len(diceList3)):
for h in range(0, len(diceList2[b])):
try:
if diceList2[d][h] not in makeAlphabet:
makeAlphabet += [diceList2[d][h]]
except:
try:
for s in range(0, len(diceList3)):
for f in range(0, len(diceList2)):
if diceList2[s][f] not in makeAlphabet:
makeAlphabet += [diceList2[s][f]]
except:
("your word is too short")
time.sleep(1)
I believe the problem is that if guessedWordUnderlined in askForWord will never be true. The in operator tests whether the first operator is within the second argument, which is a container, such as a list or string. "_" * len(askForWord), the value of guessedWordUnderlined, is a string of underscores, and you are testing whether or not that is in askForWOrd. If the vale of askForWord is cat, askForWord can be thought of as ["c", "a", "t"], so the in operator will be testing "___" == "c" or "___" == "a" or "___" == "t", none of which will be true. This means that the code beneath it will never execute, so the code just repeats forever, randomly guessing letters within the word. I cannot really tell what the function of this if is, as you already know each letter you could have chosen is in askForWord, though I'm sure I'm missing something obvious.
As an aside, you frequently use a construction similar to for x in range(0, len(LIST): ... LIST[x], which can be more concisely and obviously written as for x in LIST: ... x. For example, your code
for k in range (0, len(fullDice)):
if len(askForWord) == len(fullDice[k]):
updatedDice += [fullDice[k]]
alphabet = []
could be written as
for k in fullDice:
if len(askForWord) == len(k):
updatedDice += [k] # This should be updatedDice.append(k), but I
# have left it as-is for simplicity's sake.
alphabet = []
which should help your code become more readable. There are a few other edits that could be made to make your code more pythonic, but aside from that line I cannot see anything functionally wrong with it. If you share what this if is supposed to help, it might make it a bit easier to find any other errors in your code. I hope this helps, and good luck!
Having reviewed your code again, I believe the problem is in the statement guessedWordUnderlined = "_" * len(askForWord). This creates a string of underscores whose length is equal to that of askFOrWord. The problem is that each at each iteration of the while True: loop, a new string. This means that at each iteration, the string becomes a list of underscores with one correct letter, but in the next iteration it is overridden. To fix this, you should move the line guessedWordUnderlined = "_" * len(askForWord) from its current location to directly below askForWord = input("Please enter an english word: "). This will mean that it is present in the global scope rather than the local scope, meaning it won't get overwritten. You should also put the line global guessedWordUnderlined at the beginning of the while loop, if I'm not mistaken. This may require you to rework some code. Hope this works for you!
I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.
Here is my code
import random
'''
HANGMAN IMAGE
print(" _________ ")
print("| | ")
print("| 0 ")
print("| /|\\ ")
print("| / \\ ")
print("| ")
print("| ")
'''
def game():
print('''Welcome to hangman, you must guess letters to fill in the word.
Incorrect guesses will use up a turn, you have 7 turns before you lose.''')
lines = open("wordBank.txt").read()
line = lines[0:]
words = line.split()
myword = random.choice(words).lower()
letters = len(myword)
print("Your word has " + str(letters) + " letters.")
underscores = ""
for x in range(0, letters):
underscores += "_ "
print(underscores)
print(myword)
l = set(myword)
turn = 0
guesses = []
def guess():
thisGuess = input("Type a letter and press Enter(Return) to guess: ")
if thisGuess.lower() in l:
else:
print("Boo")
guess()
game()
You probably need to reword your question as it's not clear what you are asking. But you should look into string splicing. If they guessed the letter "a" and it goes in the third slot then you could do something like
underscores[:2] + 'a' + underscores[3:]
adapt for your code but that would replace the 3rd underscore with an "a".
UPDATE:
don't use a set, look up the index as you go. Try something like this
for index, letter in enumerate(my_word):
if letter == guessed_letter:
if not index == len(my_word) -1
underscores = underscores[:index] + letter + underscores[index+1:]
else:
underscores = undescores[:-1] + letter
Another possible approach (in Python 2.7, see below for 3):
trueword = "shipping"
guesses = ""
def progress():
for i in range(len(trueword)):
if trueword[i] in guesses:
print trueword[i],
else:
print "-",
print ""
This works by checking for each letter if it's been guessed in guesses, and printing that letter. If it hasn't been guessed, it prints -. When you put a comma at the end of a print (as in print "-",) it won't automatically print a newline, so you can continue printing on the same line. print "" prints a null string with a newline, finishing the line.
Then guessing becomes:
guesses += guess
Output is:
guesses = ''
- - - - - - - -
guesses = 'sip'
s - i p p i - -
In Python 3:
trueword = "shipping"
guesses = ""
def progress():
for i in range(len(trueword)):
if trueword[i] in guesses:
print(trueword[i], end='')
else:
print("-", end='')
print('')
you add the end='' parameter to remove the newline, instead of the comma. If you want the spaces between them, you can add sep=' ' as well to specify the separator.
Also, because list comprehensions are awesome (and this works in 2.7 & 3):
def progress():
ans = [word[x] if word[x] in guesses else '-' for x in range(len(word))]
print(' '.join(ans))
Does the same thing via list comprehensions... which are a very strong feature in python.
My Objective:
In a game of Lingo, there is a hidden word, five characters long. The
object of the game is to find this word by guessing, and in return
receive two kinds of clues: 1) the characters that are fully correct,
with respect to identity as well as to position, and 2) the characters
that are indeed present in the word, but which are placed in the wrong
position. Write a program with which one can play Lingo. Use square
brackets to mark characters correct in the sense of 1), and ordinary
parentheses to mark characters correct in the sense of 2)
Current Code:
def lingo():
import random
words = ['pizza', 'motor', 'scary', 'motel', 'grill', 'steak', 'japan', 'prism', 'table']
word = random.choice(words)
print word
while True:
guess = raw_input("> ")
guess = list(guess.lower())
word = list(word)
for x in guess:
if x in word:
if x == word[word.index(x)]:
guess[guess.index(x)] = "[" + x + "]"
else:
guess[guess.index(x)] = "(" + x + ")"
print guess
lingo()
As of now, if the words share a common letter, it puts the letter in square brackets, regardless of whether it shares the same pos or not.
Examples:
CORRECT:
- Word: Table
- My Guess: Cater
- OUTPUT: C[a](t)(e)r
INCORRECT:
- Word: Japan
- My Guess: Ajpan (Notice the switch between the a and j, I did that on purpose).
- OUTPUT: [A][j][p][a][n] (Should Be (a)(j)[p][a][n])
Your error is this line:
if x == word[word.index(x)]:
which is always true since word[word.index(x)] is the same thing as x. Try changing it to:
if x == word[guess.index(x)]:
if x == word[word.index(x)]: should be if x == word[guess.index(x)]:
I'm using pyscripter to create a hangman game. I have managed to get everything to work except one thing. This is that once i have found the correct word the script needs to match this to the secret word. This would usually be easy but the way i have done it leaves gaps in the string.
What i want to do is using the number of letters in the secret word; when i enter a letter it looks for that letter and adds how many times the letter appears in the secret word. i.e. the letter "P" in APPLE appears 2 times, therefore adding 2 to a separate string. if the word was "APPLE" the program would be looking for 5 correct letters.
This way i can make an "if" statement and end the game once the numbers of correct letters guessed matches the length of the secret word.
This is the program i am using : http://i1.ytimg.com/vi/1HZ38RzykuE/maxresdefault.jpg
Does this make sense, I've been pondering on it for a while so it may be jumbled.
Thank you if your able to help.
This is the code i am using:
(blanktotal is the length of the secret word)
else:
if letter in secretword:
letterscorrect = letterscorrect + 1
os.system("cls")
if letter not in guessedletters:
os.system("cls")
for x in range(0, len(secretword)):
if letter == secretword[x]:
for x in range(len(secretword)):
if secretword[x] in letter:
hiddenletter = hiddenletter[:x] + secretword[x] + hiddenletter[x+1:]
guessedletters.append(letter)
else:
print("")
else:
print("")
for letter in hiddenletter:
print(letter, end=' ')
print("")
if letterscorrect == blanktotal:
os.system("cls")
print("")
print("congratulations you have won!!!!")
print("You are now the master of HANGMAN!!!!!")
print("")
You can use the count() method to count the number of occurrence of a letter.
secret = "Apple"
secret.count('p')
gives
2
I think you're just looking for the count method:
>>> s = 'APPLE'
>>> s.count('P')
2