Python Black Jack game variant - python

My Black Jack code is very basic but is running quite smoothly, however I have run into a speed bump. Thus im here. When I call "Hit" to send me another card in my While loop, for every loop the DECK instantiates the same card. The first 2 drawn and the Hit card are always different but within the While loop (which is set to end when the player says "stay" and doesnt want another card.) the Hit cards remain the same.
import random
import itertools
SUITS = 'cdhs'
RANKS = '23456789TJQKA'
DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS))
hand = random.sample(DECK, 2)
hit = random.sample(DECK, 1)
print("Welcome to Jackpot Guesser! ")
c = input("Would you like to play Black Jack or play Slots? ")
if c == 'Black Jack':
print()
print("Welcome to Black Jack! Here are the rules: ")
print("Black Jack is a game of whit, skill with a bit of Luck. You will start with 2 card and try to achieve a total of 21 points. \n Each cards worth is equal to its number, face cards are worth 10 and the Ace can be 1 or 11 points. You decide. \n You can decide to -Stay- and take the points you have or -Hit- to get another card. If you get 21 its Black Jack and you win. \n If no one gets 21, the highest points win, but if you go over 21 you -Bomb- and lose everything. \n Becarful not to Bomb and goodluck out there! Remember, you got to know when to Hit, when to Stay and when to walk away! \n")
print(hand)
print()
g = 'swag'
while g != 'Stay':
g = input(("What would you like to do, Stay or Hit: "))
if g == 'Hit':
print(hit)
elif g == 'Stay':
print("Lets see how you did!")
else:
print("test3")
elif c == 'Slots':
print("test")
else:
print("test2")
EX: Hand: Td(two diamonds), 3c(3 club)
Hit: 7s(7 spades)
hit 7s
hit 7s
hit 7s
...
stay: lets see how you did. I need the continued While loop Hits to differ, any ideas.

The problem is that you are generating the hit card only once, during the start of the program. Changing your code from
if g == 'Hit':
print(hit)
to something like
if g == 'Hit':
hit = random.sample(DECK, 1)
print(hit)
will make it outputs different cards on each hit.

Related

Blackjack game not updating hands each time everyone draws

I'm trying to make a simple text-based Python game around blackjack. The game knows the variable 'hand' and 'd_hand' which are your hand and the dealer's hand, but won't update it after each new card is drawn. hand and d_hand are assigned to a random integer between 1 and 11 plus your current hand before it added the random number, which in theory should mean that your hand updates itself every time a new card is drawn.
Here's the code:
def draw(hand, d_hand):
x = randint(1, 11)
card = x
hand = x + hand
print("You drew...")
print(card)
y = randint(1, 11)
d_card = y
d_hand = y + d_hand
print("Dealer drew...")
print(d_card)
print("Your hand: ")
print(hand)
print("Dealer's hand: ")
print(d_hand)
ask()
And here's the output of everything:
(Note: I only am showing one function here, the game is obviously more than just this one function I'm showing.)
Press enter to begin:
You drew...
1
Dealer drew...
5
Your hand:
1
Dealer's hand:
5
Hit or stay? (h/s): h
You drew...
10
Dealer drew...
8
Your hand:
10
Dealer's hand:
8
Hit or stay? (h/s): '''
I'm not really sure what the issue is here...
By the way, I'm new to this site so I can't like any comments, so thank you to everyone who answered!
If hand and d_hand are lists (or mutable objets),
you may want to update the object itself by replacing hand = x + hand with hand.append(x).
Otherwise, your code will just create a new local list hand that will be lost when the function ends.
From the code you posted it looks like you aren't returning the new hands. So when the function returns the hands will revert to whatever value they were before the call. You can return tulples in python like return (hand,d_hand) and then do something like hand,d_hand = draw(hand,d_hand)

Python not finishing for loop

I just started learning python and I figured for fun to see if I could make a python version of the monty hall problem. Everything seems to be working on a small scale when I use 1 or 2 iterations but past that nothing is working. The for loop is not finishing the amount of iterations I want it to.
import random
def problem(tests):
wins = 0
losses = 0
doors = ["goat", "car", "goat"]
for test in range(tests):
#we shuffle the doors
random.shuffle(doors)
#the player picks a door
choice = random.choice(doors)
#monty chooses a door
montychoice = random.choice(doors)
while montychoice != 'car' or montychoice == choice:
montychoice = random.choice(doors)
#if the player's door is a car, he losses
if choice == 'car':
losses += 1
print 'goat'
elif choice == 'goat':
wins += 1
print 'car'
print "Switching wins: %d" % wins
print "Switching loses: %d" % losses
problem(100)
The problem isn't with the for-loop, but with the while loop.
In order for your while loop to break, montychoice would have to equal car AND the player's choice. But what if the player's choice isn't car, but it's goat? The while-loop will never break.
I think you want and and not or for your while loop. That way, if either condition isn't met, the loop breaks.
The problem is this loop
while montychoice != 'car' or montychoice == choice:
montychoice = random.choice(doors)
Once the player has picked the car, this says that whether monty picks a car or not a car, he has to pick another choice. So he keeps on picking forever, and you don't get any further in your script.

Can't figure out how to make a python coin toss program loop back to a certain point once the whole process of the toss has been completed

I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.
Here is my code:
import random
def main():
name = eval(input("Hello user, please enter your name: "))
print("Hello", name ,"This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N):")
if yn == Y:
elif yn == N:
print("Ok have a nice day!")
heads = 0
tails = 0
count = tails + heads
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
elif coin == 2:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
main()
Here is the sample output that I'm looking for:
Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!
I think you should say on line 6 if yn == 'Y' and not if yn == Y. You treat Y as a variable while it is actually a string from the input.
To run your coin toss simulation multiple times you can put it inside a while loop.
Your if yn == Y: test won't work because you haven't defined the variable Y, so when Python tries to execute that line you get a NameError. What you actually should be doing there is to test the value of yn against the string 'Y'.
I've made a couple of other minor adjustments to your code. I got rid of that potentially dangerous eval function call, you don't need it. I've also made a loop that asks for the desired flip count; we break out ofthe loop when count is a positive number.
import random
def main():
name = input("Hello user, please enter your name: ")
print("Hello", name , "This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
while True:
heads = tails = 0
while True:
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
else:
break
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
else:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
yn = input("Would you like to run another coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
main()
This code is for Python 3. On Python 2 you should use raw_input in place of input, and you should also put
from future import print_function
at the top of the script so you get the Python 3 print function instead of the old Python 2 print _statement.
There are several improvements that can be made to this code. In particular, it should handle a non-integer being supplied for the count. This version will just crash if it gets bad input. To learn how to fix that, please see Asking the user for input until they give a valid response.

Can't repeat what is asked in my code

I'm creating a text-based adventure game in Python 3.4.3 and I can't figure out how to make the code repeat a question. There's a bunch of narration before this, if that helps understand what's going on at all.
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")
str = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
print(" ")
if str in ("d"):
print("You see your combat boots and the grassy ground below your feet. ")
if str in ("l"):
print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
if str in ("r"):
print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
if str in ("u"):
print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
if str in ("b"):
print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
print("It's a bit unsettling.")
else:
print("Try that again")
I want the code to repeat the question to the user, until they've answered every possible answer and move on to the next question. I also want it to repeat the question when they get else. How do I do this?
Don't use str as a variable name, it will shadow an important builtin and cause weird problems.
Use a while loop to restrict the output to valid options.
valid_choices = ('d', 'l', 'r', 'u', 'b',)
choice = None
while choice not in valid_choices:
text = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
choice = text.strip()
if choice == 'd':
print ('...')
elif choice == 'u':
print ('...')
See also:
string.strip
tuples
None
Basically you can put your question in a loop and iterate through it until you enter one of the desired 'if' case. I have modified your code as below. Please have a look
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")
while True:
str = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
print(" ")
if str in ("d"):
print("You see your combat boots and the grassy ground below your feet. ")
break
if str in ("l"):
print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
break
if str in ("r"):
print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
break
if str in ("u"):
print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
break
if str in ("b"):
print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
print("It's a bit unsettling.")
break
else:
print("Try that again")
Do something like this:
answered = False
while not answered:
str = input("Question")
if str == "Desired answer":
answered = True
Here's how I would do this; explanation is in the comments:
# Print out the start text
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")
# Use a function to get the direction; saves some repeating later
def get_direction():
answer = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
print(" ")
return answer
# Keep running this block until the condition is False.
# In this case, the condition is True, so it keeps running forever
# Until we tell Python to "break" the loop.
while True:
# I changed "str" to "answer" here because "str" is already a Python
# built-in. It will work for now, but you'll get confused later on.
answer = get_direction()
if answer == "d":
print("You see your combat boots and the grassy ground below your feet. ")
# Stop the loop
break
elif answer == "l":
print("The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...")
break
elif answer == "r":
print("The forest is warm and inviting that way, you think you can hear a distant birds chirp.")
break
elif answer == "u":
print("The blue sky looks gorgeous, a crow flies overhead... that's not a crow...")
print("It's a Nevermore, an aerial Grim. You stand still until it passes.")
break
elif answer == "b":
print("the grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.")
print("Mount Glenn, one of the most Grim-infested places in all of Remnant.")
print("It's a bit unsettling.")
break
else:
print("Try that again")
# NO break here! This means we start over again from the top
Now, none of this scales very well if you add more than a few directions;
because I assume that after you go "right" you want a new question, so that's a
new loop inside the loop, etc.
# The start text
print("\n\n\n\n\nYou awake to find yourself in the center of a clearing in a forest.")
print("You stand up and decide to take a look around.")
# Use a function to get the direction
def get_direction():
answer = input("Which direction do you steer your head? d= down, l= left, r= right, u= up, b= behind you: ")
print(" ")
return answer
# Use a function to store a "location" and the various descriptions that
# apply to it
def location_start():
return {
'down': [
# Function name of the location we go to
'location_foo',
# Description of this
'You see your combat boots and the grassy ground below your feet.'
],
'left': [
'location_bar',
'The forest trees grow thicker and darker that way. You stare into the shadows and feel... cold...'
],
'right': [
'location_other',
'The forest is warm and inviting that way, you think you can hear a distant birds chirp.'
],
'up': [
'location_more',
"The blue sky looks gorgeous, a crow flies overhead... that's not a crow...\n" +
"It's a Nevermore, an aerial Grim. You stand still until it passes."
],
'behind': [
'location_and_so_forth',
"The grass slowly grows to dirt as the area falls into a mountain cliff. You now know where you are.\n" +
"Mount Glenn, one of the most Grim-infested places in all of Remnant.\n" +
"It's a bit unsettling."
],
}
# And another location ... You'll probably add a bunch more...
def location_foo():
return {
'down': [
'location_such_and_such',
'desc...'
],
}
# Store the current location
current_location = location_start
# Keep running this block until the condition is False.
# In this case, the condition is True, so it keeps running forever
# Until we tell Python to "break" the loop.
while True:
# Run the function for our current location
loc = current_location()
answer = get_direction()
if answer == ("d"):
direction = 'down'
elif answer == ("l"):
direction = 'left'
elif answer == ("r"):
direction = 'right'
elif answer == ("u"):
direction = 'up'
elif answer == ("b"):
direction = 'behind'
else:
print("Try that again")
# Continue to the next iteration of the loop. Prevents the code below
# from being run
continue
# print out the key from the dict
print(loc[direction][1])
# Set the new current location. When this loop starts from the top,
# loc = current_location() is now something different!
current_location = globals()[loc[direction][0]]
Now, this is just one way of doing it; one downside here is that you'll need
to repeat the descriptions for the locations if you want to allow the player to
approach one location from different directions. This may not apply to your
adventure game (the original adventure doesn't allow this, if I remember
correctly).
You can fix that quite easily, but I'll leave that as an exercise to you ;-)

Storing a dictionary generated in the loop and reusing it in a different loop assuming it exists

My task is to produce a word game.
The code is rather simple and is defined as follows( ignore the undefined helper function, which will not appear for the sake of brevity):
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, tell them their input was invalid.
2) When done playing the hand, repeat from step 1
"""
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
n=7
previous_hand={}
hand=dealHand(n)
while choice!= False:
previous_hand=hand.copy()
if choice=='n':
playHand(hand, wordList, n)
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
elif choice=='r':
if len(previous_hand)==0:
print 'You have not played a hand yet. Please play a new hand first!'
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
else:
playHand(previous_hand, wordList,n)
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
elif choice=='e':
break
else:
print 'Invalid command.'
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
Everything seems to be working fine except that 'r' bit. The main trick of this game is that a player can choose to replay a previous hand by inputting 'r'. Say player started a game, played one hand and then want to repeat exactly same hand (all the letters dealt are the same as previously dealt), and the game allows him/her to do so if a player input 'r'.
Something like this:
Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: tot
"tot" earned 9 points. Total: 9 points
Current Hand: p z u t
Enter word, or a "." to indicate that you are finished: .
Goodbye! Total score: 9 points.
Enter n to deal a new hand, r to replay the last hand, or e to end game: r
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: top
"top" earned 15 points. Total: 15 points
However, my code is not working properly on that bit. Everything else is working fine except that. I do not understand how to make a copy of the initial hand, story and then reuse it if player choose 'r'.
This is from a looong time ago but should work for your M.I.T pset:
def playGame(wordList):
hand = None
legalIn = ['r','e','n']
while True:
user = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
if user not in legalIn:
print "Invalid word."
continue
#if user inputs r but there have been no hands played yet
elif user == 'r' and hand is None:
print "You have not played a hand yet. Please play a new hand first!"
elif user == 'n':
hand = dealHand(n)
playHand(hand,wordList,n)
elif user == 'e': # exit game if player inputs e.
break
else:
playHand(hand,wordList, n)
def playHand(hand, wordList, n):
# Keep track of the total score
totalScore = 0
c = calculateHandlen(hand)
# As long as there are still letters left in the hand:
while True:
if c == 0:
print "Run out of letters. Total score: {} points.".format(totalScore)
break
# Game is over if ran out of letters), so tell user the total score
# Display the hand
displayHand(hand)
# Ask user for input
word = raw_input("Enter word, or a '.' to indicate that you are finished: ") # Ask user for input
word = word.lower()
# If the input is a single period:
if word == '.':
# End the game (break out of the loop)
print "Goodbye! Total score: {} points.".format(totalScore)
break
# Otherwise (the input is not a single period):
# If the word is not valid:
elif not isValidWord(word,hand,wordList):
# Reject invalid word (print a message followed by a blank line)
print "Invalid word, please try again."
print
# Otherwise (the word is valid):
else:
hand = updateHand(hand,word)
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
getWordScore(word,n)
totalScore += getWordScore(word,n)
print "{} earned {} points.: {}.".format(word,getWordScore(word,n),totalScore)
# Update the hand
c = calculateHandlen(hand)
Here's how I'd do it. There's only a single variable, hand, which is only modified if we're playing a new hand. If we're replaying the previous hand, we just leave it be (unless it's None, in that case we reject the input):
hand = None
while True:
choice = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if choice == "n": # deal a new hand
hand = dealHand(n)
elif choice == "r": # reuse the old hand, if there was one
if hand is None:
print 'You have not played a hand yet. Please play a new hand first!'
continue
elif choice == "e": # exit
break
else: # any other input
print 'Invalid command.'
continue
playHand(hand) # actually play here

Categories

Resources