Created
September 17, 2015 10:56
-
-
Save oisdk/94cea52f6b126ad96d06 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def cardName(card): | |
face = {11:"Jack", 12:"Queen", 13:"King"} | |
if card == 1: return "Ace" | |
if card > 10: return face[card] | |
else : return str(card) | |
def hit(hand, card): | |
if card == 1: return (hand[0] + 1, True) | |
elif card > 10: return (hand[0] + 10, hand[1]) | |
else : return (hand[0] + card, hand[1]) | |
def sumHand(hand): | |
if hand[0] > 21 : return "bust" | |
elif hand[0] <= 11 and hand[1]: return hand[0] + 10 | |
else : return hand[0] | |
def deal(hitPred, hand, cards): | |
score = sumHand(hand) | |
while score != 21 and score != "bust" and hitPred(score): | |
card = next(cards) | |
print("Dealt:", cardName(card)) | |
hand = hit(hand, card) | |
score = sumHand(hand) | |
return score | |
def askBet(left): | |
while True: | |
bet = int(input("How much will you bet?\n")) | |
if bet < 1 : print("Minimum bet is 1.") | |
elif bet > 1000: print("Maximum bet is 1000.") | |
elif bet > left: print("You don't have that many credits left!") | |
else : return bet | |
def cardGen(): | |
decks = list(range(1, 13)) * 24 | |
while True: | |
shuffled = decks | |
random.shuffle(shuffled) | |
while len(shuffled) > 52: yield shuffled.pop() | |
decks = cardGen() | |
(pCreds, dCreds, gamesLeft) = (10000, 10000, 10000) | |
while --gamesLeft >= 0 and pCreds > 0 and dCreds > 0: | |
print("You have", pCreds, "credits. The dealer has", str(dCreds) + ".") | |
bet = askBet(pCreds) | |
dBet = min(dCreds, bet) | |
(pCreds, dCreds, bet) = (pCreds - bet, dCreds - dBet, bet + dBet) | |
hand = [next(decks), next(decks)] | |
print("Your hand:", ", ".join(map(cardName, hand))) | |
pHand = hit(hit([0, False], hand[1]), hand[0]) | |
hand = [next(decks), next(decks)] | |
dHand = hit(hit([0, False], hand[1]), hand[0]) | |
pScore = deal( | |
lambda n: input("Score: " + str(n) + ". Hit? (y/n)\n") == "y", | |
pHand, decks | |
) | |
if pScore == "bust": | |
dCreds += bet | |
print("You lost!") | |
continue | |
elif pScore == 21 and sumHand(dHand) != 21: | |
pCreds += bet | |
print("You won!") | |
continue | |
print("Dealer's hand:", ", ".join(map(cardName, hand))) | |
dScore = deal(lambda n: n < 17, dHand, decks) | |
if dScore == "bust" or pScore > dScore: | |
pCreds += bet | |
print("You won!") | |
else: | |
dCreds += bet | |
print("You lost!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment