Looping the output of the poker programme - python

I would like to loop my poker program 10 times and see how much money the program makes. This is the output I got and then I have to run it again, but the program does not remind the amount of money earned from the previous round. Do you guys have any suggestions?
Dealer has:
D9
Player1, you have:
['HK', 'DQ']
The amount of money player has won so far
0
What would you like to do? H: Hit me, S: Stand? S
Player wins with 20points
Dealer Busted and has: ['D9', 'C3', 'S5']or17points
Player has won : 2euros
Process finished with exit code 0
And I would like to have an extra line with Total earned money at the bottom and the program asks me again the question if I would like to do it again.
Where should I start?
Code
from random import shuffle
def card():
card = []
for speci in ['H', 'D', 'S', 'C']:
for number in ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']:
card.append(speci+number)
shuffle(card)
return card
def pointcount(mycards):
counting = 0
acecount = 0
for i in mycards:
if(i[1] == 'J' or i[1] == 'Q' or i[1] == 'K' or i[1] == 'T'):
counting += 10
elif(i[1] != 'A'):
counting += int(i[1])
else:
acecount += 1
if(acecount == 1 and counting >= 10):
counting += 11
elif(acecount != 0):
counting += 1
return counting
def createplayinghands(mydeck):
dealerhand = []
playerhand = []
dealerhand.append(mydeck.pop())
dealerhand.append(mydeck.pop())
playerhand.append(mydeck.pop())
playerhand.append(mydeck.pop())
while(pointcount(dealerhand) <= 16):
dealerhand.append(mydeck.pop())
return [dealerhand, playerhand]
game = ""
mycard = card()
hands = createplayinghands(mycard)
dealer = hands[0]
player = hands[1]
money = 0
while(game != "exit"):
dealercount = pointcount(dealer)
playercount = pointcount(player)
print("Dealer has:")
print(dealer[0])
print("Player1, you have:")
print(player)
print("The amount of money player has won so far")
print(money)
if(playercount == 21):
money += 3
print("Blackjack Player wins")
print("Player has won: " + str(money) + "euros")
break
elif(playercount > 21):
money += 0
print("player Busts with " + str(playercount) + "points")
print("Player has won: " + str(money) + "euros")
break
elif(dealercount > 21):
print("Dealer Busts with " + str(dealercount) + "points")
print("Player has won: " + str(money) + "euros")
break
game = input("What would you like to do? H: Hit me, S: Stand? ")
if(game == 'H'):
player.append(mycard.pop())
elif(dealercount > 21):
money += 2
print("Player wins with " + str(playercount) + "points")
print("Dealer has: " + str(dealer) + "or" + str(dealercount) + "points")
print("Player has won : " + str(money) + "euros")
break
elif(playercount > dealercount):
money += 2
print("Player wins with " + str(playercount) + "points")
print("Dealer Busted and has: " + str(dealer) + "or" + str(dealercount) + "points")
print("Player has won : " + str(money) + "euros")
break
elif(playercount == dealercount):
money += 2
print("Tie Player with " + str(playercount) + "points")
print("Dealer has: " + str(dealer) + " or " + str(dealercount) + "poi nts")
print("Player has won : " + str(money) + "euros")
break
else:
money += 0
print("Dealer wins")
print("Dealer has: " + str(dealer) + "or" + str(dealercount) + "points")
print("Player has won : " + str(money) + "euros")
break

You break at the end of each hand which forces you out of the loop. If you remove the break commands, it will then loop around and go back to the start. After removing the break, you need to say
if (game != 'H'):
# This loop was not a "Hit Me"
game = input("What would you like to do? Deal or exit? ")
Since you did not count the cards after reading in game, you will get the wrong count values as well.
You need to redo the code to
Count the initial points for the deal
Decide whether to stand or Hit
Have the dealer decide whether to stand or hit.
Decide if the hand is over
If the hand is over, add the results to the money of the winner (and/or subtract from the loser)
If the hand is over, ask whether to deal or exit
If the choice is deal, go back to the beginning
If the hand is not over go back to step 2

If you want to run the game continually comment the break after every if-loop
if dealercount > 21:
money = money + 2
print("Player wins with " + str(playercount) + "points")
print("Dealer has: " + str(dealer) + "or" + str(dealercount) + "points")
print("Player has won : " + str(money) + "euros")
# break <----- breaking out of your while loop

Related

For loop is executing twice, but only returning a value once

My code is executing mostly how I want it to but when it prints my values from my function it is doubling the amount of times that the function code is ran. I only want 10 interations but it is printing 20. I would just lower the range to 5 but then it throws off my final score in my block of code that displays who won the most rounds. How can I stop the function code from running twice? TIA
import random
import time
answer = input("Play the game?")
winsP1 = 0
winsP2 = 0
def determineWinner(winsP1, winsP2):
for wins in range(10):
from random import randint
player1 = randint(1,10)
player2 = randint(1,10)
#time.sleep(1)
print("Player 1:", player1)
#time.sleep(1)
print("Player 2:", player2)
#time.sleep(1)
if player1==player2:
print("This round is a tie!")
winsP1 += 1
winsP2 += 1
elif player1>player2:
print("Player 1 wins this round!")
winsP1 += 1
elif player2>player1:
print("Player 2 wins this round!")
winsP2 += 1
return winsP1, winsP2
winsP1, winsP2 = determineWinner(winsP1 = winsP1, winsP2 =
winsP2)
if answer == "y" or answer == "Y" or answer == "yes" or answer == "Yes":
determineWinner(winsP1, winsP2)
if winsP1>winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 1 wins with a score of", str(winsP1) + "!")
print()
elif winsP2>winsP1:
print()
print("The score totals are:")
print("Player One: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 2 wins with a score of", str(winsP2) + "!")
print()
elif winsP1==winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("It's a tie!")
print()
It's running 20 times since determineWinner is called twice. Once here winsP1, winsP2 = determineWinner(winsP1 = winsP1, winsP2 = winsP2) and the next time within the if block. You could set winsP1 = winsP2 = 0 instead so as to have it start at a neutral state.
Not entirely sure if you'd like to call the function twice; But that's the main reason for the 20 prints you see.
import time
answer = input("Play the game?")
winsP1 = 0
winsP2 = 0
def determineWinner(winsP1, winsP2):
for wins in range(10):
from random import randint
player1 = randint(1,10)
player2 = randint(1,10)
#time.sleep(1)
print("Player 1:", player1)
#time.sleep(1)
print("Player 2:", player2)
#time.sleep(1)
if player1==player2:
print("This round is a tie!")
winsP1 += 1
winsP2 += 1
elif player1>player2:
print("Player 1 wins this round!")
winsP1 += 1
elif player2>player1:
print("Player 2 wins this round!")
winsP2 += 1
return winsP1, winsP2
winsP1 = winsP2 = 0
if answer == "y" or answer == "Y" or answer == "yes" or answer == "Yes":
winsP1, winsP2 = determineWinner(winsP1, winsP2)
if winsP1>winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 1 wins with a score of", str(winsP1) + "!")
print()
elif winsP2>winsP1:
print()
print("The score totals are:")
print("Player One: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 2 wins with a score of", str(winsP2) + "!")
print()
elif winsP1==winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("It's a tie!")
print()

I don't know how to make a while loop last until a list doesn't have any values left

I am trying to recreate the card game "War" in python and cant figure out how to loop the code under the comment until every value in the list is gone. So basically the code generates a shuffled deck of cards and pops the cards from the list. I want to have the code repeat until all the cards have been popped from the deck and I have no idea how to do that.
import random
def shuffled_deck():
deck = list(range(2, 15)) *4
random.shuffle(deck)
return deck
userdeck = shuffled_deck()
print("welcome to War!")
user1 = input("Player-1 name: ")
user2 = input("Player-2 name: ")
u1points = 0
u2points = 0
drawturns = 0
# - I want to loop the segment of code under this comment
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
else:
print("It's a draw, try again.")
while u1card == u2card:
drawturns +=1
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
u1points + drawturns
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
u1points + drawturns
else:
print("It's a draw, try again.")
if u1card == u2card == False:
drawturns = 0
break
You can do:
while len(userdeck)>0:
or, you can write smartly as:
while userdeck:
This is because an empty list is considered as False, whereas a non empty list is considered as True. So, when userdeck is empty, while loop will assume it to be False case, so the loop will stop. This same concept can also be applied for if statements.

Can you print either the name of the boolean or the result of a parameter?

I'm supposed to be writing code for some games of chance, and I'm working on a coin toss game. I have this almost working completely but the only thing I'm still stuck on is printing what the actual coin flip was.
When someone bets I want the result to say either
Winner winner, the coin landed on heads/tails!
You now have $n left to gamble.
or
Ohh- tough luck. The coin landed on heads/tails, better luck next time!
You now have $n left to gamble.
where it keeps a running tally of the bets. I've tried it to print the result in two ways, I'll post the full current code and a snippet of the other way I tried. The best I can get is a result saying the coin landed on true/false or 1/2 and I can't figure out how to get the result I'm looking for!
Thanks in advance.
Full code:
import random
num = random.randint(1, 2)
money = 100
heads = num == 1
tails = num == 2
# heads = num % 2 == 0
# tails = num % 2 == 1
#Write your game of chance functions here
def coin_flip(call, bet):
global money
win = heads and call == heads or tails and call == tails
lose = heads and call == tails or tails and call == heads
if win:
money += bet
print("Winner winner, the coin landed on " + str(num) + "!")
print("You now have $" + str(money) + " left to gamble.")
else:
money += -bet
print("Ohh- tough luck. The coin landed on " + str(num) +", better luck next time!")
print("You now have $" + str(money) + " left to gamble.")
#Call your game of chance functions here
coin_flip(heads, 30)
This yields 1/2 as opposed to heads/tails
And with this change:
if win:
money += bet
print("Winner winner, the coin landed on " + str(call) + "!")
print("You now have $" + str(money) + " left to gamble.")
else:
money += -bet
print("Ohh- tough luck. The coin landed on " + str(call) +", better luck next time!")
print("You now have $" + str(money) + " left to gamble.")
I get that the coin flip is True/False.
I'm mostly sure I understand why these aren't giving me the result I want but I'm not sure what needs to be done to get what I do want.
You can use a simple dict
di = {1:"Heads",2:"Tails"}
Then,
print(di[num])
Try:
import random
money = 100
heads = 1
tails = 2
# heads = num % 2 == 0
# tails = num % 2 == 1
#Write your game of chance functions here
def coin_flip(call, bet):
num = random.randint(1, 2)
valArray = ["heads", "tails"]
global money
win = num == call
lose = num != call
if win:
money += bet
print("Winner winner, the coin landed on " + valArray[num-1] + "!")
print("You now have $" + str(money) + " left to gamble.")
else:
money += -bet
print("Ohh- tough luck. The coin landed on " + valArray[num-1] +", better luck next time!")
print("You now have $" + str(money) + " left to gamble.")
#Call your game of chance functions here
coin_flip(heads, 30)

def functions repeat themselves twice per (while) loop, even though I only called them once each

I am making a game for a school project, where there are two players, rolling 2 dice each, and the scores are counted after each round. I made functions for the dice rolling for each player, but when I call this in the while loop (which runs 5 times for 5 rounds), it loops 5 times, but each time, it repeats the functions twice for some reason. I read it over thoroughly, but I couldn't find where i went wrong. I think it might have something to do with the if elif elif statments in the functions but I am not sure and don't know how to fix it. I would appreciate any help very much as I need to finish this and hand it in. Thanks in advance.
import random
#Function for Player ones rolls
def rollP1():
#Player 1 rolls twice
print("\n\nPlayer 1's rolls:")
rollOne1 = random.randint(1,6)
rollTwo1 = random.randint(1,6)
#Checking if player 1 has a double, even total, or odd total
#if player has a double, player gets a bonus roll
if rollOne1 == rollTwo1:
print("You got a double. ", rollOne1, "and ", rollTwo1,", have a
bonus
roll!")
rollThree1 = random.randint(1,6)
print(rollThree1)
rollTotal1 = rollOne1 + rollTwo1 + rollThree1
print("Your total score for this round is ", rollTotal1, ". Well
Done.")
#if player gets an even total, score increases by 10
elif (rollOne1 + rollTwo1)%2 == 0:
rollTotal1 = rollOne1 + rollTwo1 + 10
print("You got ", rollOne1, " and ", rollTwo1, ", your total is an
even number, plus 10 points. Your total for this round is now ",
rollTotal1, ". Well Done.")
#if player gets an odd total, score decreases by 5
elif (rollOne1 + rollTwo1)%2 != 0:
rollTotal1 = (rollOne1 + rollTwo1) - 5
print("You got ", rollOne1, " and ", rollTwo1, ". Unlucky, your
total is an odd number. Minus 5 points Your total for this round is
now ", rollTotal1, ". Better luck next time.")
#Returning the total score for Player one for the round.
return rollTotal1
#Function for Player twos' rolls
def rollP2():
#Player 2 rolls twice
print("\nPlayer 2's rolls:")
rollOne2 = random.randint(1,6)
rollTwo2 = random.randint(1,6)
#Checking if player 2 has a double, even total, or odd total
#if player has a double, player gets a bonus roll
if rollOne2 == rollTwo2:
print("You got a double. ", rollOne2," and", rollTwo2, ", have a
bonus roll!")
rollThree2 = random.randint(1,6)
print(rollThree2)
rollTotal2 = rollOne2 + rollTwo2 + rollThree2
print("Your total score for this round is ", rollTotal2, ". Well
Done.")
#if player gets an even total, score increases by 10
elif (rollOne2 + rollTwo2)%2 == 0:
rollTotal2 = rollOne2 + rollTwo2 + 10
print("You got ", rollOne2, " and ", rollTwo2, ". Your total is an
even number, plus 10 points. Your total for this round is now ",
rollTotal2, ". Well Done.")
#if player gets an odd total, score decreases by 5
elif (rollOne2 + rollTwo2)%2 != 0:
rollTotal2 = (rollOne2 + rollTwo2) - 5
print("You got ", rollOne2, " and ", rollTwo2, ". Unlucky, your
total is an odd number. Minus 5 points Your total for this round is
now ", rollTotal2, ". Better luck next time")
#Returning the total score for Player two for the round.
return rollTotal2
Total1 = 0
Total2 = 0
rounds = 1
while rounds < 6:
print("Round ", rounds)
rollP1()
rollP2()
rollTotal1 = rollP1()
rollTotal2 = rollP2()
print("Player 1's score for this round is ", rollTotal1, " and player
2's score for this round is ", rollTotal2)
Total1 = Total1 + rollTotal1
Total2 = Total2 + rollTotal2
print("Player 1's total so far is ", Total1, ", Player 2's total so far
is ", rollTotal2, ". Round Over\n\n")
rounds = rounds + 1
Try with this. just took off the second calling.
import random
#Function for Player ones rolls
def rollP1():
#Player 1 rolls twice
print("\n\nPlayer 1's rolls:")
rollOne1 = random.randint(1,6)
rollTwo1 = random.randint(1,6)
#Checking if player 1 has a double, even total, or odd total
#if player has a double, player gets a bonus roll
if rollOne1 == rollTwo1:
print("You got a double. ", rollOne1, "and ", rollTwo1,", have a bonus roll!")
rollThree1 = random.randint(1,6)
print(rollThree1)
rollTotal1 = rollOne1 + rollTwo1 + rollThree1
print("Your total score for this round is ", rollTotal1, ". Well Done.")
#if player gets an even total, score increases by 10
elif (rollOne1 + rollTwo1)%2 == 0:
rollTotal1 = rollOne1 + rollTwo1 + 10
print("You got ", rollOne1, " and ", rollTwo1, ", your total is an even number, plus 10 points. Your total for this round is now ", rollTotal1, ". Well Done.")
#if player gets an odd total, score decreases by 5
elif (rollOne1 + rollTwo1)%2 != 0:
rollTotal1 = (rollOne1 + rollTwo1) - 5
print("You got ", rollOne1, " and ", rollTwo1, ". Unlucky, total is an odd number. Minus 5 points Your total for this round now ", rollTotal1, ". Better luck next time.")
#Returning the total score for Player one for the round.
return rollTotal1
#Function for Player twos' rolls
def rollP2():
#Player 2 rolls twice
print("\nPlayer 2's rolls:")
rollOne2 = random.randint(1,6)
rollTwo2 = random.randint(1,6)
#Checking if player 2 has a double, even total, or odd total
#if player has a double, player gets a bonus roll
if rollOne2 == rollTwo2:
print("You got a double. ", rollOne2," and", rollTwo2, ", have a bonus roll!")
rollThree2 = random.randint(1,6)
print(rollThree2)
rollTotal2 = rollOne2 + rollTwo2 + rollThree2
print("Your total score for this round is ", rollTotal2, ". Well Done.")
#if player gets an even total, score increases by 10
elif (rollOne2 + rollTwo2)%2 == 0:
rollTotal2 = rollOne2 + rollTwo2 + 10
print("You got ", rollOne2, " and ", rollTwo2, ". Your total is an even number, plus 10 points. Your total for this round is now ", rollTotal2, ". Well Done.")
#if player gets an odd total, score decreases by 5
elif (rollOne2 + rollTwo2)%2 != 0:
rollTotal2 = (rollOne2 + rollTwo2) - 5
print("You got ", rollOne2, " and ", rollTwo2, ". Unlucky, your total is an odd number. Minus 5 points Your total for this round is now ", rollTotal2, ". Better luck next time")
#Returning the total score for Player two for the round.
return rollTotal2
Total1 = 0
Total2 = 0
rounds = 1
while rounds < 6:
print("Round ", rounds)
rolledP1 = rollP1()
rolledP2 = rollP2()
rollTotal1 = rolledP1
rollTotal2 = rolledP1
print("Player 1's score for this round is ", rollTotal1, " and player 2's score for this round is ", rollTotal2)
Total1 = Total1 + rollTotal1
Total2 = Total2 + rollTotal2
print("Player 1's total so far is ", Total1, ", Player 2's total so far is ", rollTotal2, ". Round Over\n\n")
rounds = rounds + 1

Python Blackjack game questions

I'm programming a type of Blackjack game. In this game I want to make it so the dealer and the player each have 100 health and if they lose a hand then they lose 10 health. This goes on until one of them reaches 0 health. I can't figure out how to add health to the game.
Below is the game as of right now:
import random
newgame = 0
def get_card():
#I did random from 1,11 to reduce card counting.
return random.randint(1, 11)
def player():
blackjack = False
total = 0
print('************ YOUR TURN ************')
card1 = get_card()
card2 = get_card()
total = card1 + card2
print("Cards: " + str(card1) + " " + str(card2))
print("Total: " + str(total))
if total is 21:
blackjack = True
while total < 21:
option = raw_input('Type "S" to stay or "H" to hit ')
if option == 's' or option == 'S':
break
card1 = get_card()
print("\nDraws: " + str(card1))
total += card1
print("Total: " + str(total))
return total, blackjack
def dealer():
print("\n********** DEALER'S TURN **********")
total = 0
card1 = get_card()
card2 = get_card()
total = card1 + card2
print("Cards: " + str(card1) + " " + str(card2))
print("Total: " + str(total))
while total <= 16:
raw_input('Press <enter> to continue ...')
card1 = get_card()
print("\nDraws: " + str(card1))
total += card1
print("Total: " + str(total))
return total
def main():
play_again = True
while play_again:
player_total, blackjack = player()
player_wins = False
dealer_wins = False
if blackjack:
print('Blackjack!')
player_wins = True
if player_total > 21:
print('Bust!')
dealer_wins = True
if player_wins is False and dealer_wins is False:
dealer_total = dealer()
if dealer_total > 21:
print('Bust!')
player_wins = True
elif player_total > dealer_total:
player_wins = True
else:
dealer_wins = True
print("\n********** GAME OVER **********")
if player_wins:
print('You win!')
elif dealer_wins:
print('Dealer wins!')
while True:
again = raw_input('Type "P" to play again or "Q" to quit: ')
if again.upper() == "Q":
print("Game ended.")
play_again = False
break
elif again.upper() == "P":
break
main()
You would definitely want to use an object oriented approach if you want to include several players. Refer to this page if you are unfamiliar with it: https://www.tutorialspoint.com/python/python_classes_objects.htm
If you want to just add it to the main function, I would suggest adding a hp = 100 variable. Everytime it's a bust, just deduct 10 from it. If hp == 0, end the game.
just set health to 100 for player and dealer and just take off 10 each time they lose. just decrement player health under dealer wins and dealer health under player wins. fairly simple really

Categories

Resources