Hangman game, if condition not working properly - python

I want to print a message on the screen saying "you have already entered that letter" ONLY in the case the letter was entered previously.
If the letter is being entered for the first time it should not print that.
Below is my code but it prints the message even when the letter is entered for the first time:
import requests
import random
import hangman_art #import logo
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.text.splitlines()
chosen=random.choice(WORDS) #use this or lines 8,9,10
#https://stackoverflow.com/questions/75139406/how-to-pick-a-string-from-a-list-and-convert-it-to-a-list-python?noredirect=1#comment132596447_75139406
# ~ rand=random.randint(0,10000)
# ~ pick=WORDS[rand]
# ~ pick_as_list=list(pick)
print(hangman_art.logo)
print(chosen)
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
x=[]
lives=6
for letter in chosen:
x+='_'
s=' '.join(x)
print(s)
while '_' in x:
user=input("Guess a letter: ").lower()
if user in chosen: #<---------------------------- My trial
print(f"You've already guessed {user}")
for i in range(0,len(chosen)):
if chosen[i]==user:
x[i]=user
s=' '.join(x)
print(s)
if '_' not in x:
print("You Win!")
if user not in chosen:
lives-=1
print(stages[lives])
print(f"You guessed {user}, that's not in the word. You lose a life ({lives} left).")
if lives==0:
print("You lose.")
break
Also I noticed it takes a life from the user if they repeat the wrong letter. I want it to take a life only for the first trial of a wrong letter.

Simplest thing to do is add a "continue" right after the "You've already guessed" print statement. However, I would also advise some better programming practices and use elif and else statements.

Related

Why is my Spaces and actual game not printing correctly

My game almost works perfectly but for some reason my space variable wont print correctly.
Also, the game automatically asks to play again after pressing enter. My code runs fine it s just not printing what I want it to print. The only problems are with the Spaces variable and maybe somewhere in 1 of the functions.
import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words={
'Colors':'red orange yellow green blue indigo violet white black brown'.split(),
'Shapes':'square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon hexagon septagon octagon'.split(),
'Fruits':'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantaloupe mango strawberry tomato'.split(),
'Animals':'bat bear beaver cat cougar crab deer dog donkey duck eagle fish frog goat leech lion lizard monkey moose mouse otter owl panda python rabbit rat shark sheep skunk squid tiger turkey turtle weasel whale wolf wombat zebra'.split()}
def getRandomWord(wordDict):
# This function returns a random string from the passed dictionary of lists of strings, and the key also.
# First, randomly select a key from the dictionary:
wordKey = random.choice(list(wordDict.keys()))
# Second, randomly select a word from the key's list in the dictionary:
wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
return [wordDict[wordKey][wordIndex], wordKey]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print(HANGMANPICS[len(missedLetters)])
print()
print(' Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print()
spaces = '_' * len(secretWord)
for i in range(len(secretWord)): # replace blanks with correctly guessed letters
if secretWord[i] in correctLetters:
spaces = spaces[:i] + secretWord[i] + blanks[i+1:]
for letter in spaces: # show the secret word with spaces in between each letter
print(letter, end=' ')
print()
def GetdaGuess(alreadyGuessed):
while True:
print('Pick a letter for the Hangman Game')
R_I = input()
R_I = R_I.lower()
if len(R_I) != 1:
print('Please enter 1 letter only')
elif R_I in alreadyGuessed:
print('You"ve chosen that letter. Please try again')
if R_I not in 'abcdefghijklmnopqrstuvwxyz':
print('Only letters please')
return R_I
def Play1MoreTime():
guess = input('Would you like to play again?\n')
return input().lower().startswith('y')
print('H A N G M A N ')
missedLetters = ''
correctLetters = ''
secretWords = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWords)
guess = GetdaGuess(missedLetters + correctLetters)
if guess in secretWords:
correctLetters = correctLetters + guess
foundAllDaLetters = True
for i in range(len(secretWords)):
if secretWords[i] not in correctLetters:
foundAllDaLetters = False
break
if foundAllDaLetters:
print('Good job. The correct word was'+ secretWord+'. ')
if len(missedLetters) == len(HANGMANPICS) - 1:
print('Your out of tries.\nAfter ' + str(len(missedLetters)) + ' wrong guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
if gameIsDone:
if Play1MoreTime():
missedLetters = ''
correctLetters = ''
gameIsdone = False
secretWord = getRandomWord(words)
else:
break

Python - I'm making a hangman game, and nothing gets updated

So pretty much it's in the title.
Once you type a letter in it returns the same thing from the beginning. I'm new to python and I don't know that much about it, I've tried finding a solution to it here already but was unsuccesful. I don't think it's very complicated so I hope someone can figure out what is wrong.
import random
HANGMAN = (
"""
------
| |
|
|
|
|
|
|
|
----------
""",
"""
------
| |
| O
|
|
|
|
|
|
----------
""",
"""
------
| |
| O
| -+-
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-/
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-/
| |
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-/
| |
| |
| |
| |
|
----------
""",
"""
------
| |
| O
| /-+-/
| |
| |
| | |
| | |
|
----------
""")
MAX_WRONG = len(HANGMAN) - 1
WORDS = ("WAREHOUSE", "HINGE", "SPOON", "WALLET", "GRATE", "POCKET", "REINDEER", "NILE", "POISON", "LEGEND", "SAXOPHONE",
"CIRCUS", "SILO", "FLOOD", "DISH", "SCANDAL", "FRAME", "CAFE")
word = random.choice(WORDS)
guessed = "-" * len(slowo)
wrong = 0
used = []
print("Welcome to Hangman!'.\n WARNING! Type all the letters in uppercase")
while wrong < MAX_WRONG and guessed != word:
print(HANGMAN[wrong])
print("\nYou used these letters already:\n", used)
print("\nYou guessed these many so far:\n", guessed)
guess = input("\n\nType in a letter: ")
guess = guess.upper()
while guess in used:
print("You've already used: ", guess)
guess = input("Wprowadź literę: ")
guess = guess.upper()
used.append(guess)
if guess in word:
print("\nGood Job!", guess, "is in the hidden word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += guessed[i]
guessed = new
else:
print("\nLetter: ", guess, "isn't featured in the hidden word.")
wrong += 1
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\nYou died...")
else:
print("\nCongratulations! You guessed the hidden word!")
print("\The hidden word was: ", word)
input('\n\nTo end the process, press ENTER.')
That's it, if you've run the code you may've seen that it just returns
| |
|
|
|
|
|
|
|
You used these letters already:
[]
You guessed these many so far:
I had to learn a little bit of Polish to walk through what was happening, but it looks like this section of code needs to be indented so that it is in the first while block:
uzyte.append(traf)
if traf in slowo:
print("\nBrawo!", traf, "znajduje się w ukrytym słowie!")
nowy = ""
for i in range(len(slowo)):
if traf == slowo[i]:
nowy += traf
else:
nowy += odgadniete[i]
odgadniete = nowy
else:
print("\nLitera: ", traf, "nie występuje w ukrytym słowie.")
zle += 1
if zle == MAX_ZLE:
print(WISIELEC[zle])
print("\nNie żyjesz...")
else:
print("\nGratulacje! Odgadłeś ukryte słowo!")
Result:
Wykorzystałeś już następujące litery:
['A', 'B', 'C', 'D', 'E', 'F', 'G']
Na razie odgadłeś tyle liter:
--A-A
Wprowadź literę: h
Litera: H nie występuje w ukrytym słowie.
------
| |
| O
| /-+-/
| |
| |
| | |
| | |
|
----------
Nie żyjesz...
>>>
Here's a working example of the (now translated) while block:
while wrong < MAX_WRONG and guessed != word:
print(HANGMAN[wrong])
print("\nYou used these letters already:\n", used)
print("\nYou guessed these many so far:\n", guessed)
guess = input("\n\nType in a letter: ")
guess = guess.upper()
while guess in used:
print("You've already used: ", guess)
guess = input("Wprowadź literę: ")
guess = guess.upper()
used.append(guess)
if guess in word:
print("\nGood Job!", guess, "is in the hidden word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += guessed[i]
guessed = new
else:
print("\nLetter: ", guess, "isn't featured in the hidden word.")
wrong += 1
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\nYou died...")
else:
print("\nCongratulations! You guessed the hidden word!")

How to print Tic-Tac-Toe game board?

I am trying to print the board for Tic-Tac-Toe game. When I try to run it nothing happens and it says there is invalid syntax. The invalid syntax says that it is some were in my printboard function.
I don't see what is wrong with my code.
How can I make it print the board?
#Tic-Tac-Toe Game
import os
import time
import random
board = [" " for x in range(10)]
def printTitle():
print"""
---------------- 1 | 2 | 3
TIC - TAC - TOE 4 | 5 | 6
________________ 7 | 8 | 9
TO PLAY TIC - TAC - TOE, YOU NEED TO GET THREE IN A ROW.
YOUR CHOICES ARE BETWEEN 1 TO 9.
"""
def printBoard():
print ( " | | ")
print (" "+board[1]+" | "+board[2]+" | "+board[3]+" ")
print (" | |")
print ("---|---|---")
print (" | |")
print (" "+board[4]+" | "+board[5]+" | "+board[6]+" ")
print (" | |")
print ("---|---|---")
print (" | |")
print (" "+board[7]+" | "+board[8]+" | "+board[9]+" ")
print (" | | ")
while True:
os.system("clear")
printTitle()
printBoard()
choice = input("Please choose an empty space for X. ").upper()
choice = int(choice)
if board[choice] == " ":
board[choice] = "X"
else:
print "Sorry, that space is not empty!"
time.sleep(1)
The result should be:
| |
| |
| |
-------------
| |
| |
| |
-------------
| |
| |
| |
Error message (from #Prune):
File "so.py", line 20
"""
^
SyntaxError: invalid syntax
def printTitle():
print"""
---------------- 1 | 2 | 3
TIC - TAC - TOE 4 | 5 | 6
________________ 7 | 8 | 9
TO PLAY TIC - TAC - TOE, YOU NEED TO GET THREE IN A ROW.
YOUR CHOICES ARE BETWEEN 1 TO 9.
"""
Try this :
str = '''
---------------- 1 | 2 | 3
TIC - TAC - TOE 4 | 5 | 6
________________ 7 | 8 | 9
TO PLAY TIC - TAC - TOE, YOU NEED TO GET THREE IN A ROW.
YOUR CHOICES ARE BETWEEN 1 TO 9.
'''
def printTitle(str):
print(str)
There is a problem in your print statement under this function
The error is due to the comment quotes in your print statement in printTitle() method and not putting string in brackets in last print statement. You need to make the changes to your print statements:
In method printTitle(), add remove comment tags and add open brackets as well as backslash('\') at the end of each line, this is used for representing multi line string.
In while loop add the parentheses in your last print statements.
The corrected code is here for your reference.
import os
import time
import random
board = [" " for x in range(10)]
def printTitle():
print("\
\
---------------- 1 | 2 | 3\
TIC - TAC - TOE 4 | 5 | 6\
________________ 7 | 8 | 9\
\
TO PLAY TIC - TAC - TOE, YOU NEED TO GET THREE IN A ROW.\
YOUR CHOICES ARE BETWEEN 1 TO 9.")
def printBoard():
print ( " | | ")
print (" "+board[1]+" | "+board[2]+" | "+board[3]+" ")
print (" | |")
print ("---|---|---")
print (" | |")
print (" "+board[4]+" | "+board[5]+" | "+board[6]+" ")
print (" | |")
print ("---|---|---")
print (" | |")
print (" "+board[7]+" | "+board[8]+" | "+board[9]+" ")
print (" | | ")
while True:
os.system("clear")
printTitle()
printBoard()
choice = input("Please choose an empty space for X. ").upper()
choice = int(choice)
if board[choice] == " ":
board[choice] = "X"
else:
print("Sorry, that space is not empty!")
time.sleep(1)

Why am i getting 'string index out of range' when my code tries to replace missing letter with a letter in my hangman game

This hangman game isn't entirely finished as I'm still working on it, however i came across this error which occurs very often if i get all my guesses correct. When i run it and guess a number of guesses it will sometimes not print the correct amount of left gaps after the letter or the error:
Traceback (most recent call last):
File "C:\Users\Gaming\Desktop\Hangman.py", line 110, in <module>
display(Hangman,randomWord,wrongLetters,correctLetters)
File "C:\Users\Gaming\Desktop\Hangman.py", line 73, in display
blanks = secretWord[i] + blanks[:i] + blanks[i+1] #blanks[i+1] adding '-' from the old 'blanks'
IndexError: string index out of range
will come up and sometimes both errors will happen follow one after another.
Can someone tell me how to fix this error and why it happens?
import random
Hangman = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote 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()
def GetRandomWord(word):
chosenWord = random.choice(word)
return chosenWord
def display(hangmanPic,secretWord,numWrongLetters,correctLetters):
blanks = '-'*len(secretWord)
for i in range(len(secretWord)):#repleaces blank letters with correct letters
if secretWord[i] in correctLetters:
blanks = secretWord[i] + blanks[:i] + blanks[i+1] #blanks[i+1] adding '-' from the old 'blanks'
print("Missing Letters:")
for letter in blanks:
print(letter,end='')
print(hangmanPic[numWrongLetters])
def getGuess(alreadyGuessed):
while True:
print("Guess Letter:")
guess = input()
guess = guess.lower()
if len(guess) != 1:
print("Please enter only 1 letter.")
elif guess in alreadyGuessed:
print("Letter is already guessed.")
elif guess.isdigit():
print("Please enter a letter not integer.")
else:
return guess
def playAgain():
print("Do you want to play again?")
pass
print("H A N G M A N")
correctLetters = ''
guessedLetters = ''
wrongLetters = 0
randomWord = GetRandomWord(words)
gameDone = False
while True:
display(Hangman,randomWord,wrongLetters,correctLetters)
guess = getGuess(correctLetters + guessedLetters)
if guess in randomWord:
correctLetters += guess
foundAllLetters = True
for i in range(len(randomWord)):
if randomWord[i] not in correctLetters:
foundAllLetters = False
break
if randomWord[i] in correctLetters:
foundAllLetters = True
print("Well Done You found what the missing word is!")
gameDone = True
else:
wrongLetters +=1
guessedLetters += guess
for i in range(len(secretWord)):
if secretWord[i] in correctLetters:
blanks = secretWord[i] + blanks[:i] + blanks[i+1]
# | will be out of range for the last 'i'
What you should do, only change the letter at blanks[i]. Strings, however, are immutable in Python, but from what I can see you should be perfectly fine using a list instead. Change the declaration of blanks to
blanks = ['-']*len(secretWord)
Now you should be able to use
blanks[i] = secretWord[i]
Another tip would be to use enumerate instead of range for a little cleaner code:
blanks = ['-']*len(secretWord)
for i, letter in enumerate(secretWord):
if letter in correctLetters:
blanks[i] = letter

Can someone help me with hangman?

I'm using python 2.7.1 to make a hangman game. I am trying to let the user choose whether to replay before the game finishes. I am trying to use a variable keep_playing, but it doesn't work.
Also, in guesses=word_len * ['_'], I want to have a space between the underscores because, if they stick together, I can't see how many letters are left. This is my hangman code:
from random import *
import os
keep_playing = True
def print_game_rules(max_incorrect,word_len):
print"you have only 7 chances to guess the right answer"
return
def get_letter():
print
letter = raw_input("Guess a letter in the mystery word:")
letter.strip()
letter.lower()
print
os.system('cls')
return letter
def display_figure(hangman):
graphics = [
"""
+--------+
|
|
|
|
|
|
====================
""",
"""
+-------
| o
|
|
|
|
====================
""",
"""
+-------
| o
| +
| |
|
|
======================
""",
"""
+-------
| o
| ---+
| |
|
|
|
=====================
""",
"""
+-------
| o
| ---+---
| |
|
|
|
|
=====================
""",
"""
+-------
| o
| ---+---
| |
| /
| /
| /
|
=====================
""",
"""
+-------
| o
| ---+---
| |
| / \
| / \
| / \
|
=====================
"""]
print graphics[hangman]
return
animals=["horse","donkey","dinosaur","monkey","cat","aligator","butterfly","buffallo","dragon"]
word=choice(animals)
word_len=len(word)
guesses=word_len * ['_']
max_incorrect=6
alphabet="abcdefghijklmnopqrstuvxyz"
letters_tried=""
number_guesses=0
letters_correct=0
incorrect_guesses=0
print_game_rules(max_incorrect,word_len)
while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
letter=get_letter()
if len(letter)==1 and letter.isalpha():
if letters_tried.find(letter) != -1:
print "You already picked", letter
else:
letters_tried = letters_tried + letter
first_index=word.find(letter)
if first_index == -1:
incorrect_guesses= incorrect_guesses +1
print "The",letter,"is not the mystery word."
else:
print"The",letter,"is in the mystery word."
letters_correct=letters_correct+1
for i in range(word_len):
if letter == word[i]:
guesses[i] = letter
else:
print "Please guess a single letter in the alphabet."
display_figure(incorrect_guesses)
print ''.join(guesses)
print "Letters tried so far: ", letters_tried
if incorrect_guesses == max_incorrect:
print "Sorry, too many incorrect guesses. You are hanged."
print "The word was",word
keep_playing = False
if letters_correct == word_len:
print "You guessed all the letters in the word!"
print "The word was",word
keep_playing = False
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")
print ''.join(guesses) can be turned into print ' '.join(guesses) giving spaces between the letters
you need to do keep_playing = False before while keep_playing == False: and the main game loop should be in a function that gets called from this loop if keep_playing == True:
The following will do what you want to do.
from random import *
import os
keep_playing = True
def print_game_rules(max_incorrect,word_len):
print"you have only 7 chances to guess the right answer"
return
def get_letter():
print
letter = raw_input("Guess a letter in the mystery word:")
letter.strip()
letter.lower()
print
os.system('cls')
return letter
def display_figure(hangman):
graphics = [
"""
+--------+
|
|
|
|
|
|
====================
""",
"""
+-------
| o
|
|
|
|
====================
""",
"""
+-------
| o
| +
| |
|
|
======================
""",
"""
+-------
| o
| ---+
| |
|
|
|
=====================
""",
"""
+-------
| o
| ---+---
| |
|
|
|
|
=====================
""",
"""
+-------
| o
| ---+---
| |
| /
| /
| /
|
=====================
""",
"""
+-------
| o
| ---+---
| |
| / \
| / \
| / \
|
=====================
"""]
print graphics[hangman]
return
while keep_playing:
animals=["horse","donkey","dinosaur","monkey","cat","aligator","butterfly","buffallo","dragon"]
word=choice(animals)
word_len=len(word)
guesses=word_len * ['_']
max_incorrect=6
alphabet="abcdefghijklmnopqrstuvxyz"
letters_tried=""
number_guesses=0
letters_correct=0
incorrect_guesses=0
print_game_rules(max_incorrect,word_len)
while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
letter=get_letter()
if len(letter)==1 and letter.isalpha():
if letters_tried.find(letter) != -1:
print "You already picked", letter
else:
letters_tried = letters_tried + letter
first_index=word.find(letter)
if first_index == -1:
incorrect_guesses= incorrect_guesses +1
print "The",letter,"is not the mystery word."
else:
print"The",letter,"is in the mystery word."
letters_correct=letters_correct+1
for i in range(word_len):
if letter == word[i]:
guesses[i] = letter
else:
print "Please guess a single letter in the alphabet."
display_figure(incorrect_guesses)
print ' '.join(guesses)
print "Letters tried so far: ", letters_tried
if incorrect_guesses == max_incorrect:
print "Sorry, too many incorrect guesses. You are hanged."
print "The word was",word
break
if letters_correct == word_len:
print "You guessed all the letters in the word!"
print "The word was",word
break
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
else:
break
raw_input ("\n\n\nPress enter to exit")

Categories

Resources