Python Blackjack game questions - python

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

Related

Blackjack python game

I have to create a blackjack game in python in which the user inputs the number of decks that are being used and the amount of money the user wants to bet. The rules are: o The player places his bet (should be read from the keyboard).
o The dealer and player are dealt two cards (one card of the dealer should be hidden).
o If the player has 21 he wins his bet; else if the dealer has 21 then the dealer wins and the player loses his bet.
o The player can only select to draw a new card (hit) or pass. Repeat until the player passes or busts. If the player goes above 21 then he busts.
o Then the dealer draws cards (automatically) until he either busts or reaches 17 or higher.
o Values of cards: A= 1 or 11 (the highest that does not bust you) and J=Q=K=10
o Note: in blackjack there are more actions: insurance, double, split; those are not required to be implemented as they would make the code you have to produce much, much longer and harder
I will show you my code below when I tried to run it, it said that the name "total" is not defined on the function game, but earlier on I have already defined it. I don't know how can i fix it.
import random
N=int(input("Please enter number of decks of cards used: "))
deck= [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
wins=0
losses=0
chip_pool = 100
bet = 1
def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card=deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def play_again():
again = input("Do you want to play again? (Y/N) : ").lower()
if again == "y":
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
game()
else:
print("Thank you for playing.")
exit()
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
def hit(hand):
card = deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def print_results(dealer_hand, player_hand):
clear()
print("\n WELCOME TO BLACKJACK!\n")
print("The dealer has a " + str(dealer_hand) + "for a total of" + str(total(dealer_hand)))
print("You have a" + str(player_hand) + "for a total of" + str(total(player_hand)))
def blackjack(dealer_hand, player_hand):
global wins
global losses
if total(player_hand) == 21:
print_results(player_hand,dealer_hand)
print("Congratulations! You got a blackjack.\n")
wins = wins + 1
play_again()
elif total(dealer_hand) == 21:
print_results(dealer_hand,player_hand)
print("Sorry you lose. The dealer got a blackjack.\n")
chip_pool -= bet
loses = loses + 1
play_again()
def score(dealer_hand,player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print("Congratulations! You got a blackjack1\n")
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print("Sorry you lose. The dealer go a blackjack\n")
elif total(player_hand) > 21:
print_results(dealer_hand, player_hand)
print("Sorry, you busted. You lose.\n")
elif total(dealer_hand) > 21:
print_results(dealer_hand, player_hand)
print("Dealer busts. You win!\n")
chip_pool += bet
elif total(player_hand) < total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Sorry, the score is not higher than the dealer. You lose.\n")
chip_pool -= bet
elif total(player_hand) > total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Congratulations. Your score is higher than the dealer. You win.\n")
chip_pool += bet
elif total(player_hand) == total(dealer_hand):
print_results(playe_hand, dealer_hand)
print("There is a tie. In a tie dealer always wins!\n")
chip_pool -= bet
def make_bet():
global bet
bet = 0
print("What amount of chips would you like to bet? ")
while bet == 0:
bet_comp = input()
bet_comp = int(bet_comp)
if bet_comp >= 1 and bet_comp <= chip_pool:
bet = bet_comp
else:
print("Invalid bet, you only have" + str(chip_pool) + "remaining")
def game():
choice = 0
print("Welcome to Blackjack!\n")
dealer_hand = deal(deck)
player_hand = deal(deck)
print("The dealer is showing a " +str(dealer_hand[0]))
make_bet()
print("You have a " + str(player_hand))
blackjack(dealer_hand, player_hand)
quit = False
while not quit:
choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
if choice == 'h':
hit(player_hand)
print(player_hand)
if total(player_hand) > 21:
print("You busted")
chip_pool -= bet
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
print(dealer_hand)
if total(dealer_hand) > 21:
print("Dealer busts. You win!")
chip_pool += bet
play_again()
score(dealer_hand, playe_hand)
play_again()
elif choice == "q" :
print("Thank you for playing. Hope you enjoyed!")
quit = True
exit()
if __name__ == "__main__":
game()
You have not defined the function total that you call. Try adding this to your code
def total(array):
total = 0
for card in array:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
However I see some more issues in your code that will need fixing later on! Stand or Quit do nothing currently, and on busting there is an exception thrown since chip_pool never had a value assigned to it
EDIT 1:
You defined a function
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
Similar to what I suggested. Maybe it was just a typo but you need to do the following
Rename the function from total_hand to total OR call total_hand
Change the definition from total_hand() to total_hand(hand)

Adding betting function to dice game and number guess game

I have made a dice roll game on Python 3 but want to add a betting function.
I have tried a few things but I can only play one game. I want the game to have multiple rounds.
How do I make it a game where the player(s) can bet on multiple rounds until money ends at 0, or possibly keep playing until they want to stop?
import random
import time
print("this is a dice roll game")
def main():
player1 = 0
player1wins = 0
player2 = 0
player2wins = 0
rounds = 1
while rounds != 5:
print("Round" + str(rounds))
time.sleep(1)
player1 = dice_roll()
player2 = dice_roll()
print("Player 1 rolled " + str(player1))
time.sleep(1)
print("Player 2 rolled " + str(player2))
time.sleep(1)
if player1 == player2:
print("The round is a draw")
elif player1 > player2:
player1wins += 1
print("Player 1 wins the round")
else:
player2wins += 1
print("Player 2 wins the round")
rounds = rounds + 1
if player1wins == player2wins:
print("The game ended in a draw")
elif player1wins > player2wins:
print("Player 1 wins the game, Rounds won: " + str(player1wins))
else:
print("Player 2 wins the game, Rounds won: " + str(player2wins))
def dice_roll():
diceroll = random.randint(1,6)
return diceroll
main()
Adding to the comment by John Coleman, you can modify your while loop so that it does not end when the number of rounds is different to 5, something like:
while True:
// Rest of code...
if moneyP1 <= 0 OR moneyP2 <=0:
print("Someone ran out of money")
// Implement deciding who won
break
user_confirmation = raw_input("Keep playing? (YES/NO): ")
if user_confirmation == "NO":
break

Run-time error when setting the value of a variable in Python

I want to make an RPG game, and I'm trying to make a system of buying items and potions. What I intended was for the player to get 3 potions of each in the beginning, but you need to buy more to continue with them. My problem is that they keep on resetting every time I call the fight function.
I've tried making them global in the beginning and defining them, but they keep on saying "Referenced before assignment"
def Fight(monster):
global HealPotionsLeft
global WeakPotionsLeft
HealPotionsLeft = 3
WeakPotionsLeft = 3
Potion = ['Yes', 'No']
currentFighter = ""
if myPlayer.dexterity >= monster.dexterity:
currentFighter = myPlayer.name
else:
currentFighter = monster.name
while myPlayer.isDead is not True and monster.isDead is not True:
print(currentFighter + "'s turn!")
print("===========================")
print("Name:", myPlayer.name)
print("Health:", myPlayer.health, "/", myPlayer.maxHealth)
print("===========================")
print("Name:", monster.name)
print("Health:", monster.health, "/", monster.maxHealth)
print("===========================")
if currentFighter == monster.name:
monster.Attack(myPlayer)
currentFighter = myPlayer.name
continue
userInput = ""
validInput = False
while validInput is not True:
print("-Attack")
print("-Spells")
print("-Items")
print("-Flee")
userInput = input()
if userInput == "Attack":
myPlayer.Attack(monster)
break
if userInput == "Spells":
print("TO DO - Spells")
if userInput == "Items":
secure_random = random.SystemRandom()
item = secure_random.choice(Potion)
if item == ('Yes'):
print("You have", HealPotionsLeft, "Potions of Healing Left and", WeakPotionsLeft, "Potions of Damage Left.")
PotionUsage = input("Would you like to use your *Potion of Healing*? y/n")
if PotionUsage == str("n"):
if HealPotionsLeft == 0:
print("You spent too much time trying to get the healing potion so you got attacked! *Out of Healing Potions*.")
break
elif HealPotionsLeft > 0:
if PotionUsage == ("y"):
myPlayer.health = 100
print(myPlayer.name, "Healed to 100 HP!")
HealPotionsLeft = HealPotionsLeft - 1
PotionsLeft()
break
if PotionUsage == str("y"):
if WeakPotionsLeft == 0:
print("You spent too much time trying to get the Potion of Damage so you got attacked! *Out of Potions of Damage*.")
break
elif WeakPotionsLeft > 0:
weakPotion = input("Would you like to use your Potion of Damage? y/n")
if weakPotion == str("y"):
monster.health = monster.health - 20
print(myPlayer.name, "Used their Potion of Damage on" , monster.name, "for 20 damage!")
WeakPotionsLeft = WeakPotionsLeft - 1
PotionsLeft()
break
if item == ('No'):
print("You didn't get to your potions in time!")
break
I expect the potions to go to three when the player goes into battle in the first time, but afterwards when going to battle the amount of potions resets the the amount remaining from last battle.
Outside this Fight() function initialize your potion counts to 3 each. Then pass the current amount of potions in to the Fight() function something like: Fight(monster,Hpots,Wpots) then return the remaining potions to the outer scope with a return(HealPotionsLeft,WeakPotionsLeft)
********* Example Requested: *********
I can not test this code and this is just an example
BattleResults = []
global CurrentHealPotions
global CurrentWeakPotions
CurrentHealPotions = 3
CurrentWeakPotions = 3
def Fight(monster,HealPotionsLeft,WeakPotionsLeft):
Potion = ['Yes', 'No']
currentFighter = ""
if myPlayer.dexterity >= monster.dexterity:
currentFighter = myPlayer.name
else:
currentFighter = monster.name
while myPlayer.isDead is not True and monster.isDead is not True:
print(currentFighter + "'s turn!")
print("===========================")
print("Name:", myPlayer.name)
print("Health:", myPlayer.health, "/", myPlayer.maxHealth)
print("===========================")
print("Name:", monster.name)
print("Health:", monster.health, "/", monster.maxHealth)
print("===========================")
if currentFighter == monster.name:
monster.Attack(myPlayer)
currentFighter = myPlayer.name
continue
userInput = ""
validInput = False
while validInput is not True:
print("-Attack")
print("-Spells")
print("-Items")
print("-Flee")
userInput = input()
if userInput == "Attack":
myPlayer.Attack(monster)
break
if userInput == "Spells":
print("TO DO - Spells")
if userInput == "Items":
secure_random = random.SystemRandom()
item = secure_random.choice(Potion)
if item == ('Yes'):
print("You have", HealPotionsLeft, "Potions of Healing Left and", WeakPotionsLeft, "Potions of Damage Left.")
PotionUsage = input("Would you like to use your *Potion of Healing*? y/n")
if PotionUsage == str("n"):
if HealPotionsLeft == 0:
print("You spent too much time trying to get the healing potion so you got attacked! *Out of Healing Potions*.")
break
elif HealPotionsLeft > 0:
if PotionUsage == ("y"):
myPlayer.health = 100
print(myPlayer.name, "Healed to 100 HP!")
HealPotionsLeft = HealPotionsLeft - 1
PotionsLeft()
break
if PotionUsage == str("y"):
if WeakPotionsLeft == 0:
print("You spent too much time trying to get the Potion of Damage so you got attacked! *Out of Potions of Damage*.")
break
elif WeakPotionsLeft > 0:
weakPotion = input("Would you like to use your Potion of Damage? y/n")
if weakPotion == str("y"):
monster.health = monster.health - 20
print(myPlayer.name, "Used their Potion of Damage on" , monster.name, "for 20 damage!")
WeakPotionsLeft = WeakPotionsLeft - 1
PotionsLeft()
break
if item == ('No'):
print("You didn't get to your potions in time!")
break
if myPlayer.isDead is True
result="You have been defeated!"
else
result="You have slain the Beast!"
BattleEnd=[result, HealPotionsLeft, WeakPotionsLeft]
return(BattleEnd)
A call to this function might look like:
BattleResults = Fight("Your Monster Reference Here",CurrentHealPotions,CurrentWeakPotions)
Then assign the new values to potions:
CurrentHealPotions = BattleResults[1]
CurrentWeakPotions = BattleResults[2]

Print the cards that I used after I typed yes to play again

I want this game to start each hand with the cards left over from the previous hand. Instead, it begins with a complete, newly-shuffled deck. How can I fix it to just continue?
I updated the code based in your advice but it doesnt display my show card thanks a lot
import random, sys
suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}
class Card:
def __init__(self, suit, pip):
self.suit = suit
self.pip = pip
self.value = pipValues.get(pip)
def __str__(self):
thisCard = ""
thisCard += str(self.pip)
thisCard += str(self.suit)
return (thisCard)
def __repr__(self):
thisCard = ""
thisCard += str(self.pip)
thisCard += str(self.suit)
return (thisCard)
class Player:
def __init__(self):
self.hand = []
self.handTotal = 0
def __str__(self):
printHand = ""
for i in self.hand:
printHand += str(i) + " "
return (printHand)
def __repr__(self):
printHand = ""
for i in self.hand:
printHand += str(i) + " "
return (printHand)
class Deck:
def __init__(self):
self.cardList = []
#for each suit take every card
for i in range(len(suits)):
for j in range(len(pip)):
self.cardList.append(Card(suits[i], pip[j]))
def shuffle(self):
random. shuffle (self.cardList)
def dealOne(self, player):
(player.hand).append(self.cardList[0])
player.handTotal += self.cardList[0].value
del self.cardList[0]
print self.cardList
return self.cardList
def __str__(self):
printString = ""
for i in range(len(self.cardList)):
if i % 13 == 0:
printString += "\n \t"
printString += str(self.cardList[i]) + " "
else:
printString += str(self.cardList[i]) + " "
printString += "\n"
return printString
def showHands(player, opponent):
print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
print ('You show ' + str(player.hand[0]) +str(player.hand[0] ))
def playerTurn(deck, player, other):
#First, check scores to see if either player has a blackjack:
if player.handTotal == 21 or other.handTotal == 21:
if other.handTotal == 21:
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Dealer has " + str(other) + "for a total of 21")
print ("Dealer has a Blackjack! Dealer wins!")
print ("Thanks for playing. Come back again soon! ")
message()
else:
print ("You hold " + str(player) + "for a total of 21")
print ("You have a Blackjack! You win!")
print ("Thanks for playing. Come back again soon! ")
message()
hitOrStand = 0
aces = False
#IF TWO ACES
if player.hand[0].pip == "A" and player.hand[1].pip == "A":
player.hand[0].pipValue = 1
if player.handTotal == 21:
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Blackjack! You win!")
print ("Thanks for playing. Come back soon!")
print()
message()
while hitOrStand != 2:
#check for aces
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print()
hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
while hitOrStand != 1 and hitOrStand != 2:
try:
hitOrStand = int(hitOrStand)
break
except ValueError:
print ("Enter a valid integer \n")
hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
print()
if hitOrStand == 1:
print('Card dealt: ' + str(deck.cardList[0]))
print()
deck.dealOne(player)
#check if an ace was drawn
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
if player.handTotal == 21:
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Blackjack!! You Win!")
print()
print ("Thanks for playing. Come back soon!")
message()
if player.handTotal > 21:
#check for aces
if aces:
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Over 21. Value of ace changed to 1")
#chanlge value of ace and hand
player.handTotal = player.handTotal - 10
for i in player.hand:
if i.pip == "A" and i.value == 11:
i.value = 1
#check for other standard aces
aces = False
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
else:
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("You Bust! Dealer Wins!")
#exit, since you're a loser
print ("Thanks for Playing! Come Back Soon!")
print()
raise SystemExit
if hitOrStand == 2:
print ('You stand at: ' + str(player.handTotal))
print()
print ("Now Dealer's Turn")
print ()
def message():
again = raw_input("Do you want to play again? (Y/N) : ")
if(again == "Y" or again == "y"):
main()
else:
print "\n\n-------Thank you for playing!--------\n\n"
exit()
def opponentTurn(deck, player, other):
if other.handTotal == 21:
raise SystemExit
aces = False
hitOrStand = 0
#IF TWO ACES
if player.hand[0].pip == "A" and player.hand[1].pip == "A":
player.hand[0].pipValue = 1
while hitOrStand != 2:
#check for aces
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
print()
#if blackjack
if player.handTotal == 21:
print ("Dealer has a BlackJack! Dealer Wins!")
break
if player.handTotal <21 and other.handTotal == 21:
print ("Dealer's hand is " + str(player.handTotal) + ". You have a Blackjack! Congratulations! You win! ")
break
if player.handTotal < other.handTotal:
hitOrStand = 1
if player.handTotal >= other.handTotal:
hitOrStand = 2
if hitOrStand == 1:
print("Dealer hits. " + 'Card dealt: ' + str(deck.cardList[0]))
deck.dealOne(player)
#check if an ace was drawn
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
if player.handTotal > 21:
#check for aces
if aces:
print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Over 21. Value of ace changed to 1")
#chanlge value of ace and hand
player.handTotal = player.handTotal - 10
for i in player.hand:
if i.pip == "A" and i.value == 11:
i.value = 1
#check for other standard aces
aces = False
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
else:
print ('Dealer holds ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Dealer Busts! You Win!")
message()
if hitOrStand == 2:
print ("Dealer stands at " + str(player.handTotal))
print ("Your score is " + str(other.handTotal))
print ("Dealer Wins!")
message()
#who won
def main():
cardDeck = Deck()
print ('Initial Deck: ')
print(cardDeck)
cardDeck.shuffle()
print ('Shuffled Deck: ')
print(cardDeck)
keep_playing = True
while keep_playing:
player = Player()
opponent = Player()
#give each player 2 cards, alternating
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
print ('Deck after giving 2 cards each')
print (cardDeck)
#show 1 faceup card for each player
showHands(player,opponent)
#start playing
playerTurn(cardDeck,player, opponent)
opponentTurn(cardDeck, opponent, player)
again = raw_input("Do you want to play again? (Y/N) : ")
keep_playing = again in "Yy"
# Reach here after dropping out of the while loop
print "\n\n-------Thank you for playing!--------\n\n"
main()
Yes, you can have one game continue from where the previous one left off. The current problem is that you call main recursively. This starts over from the beginning, shuffling a full deck, etc.
Instead, you would want a main program something like this:
def main():
cardDeck = Deck()
print ('Initial Deck: ')
print(cardDeck)
cardDeck.shuffle()
print ('Shuffled Deck: ')
print(cardDeck)
keep_playing = True
while keep_playing:
player = Player()
opponent = Player()
#give each player 2 cards, alternating
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
print ('Deck after giving 2 cards each')
print (cardDeck)
#show 1 faceup card for each player
showHands(player,opponent)
#start playing
playerTurn(cardDeck,player, opponent)
opponentTurn(cardDeck, opponent, player)
again = raw_input("Do you want to play again? (Y/N) : ")
keep_playing = again in "Yy"
# Reach here after dropping out of the while loop
print "\n\n-------Thank you for playing!--------\n\n"
This gets rid of your message function and the recursive call to main.
See the repl.it for a complete solution:
There are a lot of issues, here are a few of overarching themes:
If you're having to repeat yourself, you're doing it wrong:
aces = False
#IF TWO ACES
if player.hand[0].pip == "A" and player.hand[1].pip == "A":
player.hand[0].pipValue = 1
#check for aces
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
#check if an ace was drawn
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
#check for aces
if aces:
print ('You hold ' + str(player) + 'for a total of ' + str(player.handTotal))
print ("Over 21. Value of ace changed to 1")
#chanlge value of ace and hand
player.handTotal = player.handTotal - 10
for i in player.hand:
if i.pip == "A" and i.value == 11:
i.value = 1
#check for other standard aces
aces = False
for i in player.hand:
if i.pip == "A" and i.value == 11:
aces = True
Each of those is used twice... I replaced it by letting my players hand decide it's own value:
#property
def handTotal(self):
while sum(card.value for card in self.hand) > 21 and \
any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
for card in self.hand:
if card.pip == 'Ace' and card.value == 11:
card.value = 1
break
return sum(card.value for card in self.hand)
The #property decorator forces it to recalculate every time someone asks for the handTotal.
Telling main you want to keep playing
You need to return a value all the way back to main, in some way. Because you already have some global state variables, I added playing = True, then:
def message():
global playing
again = input("Do you want to play again? (Y/N) : ")
if again.lower() == "n":
print("\n\n-------Thank you for playing!--------\n\n")
playing = False
return True # Tells `turn()` the game is over

Looping the output of the poker programme

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

Categories

Resources