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
Related
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 make a really basic hangman game by using an if/in check, however, the code wasn't responding to changes in the player input. Since this is my first time using the in keyword, I wanted to ask if this was right.
I tried a few other methods such as string find and individually making letters a string (that was a mess),the if/in seemed like the most efficient way of completing the task. If there are any other ways, please let me know.
#put word into here, as a string :)
print("Welcome to Hangman")
word = ["a", "v", "a", "c" "a", "d", "o"]
wordLength = len(word) + 1
lives = wordLength * 2
print("lives:", lives)
print("Letters in word", wordLength)
guess = input("h")
while lives != 0:
if guess in word:
print("YES!")
print(guess)
index = word.index(guess)
print(index)
else:
print("Wrong!")
lives - 1
pass
pass
while lives == 0:
print("falied! try again")
pass
The ideal results would be when the input matches a letter in the above string, the console would print "YES!" and the letter, or if not print "Wrong" and take away a life.
Please check if this code works for you. I modified it a little and added some more conditions.
#put word into here, as a string :)
print("Welcome to Hangman")
word = ["a", "v", "a", "c", "a", "d", "o"]
wordLength = len(word) + 1
lives = wordLength * 2
print("lives:", lives)
print("Letters in word", wordLength)
guess = input("Enter the letter : ")
while lives != 0:
if guess in word:
print("YES!")
print(guess)
index = word.index(guess)
#print("Index = ",index)
del word[index]
else:
print("Wrong!")
lives -=1
print("lives:", lives)
if len(word)==0 and lives > 0:
print("Success!!")
break
guess = input("Enter the letter : ")
if lives == 0:
print("falied! try again")
Is this a correct use of the in keyword in python?
yes, it's correct to use the in keyword to check if a value is present in a sequence (list, range, string etc.), but your sample code contains several other errors, which are out-of-scope of the main question, just like the game below...
In the meanwhile, I got interested by the question and coded a quick StackOverflow Popular Tags Hangman game with Tag definitions, i.e:
import requests
from random import choice
# src https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
# english word_list (big)
# word_list = requests.get("https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt").text.split("\n")
# you can use any word_list, as long as you provide a clean (lowered and sripped) list of words.
# To create a hangman game with the most popular tags on stackoverflow, you can use:
try:
word_list = requests.get("https://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow").json()['items']
word_list = [x['name'].lower() for x in word_list if x['name'].isalpha()] # filter tags with numbers and symbols
except:
print("Failed to retrieve json from StackExchange.") # exit here
# function that returns a random word with/out length range , uses word_list
def rand_word(_min=1, _max=15):
# filter word_list to words between _min and _max characters
r_word = [x.strip() for x in word_list if _min <= len(x) <= _max] #
return choice(r_word)
# tag definition from stackoverflow wiki
def tag_info(w):
try:
td = requests.get(f"https://api.stackexchange.com/2.2/tags/{w}/wikis?site=stackoverflow").json()['items'][0]['excerpt']
return(td)
except:
pass
print(f"Failed to retrieve {w} definition")
# game logic (win/loose)
def play(word):
word_l = list(word) # list with all letters of word
wordLength = len(word_l)
lives = 7
print("Lives:", lives)
print("Letters in word", wordLength)
place_holder = ["*" for x in word_l]
used = [] # will hold the user input letters, so no life is taken if letter was already used.
while 1:
print("".join(place_holder))
guess = input().lower().strip() # get user guess, lower it and remove any whitespaces it may have
if not guess or len(guess) > 1: # if empty guess or multiple letters, print alert and continue
print("Empty letter, please type a single letter from 'a' to 'z' ")
continue
if guess in word_l:
used.append(guess) # appends guess to used letters
print(guess, "Correct!", guess)
for l in word_l: # loop all letters in word and make them visible
if l == guess:
index = word_l.index(guess) # find the index of the correct letter in list word
word_l[index] = "." # use index to substitute the correct letter by a dot (.), this way, and if there are repeated letters, they don't overlap on the next iteration. Small hack but it works.
place_holder[index] = guess # make the correct letter visible on place_holder. Replaces * by guess
elif guess in used:
print("Letter already used.")
continue
else:
used.append(guess) # appends guess to used letters
print(HANGMANPICS[-lives])
lives -= 1 # removes 1 life
print(f"Wrong! Lives: {lives}" )
if lives == 0:
print(f"You Lost! :-|\nThe correct word was:\n{word}\n{tag_info(word)}")
#print(HANGMANPICS[-1])
break
# When there are no more hidden letters (*) in place_holder the use won.
if not "*" in place_holder:
print(f"You Won!!!\n{word}\n{tag_info(word)}")
break
print("Welcome to StackTag Hangman")
while 1:
play(rand_word(1, 15)) # creates a new game with a random word between x and x letters. play() can be simply be used as play("stackoverflow").
pa = input("Try again? (y/n)\n").lower().strip() # Ask user if wants to play again, lower and cleanup the input for comparision below.
if pa != "y": # New game only if user input is 'y', otherwise break (exit)
print("Tchau!")
break
Notes:
You can play with it
Asciinema Video
v2 with approx. 7k computer jargon's.
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")