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()
Related
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!")
Follow up from this:
I want to now randomnize the AI boat's locations. Also, can we try to do two boats?
Here's the code if you dont want to click the above link:
def drawboard(hitboard):
print('| | | |')
print('| ' + hitboard[7] + ' | ' + hitboard[8] + ' | ' + hitboard[9] + ' |')
print('| | | |')
print('-------------')
print('| | | |')
print('| ' + hitboard[4] + ' | ' + hitboard[5] + ' | ' + hitboard[6] + ' |')
print('| | | |')
print('-------------')
print('| | | |')
print('| ' + hitboard[1] + ' | ' + hitboard[2] + ' | ' + hitboard[3] + ' |')
print('| | | |')
def aicorners(hitboard,spot_hit):
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def aiedges(hitboard,spot_hit):
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def aimiddle(hitboard,spot_hit):
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def hitplayer():
pass
def main():
gameisplaying = True
while gameisplaying:
hitboard = [' ' for i in range(10)]
userready = input('Place your ships. Type done when you finished placing it.')
while not userready == 'done':
userready = input('Type done when you locate your ship. ')
shipissunk = False
while shipissunk == False:
spot_hit = input('Where\'s the hit?: 1-9 ')
while not (spot_hit in '1 2 3 4 5 6 7 8 9'.split()):
spot_hit = input ('Please tell me where the hit is: 1-9 ')
spot_hit = int(spot_hit)
if (spot_hit in [1,3,7,9]):
aicorners(hitboard,spot_hit)
elif (spot_hit in [2,4,6,8]):
aiedges(hitboard,spot_hit)
else:
aimiddle(hitboard,spot_hit)
main()
Notice how I only have one boat, and it's set position of [1,2,3]. I want to change the location every time the user plays it.
Parts of code updated below: (should i replace the original code?)
def aicorners(hitboard,spot_hit,ship_spots,ship_spots2):
if spot_hit in ship_spots or spot_hit in ship_spots2:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def main():
import random
possible_spots = [[1,2,3], [4,5,6], [7,8,9], [7,4,1], [8,5,2], [9,6,3]]
possible_spots2 = [[1,2],[2,3],[4,5],[5,6],[7,8],[8,9],[1,4],[4,7],[2,5],[5,8],[3,6],[6,9]]
ship_spots = random.choice(possible_spots)
ship_spots2 = random.choice(possible_spots2)
gameisplaying = True
while gameisplaying:
hitboard = [' ' for i in range(10)]
userready = input('Place your ships. Type done when you finished placing it.')
while not userready == 'done':
userready = input('Type done when you locate your ship. ')
shipissunk = False
while shipissunk == False:
spot_hit = input('Where\'s the hit?: 1-9 ')
while not (spot_hit in '1 2 3 4 5 6 7 8 9'.split()):
spot_hit = input ('Please tell me where the hit is: 1-9 ')
spot_hit = int(spot_hit)
aicorners(hitboard,spot_hit,ship_spots,ship_spots2)
main()
Help is greatly appreciated!
Right now you're hard-coding the check (in three identical functions with different names -- a mysterious approach!) as:
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
this needs to become something like
if spot_hit in ship_spots:
where ship_spots is a global variable you randomly set at the start to one of the possible set of positions for the ship.
I have no idea what sets of positions you want to choose among (never played battleship on a 3 by 3 board!-) but for example:
import random
possible_spots = [[1,2,3], [4,5,6], [7,8,9]]
ship_spots = random.choice(possible_spots)
would give you one of the three horizontal possibilities.
Place this in main just before gameisplaying = True (the import random should more elegantly moved to the top of the module) and there you are.
Of course you would extend possible_spots if ships need not be horizontal, e.g
possible_spots = [[1,2,3], [4,5,6], [7,8,9],
[7,4,1], [8,5,2], [9,6,3]]
would allow the three vertical placements as well as the three horizontal ones.
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 am current building a simple card matching game in python, with a 5x4 (row*column) grid, in which two players try to match a deck of twenty cards (2,10 of only suit Hearts) * 2.
The problem I am running into is in iterating through the deck, printing the cards out in a grid fashion so it would look like this:
----- ----- ----- -----
- - - - - - - -
4-H 6-H 7-H 8-H
- - - - - - - -
----- ----- ----- -----
The code I currently have is below:
#needed import for shuffle function
from random import shuffle
#class for my deck
class Deck:
#constructor starts off with no cards
def __init__( self ):
self._deck = []
#populate the deck with every combination of suits and values
def Populate( self ):
#Heart, Diamond, Spades, Clubs
for suit in 'HDSC':
#Jack = 11, Queen = 12, King = 13, Ace = 14
for value in range(2, 15):
if value == 11:
value = 'J'
elif value == 12:
value = 'Q'
elif value == 13:
value = 'K'
elif value == 14:
value = 'A'
#add to deck list
self._deck.append(str(value) + '-' + suit)
#populate the deck with only hears hearts and all cards except face cards and aces (2, 3, 4, 5, 6, 7, 8, 9, 10) twice
def gamePop( self ):
suit = 'H'
for x in range(2):
for value in range(2, 11):
self._deck.append(str(value) + '-' + suit)
#shuffle the deck with the random import
def Shuffle( self ):
shuffle( self._deck )
#length of the deck
def len( self ):
return len( self._deck )
def stringIt( self ):
#Returns the string representation of a deck
result = ''
for c in self._deck:
result = result + str(c) + '\n'
return result
#class for a single card
class Card:
#constructor for what type of card it is
def __init__( self, value, suit ):
self._value = value
self._suit = suit
self._card = self._value + self._suit
#print the type of card
def Description( self ):
return ( self._card )
#overloaded ==
def __eq__( self, another ):
if ( self._card == another.Description() ):
return True
else:
return False
#main function which plays the game
def main():
#sets player counters to zero,
pOneCount = 0
pTwoCount = 0
#creates the deck to be put on the board
gameDeck = Deck()
gameDeck.gamePop()
gameDeck.Shuffle()
print(gameDeck._deck)
currentCard = 0
for row in range(5):
for card in range(0,4+i):
mystring =
print ('------- ' * 4)
print ('| | ' * 4)
for x in range(4):
print ('| ' +gameDeck._deck[currentCard]+'|'),
currentCard += 1
print ('| | ' * 4)
print ('------- ' * 4)
Edit: I cleared up the code which I've tried.
The current output is this:
------- ------- ------- -------
| | | | | | | |
| 7-H|
| 5-H|
| 7-H|
| 9-H|
| | | | | | | |
------- ------- ------- -------
the problem is in the def main():
def main():
print ('------- ' * 4)
print ('| | ' * 4)
for x in range(4):
print ('| ' +gameDeck._deck[currentCard]+'|'),
currentCard += 1
print ('| | ' * 4)
print ('------- ' * 4)
the * 4 just mean that this:
print ('------- ' * 4)
will become this:
print ('------- ' + '------- ' + '------- ' + '------- ' )
it can also be type as:
print ('------- ------- ------- ------- ' )
so. your problem is here:
for x in range(4):
print ('| ' +gameDeck._deck[currentCard]+'|'),
currentCard += 1
this would print as:
| 7-H|
| 5-H|
| 7-H|
| 9-H|
you need to put it as something like this:
print ('| ' +gameDeck._deck[currentCard]+'|'+'| ' +gameDeck._deck[currentCard+1]+'|'+'| ' +gameDeck._deck[currentCard+2]+'|'+'| ' +gameDeck._deck[currentCard+3]+'|')
so it would print in one line like how you want it:
| 7-H| | 5-H| | 7-H| | 9-H|
here is the code that i clean up a little. if it work like it should, it should work:
def main():
#sets player counters to zero,
pOneCount = 0
pTwoCount = 0
#creates the deck to be put on the board
gameDeck = Deck()
gameDeck.gamePop()
gameDeck.Shuffle()
print(gameDeck._deck)
currentCard = 0
for row in range(5):
for card in range(0,4+i):
print (' ------- ' * 4)
print (' | | ' * 4)
print (' | ' +gameDeck._deck[currentCard]+' | '+' | ' +gameDeck._deck[currentCard+1]+' | '+' | ' +gameDeck._deck[currentCard+2]+' | '+' | ' +gameDeck._deck[currentCard+3]+' | ')
print (' | | ' * 4)
print (' ------- ' * 4)
oh, and like John Y say (copy and paste):
The main function has a dangling mystring =, which is a blatant syntax error
here what i use to test, because the whole code don't work for me, i just tested the print part:
print (' ------- ' * 4)
print (' | | ' * 4)
print (' | ' +"1-H"+' | '+' | ' +"2-H"+' | '+' | ' +"3-H"+' | '+' | ' +"4-H"+' | ')
print (' | | ' * 4)
print (' ------- ' * 4)
that got me:
------- ------- ------- -------
| | | | | | | |
| 1-H | | 2-H | | 3-H | | 4-H |
| | | | | | | |
------- ------- ------- -------
>>>
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")