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!")
Related
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.
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
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)
I'm currently using Python to create a hangman game but I can't quite figure out how to get it working. In the game, there is a list of fourteen words, and one word from the list will be selected at random to be the word that the player has to guess. The player will then have to keep entering letters until they get them all, or until they run out of guesses. At the start of the game, the word will be displayed with each letter represented by an underscore. But I have no idea how to get the letters to reveal themselves in place of the corresponding underscore as the player guesses them. This is the basic setup I have:
print(stage1)
if (mystery == "spongebob" or mystery == "squidward" or mystery == "pineapple" or mystery == "jellyfish"):
print("_ _ _ _ _ _ _ _ _")
print("Your word has 9 letters in it")
elif (mystery == "plankton"):
print("_ _ _ _ _ _ _ _")
print("Your word has 8 letters in it")
elif (mystery == "patrick"):
print("_ _ _ _ _ _ _")
print("Your word has 7 letters in it")
elif (mystery == "island"):
print("_ _ _ _ _ _")
print("Your word has 6 letters in it")
elif (mystery == "sandy" or mystery == "larry" or mystery == "beach"):
print("_ _ _ _ _")
print("Your word has 5 letters in it")
elif (mystery == "gary" or mystery == "tiki" or mystery == "rock" or mystery == "sand"):
print("_ _ _ _")
print("Your word has 4 letters in it")
print(mystery)
letter = str(input("Enter a letter you'd like to guess: "))
So how do I get the underscores to be replaced by letters as they are guessed?
By the way, don't keep writing print statements for each instance, just do this:
>>> mystery = 'hippopotamus'
>>> print '_ '*len(mystery)
_ _ _ _ _ _ _ _ _ _ _ _
But you also want to store the underscores in a variable, so that you can change and print them later. So do this:
>>> mystery = 'hippopotamus'
>>> fake = '_ '*len(mystery)
>>> print fake
_ _ _ _ _ _ _ _ _ _ _ _
Your next step is to take input. In my opinion, do not use str(input()), use raw_input. It is just a habit, because if you enter a number, it becomes '1', not 1.
>>> guess = raw_input("Enter a letter you'd like to guess: ")
Enter a letter you'd like to guess: p
Now to check if the letter is in the mystery. Do not use index to check, because if there is more than one instance with the letter, it will only iterate over the first instance. See this for more information.
>>> fake = list(fake) #This will convert fake to a list, so that we can access and change it.
>>> for k in range(0, len(mystery)): #For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
... if guess == mystery[k] #If the guess is in the answer,
... fake[k] = guess #change the fake to represent that, EACH TIME IT OCCURS
>>> print ''.join(fake) #converts from list to string
_ _ p p _ p _ _ _ _ _ _
n="no"
while 'no':
n = input("do you want to play? ")
if n.strip() == 'yes':
break
"""Hangman
Standard game of Hangman. A word is chosen at random from a list and the
user must guess the word letter by letter before running out of attempts."""
import random
def main():
welcome = ['Welcome to Hangman! A word will be chosen at random and',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts and your execution is complete.. no pressure'
]
for line in welcome:
print(line, sep='\n')
play_again = True
while play_again:
words = ["hangman", "chairs", "backpack", "bodywash", "clothing",
"computer", "python", "program", "glasses", "sweatshirt",
"sweatpants", "mattress", "friends", "clocks", "biology",
"algebra", "suitcase", "knives", "ninjas", "shampoo"
]
chosen_word = random.choice(words).lower()
player_guess = None
guessed_letters = []
word_guessed = []
for letter in chosen_word:
word_guessed.append("-")
joined_word = None
HANGMAN = (
"""
-----
| |
|
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| -+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| |
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| |
| |
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| | |
| |
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| | |
| | |
|
--------
""")
print(HANGMAN[0])
attempts = len(HANGMAN) - 1
while (attempts != 0 and "-" in word_guessed):
print(("\nYou have {} attempts remaining").format(attempts))
joined_word = "".join(word_guessed)
print(joined_word)
try:
player_guess = str(input("\nPlease select a letter between A-Z" + "\n> ")).lower()
except: # check valid input
print("That is not valid input. Please try again.")
continue
else:
if not player_guess.isalpha():
print("That is not a letter. Please try again.")
continue
elif len(player_guess) > 1:
print("That is more than one letter. Please try again.")
continue
elif player_guess in guessed_letters: # check it letter hasn't been guessed already
print("You have already guessed that letter. Please try again.")
continue
else:
pass
guessed_letters.append(player_guess)
for letter in range(len(chosen_word)):
if player_guess == chosen_word[letter]:
word_guessed[letter] = player_guess
if player_guess not in chosen_word:
attempts -= 1
print(HANGMAN[(len(HANGMAN) - 1) - attempts])
if "-" not in word_guessed:
print(("\nCongratulations! {} was the word").format(chosen_word))
else:
print(("Unlucky! The word was {}.").format(chosen_word))
print("Would you like to play again?")
response = input("> ").lower()
if response not in ("yes", "y"):
play_again = False
if __name__ == "__main__":
main()
This code plays a hangman game, feel free to change the words though. It took me ages to code this at school last year, it was part of my year 10 assessment.
Enjoy playing hangman.:)
Another way to get some codes is to look at other peoples. Their code can give you some inspiration and you can use several people's codes to create a program.
Here's something you could do, actually.
import random
print("Welcome to hangman!!")
words = []
with open('sowpods.txt', 'r') as f:
line = f.readline().strip()
words.append(line)
while line:
line = f.readline().strip()
words.append(line)
random_index = random.randint(0, len(words))
word = words[random_index]
guessed = "_" * len(word)
word = list(word)
guessed = list(guessed)
lstGuessed = []
letter = input("guess letter: ")
while True:
if letter.upper() in lstGuessed:
letter = ''
print("Already guessed!!")
elif letter.upper() in word:
index = word.index(letter.upper())
guessed[index] = letter.upper()
word[index] = '_'
else:
print(''.join(guessed))
if letter is not '':
lstGuessed.append(letter.upper())
letter = input("guess letter: ")
if '_' not in guessed:
print("You won!!")
break
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")