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)
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
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!")
I am trying to draw a fake 3x3 tic tac toe board. I am new to python and I don't understand why this does not work. Help would be appreciated. Thanks!
def draw():
for i in range(4):
board = (" ___ " * 3)
for i in board:
("| " * 4).join(board)
print(board)
draw()
EDIT:
Final code:
def draw():
board = ''
for i in range(-1,6):
if i%2==0:
board += '| ' * 4
board += '\n| | | |'
else:
board += ' _____ ' * 3
board += '\n'
print (board)
draw()
output:
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
Double Edit:
Another way:
def drawsmall():
a = (' ___' * 3 )
b = ' '.join('||||')
print('\n'.join((a, b, a, b, a, b, a, )))
drawsmall()
output:
___ ___ ___
| | | |
___ ___ ___
| | | |
___ ___ ___
| | | |
___ ___ ___
I found it easier to do this in one loop, printing a row of the board each iteration. You can alternate between vertical and horizontal bars by checking if the current iteration is an even or odd number using the % operator.
With strings you don't need to use join -- it can be more clear to append with the += operator.
def draw():
# initialize an empty board
board = ""
# there are 5 rows in a standard tic-tac-toe board
for i in range(5):
# switch between printing vertical and horizontal bars
if i%2 == 0:
board += "| " * 4
else:
board += " --- " * 3
# don't forget to start a new line after each row using "\n"
board += "\n"
print(board)
draw()
Output:
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
If you don't want to use variables/functions/loops and want a simple one-liner solution based on Print command:
print("__|__|__", "__|__|__", " | | ", sep='\n')
Try this code instead:
def draw():
a=('\n _____ _____ _____ ')
b= ('\n| | | |')
print(a,b,b,a,b,b,a,b,b,a)
draw()
Output:
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
for Better view use:
def print_tic_tac_toe():
print("\n")
print("\t | |")
print("\t | | ")
print('\t_____|_____|_____')
print("\t | |")
print("\t | | ")
print('\t_____|_____|_____')
print("\t | |")
print("\t | | ")
print("\t | |")
print("\n")
print_tic_tac_toe()
Output :
| |
| |
_____|_____|_____
| |
| |
_____|_____|_____
| |
| |
| |
Look up how the join function works. First, it takes the given string and uses that for the "glue", the string that connects the others. Second, it returns the constructed string; your join operation fails to save the result.
Try doing this first with nested loops: print a row of boxes, then the horizontal divider, etc. Then, bit by bit, convert that to the single-string output you want.
You can try this:
def draw():
return [["__" for b in range(3)] for i in range(3)]
Now you have a list of lists which contains your board. To print it out, you can do this:
the_board = draw()
for i in the_board:
for b in i:
print('|'.join(i), end="")
print()
print(" | | ")
I thought I'd simplify things so that I could understand it myself. This code produces the same output as above:
def draw_board():
v = '| | | |'
h = ' ____ ____ ____ '
for i in range(0,10):
if i%3==0:
print(h)
else:
print(v)
draw_board()
Output:
____ ____ ____
| | | |
| | | |
____ ____ ____
| | | |
| | | |
____ ____ ____
| | | |
| | | |
____ ____ ____
You can try this:
find below python code for end-to-end interactive Tic-Tac-Toe board game.
Code looks lengthy which can be optimized, but it works perfect as interactive Tic-Tac-Toe board game.
#Function code to clear the output space (screen)
from IPython.display import clear_output
#code to display just board-
def ttt_borad(board):
cl = clear_output()
print('Your Tic-Tac-Toe board now:\n')
print(board[1] + "|" + board[2] + "|" + board[3])
print("________")
print(board[4] + "|" + board[5] + "|" + board[6])
print("________")
print(board[7] + "|" + board[8] + "|" + board[9])
#function code to accept player key choices-
def player_key():
player_choice = ''
play1 = ''
play2 = ''
while player_choice not in ('Y', 'N'):
player_choice = input("Player-1 would like to go first ? Enter Y/N: ")
player_choice = player_choice.upper()
if player_choice not in ('Y', 'N'):
print("Invalid Key")
else:
pass
if player_choice == 'Y':
while play1 not in ('X', 'O'):
play1 = input("Select your Key for Player-1 X or O: ")
play1 = play1.upper()
if play1 not in ('X', 'O'):
print("Invalid Key")
else:
pass
else:
while play2 not in ('X', 'O'):
play2 = input("Select your Key for Player-2 X or O: ")
play2 = play2.upper()
if play2 not in ('X', 'O'):
print("Invalid Key")
else:
pass
if play1 == 'X':
play2 = 'O'
elif play1 == 'O':
play2 = 'X'
elif play2 == 'X':
play1 = 'O'
elif play2 == 'O':
play1 = 'X'
print(f'Key for Player-1 is: {play1} and Key for Player-2 is: {play2}')
return play1, play2
#function code to accept key strokes to play game
def enter_key(key, bp):
play1, play2 = key
ind = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
i = 1
while i < 10:
j = 0
k = 0
print(f'Game Move: {i}')
while j not in ind:
j = input("Player-1: Select position (1-9) for your Move: ")
if j not in ind:
print("Invalid Key or Position already marked")
else:
pass
x = ind.index(j)
ind.pop(x)
j = int(j)
bp[j] = play1
ttt_borad(bp)
i = i + 1
tf = game_winner(key, bp)
if tf == 1:
print("The Winner is: Player-1 !!")
break
print(f'Game Move: {i}')
if i == 10:
break
while k not in ind:
k = input("Player-2: Select position (1-9) for your Move: ")
if k not in ind:
print("Invalid Key or Position already marked")
else:
pass
y = ind.index(k)
ind.pop(y)
k = int(k)
bp[k] = play2
ttt_borad(bp)
i = i + 1
ft = game_winner(key, bp)
if ft == 2:
print("The Winner is: Player-2 !!")
break
return bp
#function code to calculate and display winner of the game-
def game_winner(key, game):
p1, p2 = key
p = 0
if game[1] == game[2] == game[3] == p1:
p = 1
return p
elif game[1] == game[4] == game[7] == p1:
p = 1
return p
elif game[1] == game[5] == game[9] == p1:
p = 1
return p
elif game[2] == game[5] == game[8] == p1:
p = 1
return p
elif game[3] == game[6] == game[9] == p1:
p = 1
return p
elif game[4] == game[5] == game[6] == p1:
p = 1
return p
elif game[3] == game[5] == game[7] == p1:
p = 1
return p
elif game[1] == game[2] == game[3] == p2:
p = 2
return p
elif game[1] == game[4] == game[7] == p2:
p = 2
return p
elif game[1] == game[5] == game[9] == p2:
p = 2
return p
elif game[2] == game[5] == game[8] == p2:
p = 2
return p
elif game[3] == game[6] == game[9] == p2:
p = 2
return p
elif game[4] == game[5] == game[6] == p2:
p = 2
return p
elif game[3] == game[5] == game[7] == p2:
p = 2
return p
else:
p = 3
return p
#Function code to call all functions in order to start and play game-
def game_play():
clear_output()
entry = ['M', '1', '2', '3', '4', '5', '6', '7', '8', '9']
ttt_borad(entry)
plk = player_key()
new_board = enter_key(plk, entry)
tie = game_winner(plk, new_board)
if tie == 3:
print("Game Tie !!! :-( ")
print('Would you like to play again? ')
pa = input("Enter Y to continue OR Enter any other key to exit game: ")
pa = pa.upper()
if pa == 'Y':
game_play()
else:
pass
game_play()
#Try this entire code in any Python3 editor and let me know your feedback.
I have attached sample board how code displays.Sample Tic-Tac-Toe board by code
Thanks
def create_board():
board_size = int(input("What size game board they want to draw? "))
horizontal = " ---"
vertical = "| "
for i in range(board_size):
print(horizontal * board_size)
print(vertical * (board_size + 1))
return print(horizontal * board_size)
create_board()
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")