Advertisement
Guest User

Untitled

a guest
Mar 17th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.71 KB | None | 0 0
  1. '''
  2. Made By: Sean Stach
  3. Last Edited: 17/03/2018
  4.  
  5. This is a game of Black jack that only supports up to one player and has nearly
  6. all functionality of a normal blackjack game. The game differs from casino to
  7. casino so the rules may not be the same as you expect.
  8.  
  9. You can find the specific rules for this blackjack under the rules function or
  10. by pressing r in the console.
  11.  
  12. It was progammed with out much use of Object Orientation which I accustomed to.
  13.  
  14. '''
  15.  
  16. import random
  17.  
  18. '''
  19.  
  20. FUNCTIONS
  21.  
  22. '''
  23.  
  24. #Builds a deck of cards and shuffles
  25. #Playing with two decks as one deck isn't common unless odds are changed
  26. #Return: (list) shuffled deck
  27. def shuffleDeck():
  28. deck = []
  29. for suit in SUITS:
  30. for card in CARDS:
  31. deck.append([(suit, card), False])
  32. deck.append([(suit, card), False])
  33. random.shuffle(deck)
  34. print("\n~ Deck shuffled! ~")
  35. return deck
  36.  
  37. #Draws a card to a hand
  38. #Par1: (list) deck to draw from
  39. #Par2: (list) hand to draw to
  40. #Par3: (str) Name of hand owner
  41. #Par4: (bool) draw card face down
  42. #Par5: (num) hand number to print
  43. def drawCard(deck, hand, name, faceDown=False, handNumber=0):
  44. hand.append(deck.pop(len(deck)-1))
  45. if(faceDown):
  46. hand[len(hand)-1][1] = True
  47. if(handNumber == 0):
  48. print("\n~ " + name + " receives " + cardName(hand[len(hand)-1]) + " ~")
  49. else:
  50. print("\n~ " + name + " receives " + cardName(hand[len(hand)-1]) +
  51. " in Hand " + str(handNumber) + "~")
  52.  
  53. return None
  54.  
  55. #Reveals dealer hole card
  56. #Par1: (list) dealer hand
  57. def dealerReveal(dealerHand):
  58. if(dealerHand[0][1] == False):
  59. return None
  60.  
  61. dealerHand[0][1] = False
  62. print("\n~ Dealer revealed: " + cardName(dealerHand[0]) + " ~")
  63.  
  64. return None
  65.  
  66. #Makes a card name
  67. #Par1: (tuple) card tuple
  68. #Return: (str) card string
  69. def cardName(card):
  70. if(card[1] == True):
  71. return "Face Down Card"
  72. else:
  73. return "%s %s" % (card[0][0], card[0][1])
  74.  
  75. #Prints out the given hand
  76. #Par1: (llist) Hand to print
  77. #Par2: (str) name of hand owner
  78. #Par3: (num) number of hand to print
  79. def printHand(hand, name, handNumber=0):
  80. if(handNumber==0):
  81. print("\n" + name + " Hand:")
  82. else:
  83. print("\n" + name + " Hand " + str(handNumber) +":")
  84. for card in hand:
  85. print("- ", cardName(card))
  86.  
  87. isFirstCardFaceDown = hand[0][1]
  88. if(isFirstCardFaceDown):
  89. print("Est. Total: " + str(handValue(hand, True)) + " + 1-11")
  90. else:
  91. print("Total: " + str(handValue(hand)))
  92.  
  93. return None
  94.  
  95. #Returns the value of hand, returns value without hidden card if set to hidden
  96. #Par1: (list) Hand to evaluate
  97. #Par2: (bool) Add Facedown card valuie
  98. #Return: (int) value of hand
  99. def handValue(hand, hidden=False):
  100. handValue = 0
  101. aces = 0
  102. for card in hand:
  103. cardName = card[0][1]
  104. if(hidden):
  105. hidden = False
  106. continue
  107. if(cardName == "Ace"):
  108. aces+=1;
  109. continue
  110. value = 0
  111. if(cardName == "King" or cardName == "Queen" or
  112. cardName == "Jack"):
  113. value = 10
  114. else:
  115. value = int(cardName)
  116. handValue += value
  117.  
  118. while (aces != 0):
  119. if(handValue + 11 <= 21):
  120. handValue += 11
  121. else:
  122. handValue += 1
  123.  
  124. aces -= 1
  125.  
  126. return handValue;
  127.  
  128. #Work out the payout for the player
  129. #Par1: (list) hand of dealer
  130. #Par2: (list hand of player
  131. def payOut(dealerHand, playerHands, index, bettingAmount):
  132.  
  133. playerHand = playerHands[index]
  134. dealerValue = handValue(dealerHand)
  135. playerValue = handValue(playerHand)
  136. dealerBlackjack = len(dealerHand) == 2 and dealerValue == 21
  137. playerBlackjack = len(playerHand) == 2 and playerValue == 21 and len(playerHands) == 1
  138.  
  139. amount = 0
  140. if(dealerBlackjack and not playerBlackjack):
  141. print("\nDealer blackjack!")
  142. amount = -bettingAmount
  143. elif(playerBlackjack and not dealerBlackjack):
  144. print("\nBlackjack Win!")
  145. amount = bettingAmount * 1.50
  146. elif((playerValue > dealerValue or dealerValue > 21) and
  147. playerValue <= 21):
  148. print("\nWin!")
  149. amount = bettingAmount
  150. elif(playerValue == dealerValue and playerValue <= 21):
  151. print("\nDraw!")
  152. else:
  153. print("\nLost!")
  154. amount = -bettingAmount
  155. return amount
  156.  
  157. #Alters amount of cash
  158. #Par1: (int) The amount to alter
  159. def alterCash(amount):
  160. if(amount < 0):
  161. print("\n-- Lost $" + str(abs(amount)) + " --")
  162. elif(amount > 0):
  163. print("\n++ Gained $" + str(abs(amount)) + " ++")
  164.  
  165. return amount
  166.  
  167. #Asks a user for an amount to bet with
  168. #Parameter 1: (string) Text to display to the user
  169. #Parameter 2: (int) limit of bet
  170. #Paramater 3: (int) what intervals that bet can be taken as
  171. #Return: (int) the amount the user bet with
  172. def betInput(toDisplay, limit, interval):
  173. while(True):
  174. print(toDisplay)
  175. bet = input()
  176.  
  177. if(not bet.isdigit()):
  178. print("\nMust only enter whole numbers!")
  179. continue
  180.  
  181. bet = int(bet)
  182.  
  183. if(bet % interval != 0):
  184. print("\nMust be in intervals of %d!" % interval)
  185. continue
  186.  
  187. if(bet > limit):
  188. print("\nMust not be over %d!" % limit)
  189. continue
  190.  
  191. return bet
  192. return None
  193.  
  194. #Prints rules specific to this blackjack
  195. def printRules():
  196. print("\nRules:")
  197. print("- Uses two decks.")
  198. print("- Dealer doesn't draw on soft 17.")
  199. print("- Insurance:")
  200. print("-- Can do insurance wager between 0 and original betting amount.")
  201. print("-- If you bet maximum insurance with blackjack you'll receive 2x")
  202. print("-- your original bet and end your hand.")
  203. print("- Surrender:")
  204. print("-- Can surrender only after drawing first two cards.")
  205. print("-- Will get 50% of money back.")
  206. print("- Split:")
  207. print("-- Can split a maximum of 3 times.")
  208. print("-- Can not get blackjack on a split.")
  209. print("-- No special rules for splitting on ace.")
  210. print("- Double:")
  211. print("-- Double your bet and only receive one extra card.")
  212. print("-- May only be exactly double of current bet.")
  213.  
  214. #Setup the game
  215. #Par1: (list) used deck
  216. #Par2: (list) player hands
  217. #Par3: (list) dealer hand
  218. #Return: (int) betting amount
  219. def gameSetup(deck, hands, dealer):
  220.  
  221. #Player starting hand
  222. hands.append([])
  223. drawCard(deck, hands[0], "Player")
  224. drawCard(deck, hands[0], "Player")
  225.  
  226. if(handValue(hands[0]) == 21):
  227. print("\nBlack jack!")
  228.  
  229. #Dealer hand
  230. drawCard(deck, dealer, "Dealer", True)
  231. drawCard(deck, dealer, "Dealer")
  232.  
  233. return bettingAmount
  234.  
  235. #Double bet
  236. #Par1: (int) bet amount
  237. #Par2: (int) hand index
  238. #Return: (int) bet amount
  239. def double(bet, idx):
  240. print("\nDouble down!")
  241. doubled[idx] = True
  242. return bet
  243.  
  244. #Add a card to hand
  245. #Par1: (list) deck to add to
  246. #Par2: (list) player hands
  247. #Par3: (int) current player hand index
  248. #Return: (int) next hand index
  249. def hit(deck, hands, index):
  250. if(len(hands) == 1):
  251. drawCard(deck, hands[index], "Player")
  252. else:
  253. drawCard(deck, hands[index], "Player", False, index+1)
  254.  
  255. #Check for bust
  256. if(bustCheck(hands[index], "Player", index+1)):
  257. return index+1
  258. return index
  259.  
  260.  
  261. #Splits the hand into two
  262. #Par1: (list) deck to get cards from
  263. #Par2: (list) players hands
  264. #Par3: (int) index of current hand
  265. def split(deck, hands, handIdx):
  266. print("\nSplit hand!")
  267. hands.append([hands[handIdx].pop(1)])
  268. drawCard(deck, hands[handIdx], "Player", False, handIdx+1)
  269. drawCard(deck, hands[len(hands)-1], "Player", False, len(hands))
  270. return None
  271.  
  272. #Checks to see if can split hand
  273. #Par1: (list) hands to check
  274. #Par2: (str) index of hand
  275. #Return: (bool) if can split
  276. def canSplit(hands, index):
  277. hand = hands[index]
  278. firstCardName = hand[0][0][1]
  279. secondCardName = hand[1][0][1]
  280. if(len(hand) !=2):
  281. return False
  282. if(len(hands) < 4 and (hand[0][0][1] == hand[1][0][1] or
  283. ((firstCardName == "King" or firstCardName == "10" or
  284. firstCardName == "Queen" or firstCardName == "Jack") and
  285. (secondCardName == "King" or secondCardName == "10" or
  286. secondCardName == "Queen" or secondCardName == "Jack")))):
  287. return True
  288. return False
  289.  
  290. #Checks to see if hand is bust
  291. #Par1: (list) hand to check
  292. #Par2: (str) name of hand owner
  293. #Par3: (num) hand number
  294. #Return: (bool) if bust
  295. def bustCheck(hand, name, number=0):
  296. if(handValue(hand) > 21):
  297. if(number==0):
  298. print("\n" + name + " bust!")
  299. else:
  300. print("\n%s Hand %d bust!" % (name, number))
  301. return True
  302. return False
  303.  
  304. '''
  305.  
  306. VARIABLES
  307.  
  308. '''
  309.  
  310. #Tuples for card generation
  311. SUITS = ("♠", "♦", "♣", "♥")
  312. CARDS = ("Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",
  313. "Queen", "King")
  314. #List of all actions
  315. ACTIONS = {'p':"S(p)lit", 'u':"S(u)rrender", 'l':"(L)eave", 's':"(S)tand"
  316. , 'a':"(A)lter bet", 'h':"(H)it", 'b':"(B)et", 'd':"(D)ouble",
  317. 't':"Player S(t)atistics", 'r':"House (R)ules"}
  318.  
  319. #Game state variables
  320. deck = []
  321. cash = 1000
  322. bettingAmount = 0
  323. insuranceAmount = 0
  324. playerHands = []
  325. dealerHand = []
  326. currentHandIdx = 0
  327. doubled = {} #Key is hand index and value is if hand should be doubled
  328.  
  329. #Stats
  330. handsPlayedStat = 0
  331. standStat = 0
  332. evenMoneyStat = 0
  333. splitStat = 0
  334. doubleStat = 0
  335. bustStat = 0
  336. hitStat = 0
  337. surrenderStat = 0
  338. insuranceStat = 0
  339. blackJackStat = 0
  340. drawStat= 0
  341. insuranceAmtStat = [] #Record of amounts spent on insurance
  342. betAmtStat = [] #Record of amounts spent on initial bet
  343. winTotal = [] #Record of individual accounts of money earned
  344. loseTotal = [] #Record of individual accounts of money lost
  345.  
  346.  
  347. '''
  348.  
  349. THE GAME LOOP
  350.  
  351. '''
  352.  
  353. userInput = ""
  354. print("\nWelcome to Digital Casino!")
  355.  
  356. while(cash > 0 and userInput != 'l'):
  357. #Check available actions taking from action var
  358. currentActions = []
  359.  
  360. #Starting actions
  361. if(len(playerHands) == 0):
  362. currentActions.append('b')
  363. if(bettingAmount <= cash and bettingAmount > 0):
  364. currentActions.append('a')
  365. currentActions.append('r')
  366. currentActions.append('t')
  367. currentActions.append('l')
  368. #Playing actions
  369. elif(currentHandIdx < len(playerHands) and
  370. handValue(playerHands[currentHandIdx]) < 21 and
  371. handValue(dealerHand) < 21):
  372. currentActions.append('h')
  373. currentActions.append('s')
  374. if(bettingAmount*2 <= cash):
  375. currentActions.append('d')
  376. if(cash-bettingAmount*(len(playerHands)+1) and
  377. canSplit(playerHands, currentHandIdx)):
  378. currentActions.append('p')
  379. if(len(playerHands) == 1 and len(playerHands[0]) == 2):
  380. currentActions.append('u')
  381.  
  382. if(len(playerHands) != 0 and currentHandIdx < len(playerHands) and
  383. handValue(playerHands[currentHandIdx]) == 21):
  384. currentHandIdx+=1
  385. continue
  386.  
  387. #Handle user input
  388. userInput = ""
  389.  
  390. while(not userInput in currentActions and len(currentActions) > 0):
  391.  
  392. #Print game state
  393. if(len(playerHands) > 0):
  394. printHand(dealerHand, "Dealer")
  395. printHand(playerHands[currentHandIdx], "Player", currentHandIdx+1)
  396.  
  397. print("\nCurrent Balance: $" + str(cash))
  398. if(bettingAmount > 0 and bettingAmount <= cash):
  399. print("Current Bet: $%d" % bettingAmount)
  400. for action in currentActions:
  401. print(ACTIONS[action])
  402.  
  403. print("\nChoose an action:")
  404. userInput = input().lower()
  405.  
  406. if(userInput=='r'):
  407. printRules()
  408. continue
  409.  
  410. if(userInput=='t'):
  411. print("\nPLAYER STATISTICS:")
  412. print("Hands Played: %d Hits: %d" % (handsPlayedStat, hitStat))
  413. print("Stands : %d Splits: %d" % (standStat, splitStat))
  414. print("Doubles: %d Surrenders: %d" % (doubleStat, surrenderStat))
  415. print("Busts: %d Blackjacks: %d" % (bustStat, blackJackStat))
  416. print("Total Winnings: %d Total Losses: %d Times Made Even: %d" %
  417. (sum(winTotal), sum(loseTotal), drawStat))
  418. if(len(winTotal) > 0):
  419. print("Avg Winnings: %d" %
  420. (sum(winTotal)/len(winTotal)))
  421. if(len(loseTotal) > 0):
  422. print("Avg Losings: %d" %
  423. (sum(loseTotal)/len(loseTotal)))
  424. if(len(loseTotal) > 0 and len(winTotal) > 0):
  425. print("Earnings Per Hand: %d" %
  426. ((sum(winTotal)-sum(loseTotal))/handsPlayedStat))
  427. if(len(betAmtStat) > 0):
  428. print("Avg Bet Amount: %d" % (sum(betAmtStat)/len(betAmtStat)))
  429. if(len(insuranceAmtStat) > 0):
  430. print("Avg Insurance Amount: %d" %
  431. (sum(insuranceAmtStat)/len(insuranceAmtStat)))
  432. continue
  433.  
  434. if(userInput=='b' or userInput=='a'):
  435. if(bettingAmount == 0 or bettingAmount > cash or userInput=='a'):
  436. bettingAmount = betInput("\nInput an interval of 2 as bet:",
  437. cash, 2)
  438.  
  439. betAmtStat.append(bettingAmount)
  440. deck = shuffleDeck()
  441. dealerHand = []
  442. currentBet = bettingAmount
  443. gameSetup(deck, playerHands, dealerHand)
  444. handsPlayedStat+=1
  445. if(handValue(playerHands[0]) == 21):
  446. blackJackStat+=1
  447. currentHandIdx = 0
  448. doubled = {}
  449. #Insurance check
  450. dealer2ndCard = dealerHand[1][0][1]
  451. if(dealer2ndCard == "Ace"):
  452. insuranceAmount = betInput("\nPlease enter desired insurance amount:",
  453. bettingAmount/2, 1)
  454. insuranceAmtStat.append(insuranceAmount)
  455.  
  456. if(insuranceAmount > 0):
  457. insuranceStat+=1
  458. #Take even money
  459. if(handValue(playerHands[0]) == 21 and
  460. insuranceAmount == bettingAmount/2):
  461. cash+= alterCash(bettingAmount)
  462.  
  463. winTotal.append(bettingAmount)
  464. insuranceAmount = 0
  465. evenMoneyStat+=1
  466.  
  467. if(dealer2ndCard == "Ace" or dealer2ndCard == 10 or
  468. dealer2ndCard == "Jack" or dealer2ndCard == "Queen" or
  469. dealer2ndCard == "King"):
  470. print("\n~ Dealer peeks at face down card ~")
  471. if(handValue(dealerHand) != 21 and insuranceAmount > 0):
  472. print("\nLost insurance!")
  473. cash+=alterCash(-insuranceAmount)
  474. loseTotal.append(insuranceAmount)
  475. insuranceAmount = 0
  476. continue
  477.  
  478. if(userInput == 'l'):
  479. continue
  480.  
  481. if(userInput=='s'):
  482. standStat+=1
  483. currentHandIdx+=1
  484. continue
  485.  
  486. if(userInput=='d'):
  487. doubleStat+=1
  488. bettingAmount = double(bettingAmount, currentHandIdx)
  489. hit(deck, playerHands, currentHandIdx)
  490. currentHandIdx+=1
  491. continue
  492.  
  493. if(userInput=='h'):
  494. hitStat+=1
  495. print("\nHit!")
  496. currentHandIdx = hit(deck, playerHands, currentHandIdx)
  497. continue
  498.  
  499. if(userInput=='p'):
  500. splitStat+=1
  501. split(deck, playerHands, currentHandIdx)
  502. continue
  503.  
  504. if(userInput=='u'):
  505. print("\nSurrendered!")
  506. cash+=alterCash(int(-bettingAmount/2))
  507. loseTotal.append(bettingAmount/2)
  508. surrenderStat+=1
  509. playerHands = []
  510.  
  511. dealerReveal(dealerHand)
  512.  
  513. #Dealer card draw, no soft 17
  514. while(handValue(dealerHand) < 17):
  515. drawCard(deck, dealerHand, "Dealer")
  516.  
  517. #Dealer bust
  518. bustCheck(dealerHand, "Dealer")
  519.  
  520. #Handle final payouts
  521. printHand(dealerHand, "Dealer")
  522.  
  523. #Record busts
  524. for hand in playerHands:
  525. if(handValue(hand) > 21):
  526. bustStat+=1
  527.  
  528. #Resolve hands
  529. if(len(playerHands) == 1):
  530. printHand(playerHands[0], "Player")
  531. if(0 in doubled and doubled[0] == True):
  532. currentBet = bettingAmount * 2
  533. else:
  534. currentBet = bettingAmount
  535. cashWon = payOut(dealerHand, playerHands, 0, currentBet)
  536. #Resolve insurance
  537.  
  538. cashChange = 0
  539. if(insuranceAmount != 0 and handValue(dealerHand) == 21):
  540. print("\nWon insurance!")
  541. cashChange = alterCash(insuranceAmount)
  542. insuranceAmount = 0
  543.  
  544. cashChange = alterCash(cashWon)
  545.  
  546. cash+=cashChange
  547. if(cashChange < 0):
  548. loseTotal.append(-cashChange)
  549. elif(cashChange > 0):
  550. winTotal.append(cashChange)
  551. else:
  552. drawStat+=1
  553. else:
  554. for i in range(len(playerHands)):
  555. if(i in doubled and doubled[i] == True):
  556. currentBet = bettingAmount * 2
  557. else:
  558. currentBet = bettingAmount
  559. printHand(playerHands[i], "Player", i+1)
  560. cashChange = alterCash(payOut(dealerHand, playerHands, i, currentBet))
  561. cash+=cashChange
  562. if(cashChange < 0):
  563. loseTotal.append(-cashChange)
  564. elif(cashChange > 0):
  565. winTotal.append(cashChange)
  566. else:
  567. drawStat+=1
  568. playerHands = []
  569. if(cash == 0):
  570. print("\nYou're out of money! Get out of the casino!")
  571. else:
  572. print("\nYou've left with $" + str(cash) +
  573. ". Please visit our establishment again!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement