here is my python game:
import random
print('H A N G M A N')
hidden_words = ['python', 'java', 'kotlin', 'javascript']
hidden_word = random.choice(hidden_words)
display = '-' * len(hidden_word)
used = []
i = 0
maxshit = 8
while i < maxshit and display != hidden_word:
print()
print(display)
inp = input("Input a letter: ")
if inp in used:
print("No improvements")
i += 1
elif inp in hidden_word:
new = ""
used.append(inp)
for i in range(len(hidden_word)):
if inp == hidden_word[i]:
new += inp
else:
new += display[i]
display = new
else:
print("No such letter in the word")
i += 1
if i == maxshit:
print("You are hanged!")
else:
print("You survived!")
print()
print('Thanks for playing!')
print("We'll see how well you did in the next stage")
It works well when there is 8 wrong answers you lose and game print "You are hanged !",but if you answer is well you win and it prints "You survived" and if you print allredy printed word it prints "No improvments!" or if there is no word what you inputed it prints "No such letter in the world !".
But when you input looks like
$ python govno.py
H A N G M A N
------
Input a letter: j
No such letter in the word
------
Input a letter: i
----i-
Input a letter: g
No such letter in the word
----i-
Input a letter: g
No such letter in the word
----i-
Input a letter: k
k---i-
Input a letter: g
No such letter in the word
k---i-
Input a letter: g
No such letter in the word
k---i-
Input a letter: g
No such letter in the word
You are hanged!
In this input you lose only after 6 mistakes. Why is this like that?
P.S sorry for comon mistakes I am only begining
The problem is in your second loop (the for loop) you reused the variable i. When the input is in the hidden word and after the loop the variable i will be set to one less than the length of the hidden word ("kotlin"), which in this case is 5. After that, the i was incremented 3 times, ending at the value of 8, which is equal to maxshit. So the loop ended and the message was displayed.
Change that variable to another name (e.g. j).
The loop should look something like this:
for j in range(len(hidden_word)):
if inp == hidden_word[j]:
new += inp
else:
new += display[j]
Related
Hangman. As you probobly understand i am new to coding and python, sorry for bad code.
The best way i can think of to describe this problem is through the following way: In the "try:" section i try to index = list_of_letters.index(guesssed_letter_string). i want to check if the guessed_letter_string is in list_of_letters: i earlier in the code translate the input from well the only input() in the code to guessed_letter_string (its the same thing). when you input a letter in the middel of the word it works like index[3] but when you input the first letter in the word the index locks at 0 and every other letter replaces it. is there a way to fix this
import random
list_of_words = ["mom", "dad", "sister", "brother"]
random_word = random.choice(list_of_words)
list_of_letters = list(random_word)
print(random_word)
print(list_of_letters)
rounds_failed = 1
rounds_max = 16
list_of_letters_guessed = []
under_grejer = []
count_of_right_letters_list = []
print(f"You have {rounds_max - rounds_failed} rounds left to find out the word")
for every in list_of_letters:
under_grejer.extend("_")
while True:
if rounds_failed == rounds_max:
print("To many attempts, no more rounds")
break
if len(list_of_letters) == 0:
print("YOU FUCKING WON")
break
print(f"This is round: {rounds_failed}")
print(" ".join(under_grejer))
print("Letters that are correct(not in order): "+", ".join(count_of_right_letters_list))
print("List of letters guessed: "+", ".join(list_of_letters_guessed))
guess = input("NAME A Letter: ")
guess_letters_list = (list(guess))
guess_count_letters = len(guess_letters_list)
if guess_count_letters > 1:
print("Dummy you just need to input a letter, nothing else")
guesssed_letter_string = " ".join(guess_letters_list)
try:
index = list_of_letters.index(guesssed_letter_string)
print("Congrats you got the letter: " + guesssed_letter_string)
print(f"thats the {index + 1}nd letter in the word")
rounds_failed += 1
count_of_right_letters_list.extend(guesssed_letter_string)
print(index)
list_of_letters.pop(index)
under_grejer[index] = guesssed_letter_string
except ValueError:
print("try again mate that letter was not in the word")
list_of_letters_guessed.append(guesssed_letter_string)
rounds_failed += 1
continue
It's not about the first letter only. Your problem is that with list_of_letters.pop(index) you remove the guessed letter form list_of_letters; parts of your code rely on this to check if you guessed all occurrences of that letter before already, but on the other hand this reduces the index of all letters behind the guessed one for later iterations.
For example, for brother, if you guess r it correctly says position 2, but if you then guess o next, it again says position 2 because your list_of_letters now reads ["b","o","t","h","e","r"].
You could either try to work with list_of_letters_org = list_of_letters.copy() which you will never change, and pick the right one for every task, or you could for example change the program structure by adding a list of booleans that store which letters were guessed already.
I am making a hang man game. I am trying to cycle through a word and have all the repeats in the letter be appended to my list. For example the word "hello": if the user types in "l" I want all the l's to be added to my list. Right now it is only finding one "l" and if the user types an "l" again it finds the second "l".
I also want the user not to be able to type in another letter if they previously already typed it in.
I have two lists one for right guesses and wrong guesses that store every guess. For example if a user types in "h" in "hello"
"h" is a right guess so it appends to [h] but if they type in "h" again it adds it to the list so it says ["h","h"]. The wrong box works the same way but for words that are wrong. If they type in "z" for the word "hello" it says ["z"] in the wrong box.
Here is my code:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
# Picks a random word from the list and prints the length of it
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:")
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word:
right_guess.append(i)
else:
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
I'm not sure what your direct question is, but thinking about a hangman game you want to take the users guess and parse the entire word or phrase they are guessing to see if their guess matches anywhere in the word. I made a hang man game below that will function as expected (minus any error handling) Let me know if any parts confuse you, and i can explain
import random
wordcomp = []
wordguess = []
#this is a word bank for all puzzles, they are randomly chosen
word_bank = ['guess this phrase', 'Lagrange', 'foo', 'another phrase to guess']
# This loop stores each letter in a list, and generates a blank list with correct spaces and blanks for user
rand_word = random.randrange(4)
for i in word_bank[rand_word]:
wordcomp.append(i)
if i == ' ':
wordguess.append(' ')
else:
wordguess.append('__')
print('I am thinking of a word,' , wordguess , ' it has ', len(wordguess), ' characters total, GOOD LUCK \n')
wordlist = wordcomp
count = 0
placeletter = 0
wrongguess = []
guesscount = 0
while wordlist != wordguess:
guess = input('please input a lower case letter within the english alphabet!') ##Check that input is one character, and lower case
guesscount = guesscount + 1
# This for loop scans through to see if the letter that was guessed is in the actual puzzle, and places in the correct spot!!
for t in wordcomp:
if t == guess:
wordguess[placeletter] = guess
placeletter = placeletter + 1
# This check tells them they already guessed that letter... then makes fun of them
if guess in wordguess:
pass
else:
wrongguess.append(guess)
while wrongguess.count(guess) > 1:
wrongguess.remove(guess)
print('you guessed the letter ' , guess , ' already, are you person that suffers short term memory loss...')
print('The word I am thinking of: ' , wordguess)
print('The letters you have already guess are: ', wrongguess)
placeletter = 0
# This tells them they finished the puzzle and the number of guesses it took, if its over 26, it calls them stupid for obvious reasons...
if guesscount >= 26:
print('you are an idiot if it took you more than 26 guesses..... now take a minute, sit silently, and think about why you are idiot if it took over 26 guesses... for hangman... where you guess the letters of the alphabet... YOU GET IT, stupid')
elif guesscount < 26:
print('Congrats you solved the puzzle, w00t!!')
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word and i not in right_guess:
right_guess.append(i)
elif i not in hold_random_word or i not in wrong_guess:
wrong_guess.append(i)
elif i in hold_random_word:
# here user types something that is already typed and is a right_guess
pass
else:
# Types something wrong, that was already typed
pass
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
It is not clear how you are taking inputs, but I think this code can be further optimized. Give it a shot.
Edit 1:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
# This condition can lead to issues in situations like this - abc and aabbcc [sorry couldn't quickly come up with a good actual example :)]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:").strip()
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
# user_input is 1 letter so for i in user_input will execute only once
# Use the if structure as defined above
if user_input in hold_random_word:
right_guess.append(i)
else:
# this is missing
turns -= 1
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
elif len(user_input) > 1:
print("Please type only one letter at a time")
elif not user_input.isalpha():
print("Please enter only valid English letters")
else:
# handle this however you want :)
pass
I am a new programmer with experience with Visual Basic for Applications and have recently changed to python.
I'm working on a number guessing game and so far progress has been great. The user enters 4 digits into the program. The program also generates a 4 digit number and the program returns Ys or Ns to show whether any digits are correct or not. EG 1357 as a user guess and 1358 as the programs number shows YYYN as output.
I'm trying to rework the program to make it simpler for users by showing H or L to suggest that they need to guess higher or lower IF the digit guessed is incorrect. If it's correct, then a Y should be shown as per normal. I am aware that it's a condition in the loop I need to change or another loop I need to add but I am struggling to see where to add this and how to write it. Does anybody have a solution for this?
Here is part of my code for the section of the program which returns the result for the guesses.
lives = 10
while lives > 0:
number = input("Enter your guess: ")
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else 'N'
if letter == 'Y' * len(numToGuess):
print("Good job!")
break
print(letter)
lives -= 1
else:
print("Game over! You used up all of your tries.")
Does anybody have a solution for this?
I prefer to use lists for this. Meaning, I'd convert both the correct answer and the user guess into separate digits saves in two lists and then compare them.
Let's say the correct answer is '1234':
lives = 10
correct_answer = 1234
correct_answer = [int(char) for char in str(correct_answer)]
while lives > 0:
letter = ''
number = input("Enter your guess: ")
number = [int(char) for char in str(number)]
if number == correct_answer:
print("Correct!")
break
for i in range(len(correct_answer)):
if correct_answer[i] == number[i]:
letter += 'Y'
elif correct_answer[i] > number[i]:
letter += 'H'
else:
letter += 'L'
print("Your guess is wrong: ", letter)
lives -= 1
print("Game over!")
Now for example:
Enter your guess: 1111
Your guess is wrong: YHHH
Enter your guess: 1235
Your guess is wrong: YYYL
Enter your guess: 1234
Correct!
Game over!
>>>
You can use zip function for compare the letters :
>>> a='1357'
>>> b='1358'
>>> l=[]
>>> for i,j in zip(a,b):
... if i==j :l.append('Y')
... else :l.append('N')
...
>>> ''.join(l)
'YYYN'
And for check the answer you can use a generator expression within all :
>>> all(i=='Y' for i in l)
False
You don't need to change your loop condition. Just change the logic of your if expression.
letter = ''
for i in range(len(numToGuess)):
if int(number[i]) == numToGuess[i]:
letter += 'Y'
elif int(number[i]) > numToGuess[i]:
letter += 'H'
else:
letter += 'L'
Or, in one line:
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else ('H' if int(number[i]) > numToGuess[i] else 'L')
So my program is this so far:
def update():
print word
counter = 0
blanks = len(word)*'-'
blank_list = list(blanks)
letter = raw_input('Please enter a single letter: ')
for index in range(len(word)):
if letter in word[index]:
blank_list[index] = letter
print ''.join(blank_list)
letter = raw_input('Please enter a single letter: ')
but when I enter a correct letter in the wrong order it displays it as an incorrect guess, ie, one of my words is horse, if i entered an o it would display -o---, but if I entered an h, it would come up as None, because haven't set parameters of what to do when it is incorrect guess. This goes for when it is if letter in word[index] or if letter == word[index].
any suggestions on how to fix this problem?
Here, you enforce order by looking at the exact index:
if letter == word[index]
You want to ask if letter in word. You can also find the exact index of the letter with word.index(letter) (careful with repeated letters).
I think the problem is that you have a for loop based on index so when you enter a correct answer the next correct letter has to be in a later index because you already passed the previous indexes. For a hangman program I might do something with a while loop and use a count like you have and if the count exceeds your limit then break the while loop and make you word a list of letters. Then check to see if your guessed letter is within your list of letters of the word.
so if your guess limit is 5 then do something like
break word into list
set guess count to 0
while guess_count < 5:
if letter in word_list:
#update
else:
guess_count += 1
The problem is that your guesses are based on indexing. Once you guess a letter, you cannot guess one before that.
Running your code:
>>> update('mouse')
mouse
Please enter a single letter: m
m----
Please enter a single letter: u
m-u--
Please enter a single letter: o
>>>
It exits because the placing of 'u' is after that of 'o'. Instead change your code to this:
def update(word):
found = False
guesses_left = 3
blank_list = list(len(word)*'_')
while guesses_left > 0:
letter = raw_input('Enter your letter: ')
for k in range(len(word)):
if word[k] == letter and letter not in blank_list:
blank_list[k] = letter
found = True
if found == False:
guesses_left-=1
else:
found = False
print ''.join(blank_list)
if '_' not in blank_list:
break
if guesses_left < 1:
print 'You lost!'
else:
print 'You won!'
Running my code:
>>> update('mouse')
Enter your letter: m
m____
Enter your letter: s
m__s_
Enter your letter: u
m_us_
Enter your letter: o
mous_
Enter your letter: e
mouse
You won!
>>>
I'm got the bulk of my first real attempt at a python program--a letter guessing game.
I've got the bulk of the work done, but I'm stuck on the last little bit
I want to make it so that the game alternates back and forth between user and AI turns, until the world has been fully revealed. I'm good so far up to here. At this point, I want to make it so the player to guess the most letters correctly wins a point. The computer moderator picks another word and starts again. The first player to five points wins the game.
I have a while loop that alternates between user/AI turns, but I can't get it to break properly once the word has been fully unveiled? After that it should be pretty simple to just compare the number of userCorrectLetters to the number of aiCorrectLetters and use that to determine who wins the point for the round.
Then I assume the entire thing should go inside a while loop that doesn't break until one of the players has reached 5 points.
The other thing I'm having problems with is how to disallow the user from re-guessing a character position that has already been solved.
import random
#set initial values
player1points= 0
ai= 0
userCorrectLetters= []
aiCorrectLetters=[]
wrongLetters=[]
wrongPlace= []
correctLetters = []
endGame = False
allLetters = set(list('abcdefghijklmnopqrstuvwxyz'))
alreadyGuessed = set()
userGuessPosition = 0
availLetters = allLetters.difference(alreadyGuessed)
#import wordlist, create mask
with open('wordlist.txt') as wordList:
secretWord = random.choice(wordList.readlines()).strip()
print (secretWord)
secretWordLength = len(secretWord)
def displayGame():
mask = '_' * len(secretWord)
for i in range (len(secretWord)):
if secretWord[i] in correctLetters:
mask = mask[:i] + secretWord[i] + mask [i+1:]
for letter in mask:
print (letter, end='')
print (' ')
print ('letters in word but not in correct location:', wrongPlace)
print ('letters not in word:', wrongLetters)
##asks the user for a guess, assigns input to variable
def getUserGuess(alreadyGuessed):
while True:
print ('enter your letter')
userGuess = input ()
userGuess= userGuess.lower()
if len(userGuess) != 1:
print ('please enter only one letter')
elif userGuess in alreadyGuessed:
print ('that letter has already been guessed. try again')
elif userGuess not in 'abcdefjhijklmnopqrstuvwxyz':
print ('only letters are acceptable guesses. try again.')
else:
return userGuess
def newGame():
print ('yay. that was great. do you want to play again? answer yes or no.')
return input().lower().startswith('y')
def userTurn(wrongLetters, wrongPlace, correctLetters):
print ('\n')
displayGame ()
print ('which character place would you like to guess. Enter number?')
userGuessPosition = input ()
if userGuessPosition not in ('123456789'):
print ('please enter a NUMBER')
userGuessPosition = input()
slice1 = int(userGuessPosition) - 1
##player types in letter
guess = getUserGuess(wrongLetters + correctLetters)
if guess== (secretWord[slice1:int(userGuessPosition)]):
print ('you got it right! ')
correctLetters.append(guess)
userCorrectLetters.append(guess)
displayGame()
elif guess in secretWord:
wrongPlace.append(guess)
print ('that letter is in the word, but not in that position')
displayGame()
else:
wrongLetters.append(guess)
print ('nope. that letter is not in the word')
displayGame()
def aiTurn(wrongLetters,wrongPlace, correctLetters):
print ('\n')
print ("it's the computers turn")
aiGuessPosition = random.randint(1, secretWordLength)
aiGuess=random.sample(availLetters, 1)
print ('the computer has guessed', aiGuess, "in position", + aiGuessPosition)
slice1 = aiGuessPosition - 1
if str(aiGuess) == (secretWord[slice1:userGuessPosition]):
correctLetters.append(aiGuess)
aiCorrectLetters.append(aiGuess)
print ('this letter is correct ')
return
elif str(aiGuess) in secretWord:
wrongPlace.append(aiGuess)
print ('that letter is in the word, but not in that position')
return
else:
wrongLetters.append(aiGuess)
print ('that letter is not in the word')
return
wordSolved = False
while wordSolved == False:
userTurn(wrongLetters, wrongPlace, correctLetters)
aiTurn(wrongLetters, wrongPlace, correctLetters)
if str(correctLetters) in secretWord:
break
The problem is here:
if str(correctLetters) in secretWord:
You might expect that str(['a', 'b', 'c']) returns 'abc' but it does not. It returns "['a', 'b', 'c']".
You should replace that line with:
if "".join(correctLetters) in secretWord:
There is one more problem with your code, except for this one:
Let's say the correct word is foobar. If the user guesses the first 5 letters, but in reversed order, correctLetters will be ['a', 'b', 'o', 'o', 'f'], and the line if "".join(correctLetters) in secretWord: will evaluate to False bacause 'aboof' is not in 'foobar'.
You could fix that problem by replacing if "".join(correctLetters) in secretWord: with:
if len(correctLetters) > 4:
Basically, this will end the execution of the program as soon as the user guesses 5 correct letters. There is no need to check if the the letters are in secretWord, because you already do that in userTurn function.
You are comparing the string representation of the list correctLetters to the string secretWord. For example:
>>> secretWord = 'ab'
>>> correctLetters = ['a','b']
>>> str(correctLetters)
"['a', 'b']"
>>> str(correctLetters) in secretWord
False
Try comparing a string made of the correct letters to the secret word:
>>> ''.join(correctLetters) == secretWord
True