Last active
March 16, 2020 22:26
-
-
Save nickolasteixeira/f4bbd219233cd2ef57e1004a5d01b0a1 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
# Write code that implements the scoring and rules for a simplified | |
# single-player blackjack game. Aim to make your code easy to | |
# re-use by other developers. | |
# Required functionality:: | |
# Draw card | |
# See current hand | |
# Get score of current hand | |
# Get score for an explicitly defined hand | |
# In this simplified game, scoring works as follows: | |
# The score of your hand is the sum of the card values | |
# Cards 2 to 10 have face value | |
# J, Q, K have a value of 10 | |
# Aces count as 11 as long as that doesn’t make the total score exceed 21. | |
# Otherwise, they count as 1. If multiple aces are present in a hand, one | |
# of them may count as 1 while the other as 11. | |
import random | |
class BlackJack: | |
def __init__(self): | |
self.num_count = {2, 3, 4, 5, 6, 7, 8, 9, 10} | |
self.current_hand = [] | |
def draw_card(self): | |
randomNum = random.randint(2, 14) | |
if 2 <= randomNum <= 10: self.current_hand.append(randomNum) | |
elif randomNum == 11: self.current_hand.append('J') | |
elif randomNum == 12: self.current_hand.append('Q') | |
elif randomNum == 13: self.current_hand.append('K') | |
elif randomNum == 14: self.current_hand.append('A') | |
def see_current_hand(self): | |
return self.current_hand | |
def get_score(self): | |
return self.scoring(self.current_hand) | |
def scoring(self, hand_list): | |
if len(hand_list) == 0: return 0 | |
score = 0 | |
ace_count = 0 | |
for idx in range(len(hand_list)): | |
temp_card = hand_list[idx] | |
if temp_card in self.num_count: score += temp_card | |
elif temp_card is 'A': ace_count += 1 | |
else: score += 10 # assumes a face count | |
# determining the ace count | |
if ace_count == 1: score += 11 | |
elif ace_count == 2 and len(hand_list) == 2: score += 12 | |
elif ace_count == 2 and len(hand_list) > 2: score += 2 | |
return score | |
# Scoring | |
# Rules | |
# _ easy and simple to read for other developers | |
if __name__ == "__main__": | |
hand1 = [2, 'J'] # 12, | |
hand2 = ['J', 'A'] # 21, | |
hand3 = ['A', 'A'] # 12 | |
hand4 = ['A', 'A', 'J'] # 12 | |
hand5 = ['A'] # 11 | |
hand6 = [] # 0 | |
b = BlackJack() | |
print(b.scoring(hand1) == 12) | |
print(b.scoring(hand2) == 21) | |
print(b.scoring(hand3) == 12) | |
print(b.scoring(hand4) == 12) | |
print(b.scoring(hand5) == 11) | |
print(b.scoring(hand6) == 0) | |
b.draw_card() | |
b.draw_card() | |
b.draw_card() | |
print(b.see_current_hand()) | |
print(b.get_score()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment