Skip to content

Instantly share code, notes, and snippets.

@dtanner
Last active May 8, 2019 22:32
Show Gist options
  • Save dtanner/a7a154a12600519cb1fda47723c3e1f1 to your computer and use it in GitHub Desktop.
Save dtanner/a7a154a12600519cb1fda47723c3e1f1 to your computer and use it in GitHub Desktop.
from __future__ import print_function
from math import ceil, log
print("\n Welcome to Up-To-9-Cards Game!")
print("\n================================\n")
def get_cards():
valid_count = 0
numbers = []
while valid_count < 9:
print('Please enter a card or enter -1 to end: ', end='')
coded_number = int(raw_input())
if coded_number == -1:
return numbers
elif coded_number < 0 or coded_number > 51:
print("Not a valid card entry.")
else:
numbers.append(coded_number)
valid_count += 1
return numbers
def get_suit_number(coded_number):
return coded_number % 4
def get_suit_string(coded_number):
suit_number = get_suit_number(coded_number)
if suit_number == 0:
return "Clubs"
elif suit_number == 1:
return "Spades"
elif suit_number == 2:
return "Diamonds"
elif suit_number == 3:
return "Hearts"
def get_card_value(coded_number):
return coded_number / 4 + 1
def next_highest_power_of_two(value):
return pow(2, ceil(log(value, 2)))
def simple_sum_cards(cards):
return sum((get_card_value(card) - get_suit_number(card)) for card in cards)
def has_three_or_more_non_number_cards(cards):
return len([card for card in cards if (get_card_value(card) >= 11 or get_card_value(card) == 1)]) >= 3
def is_prime(n):
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def calculate_hand_value(cards):
base_score = simple_sum_cards(cards)
total_value = base_score
if has_three_or_more_non_number_cards(cards):
total_value = total_value * total_value + 7
if is_prime(total_value):
total_value += next_highest_power_of_two(total_value)
return total_value
def display_cards(cards):
print("Your hand is:")
for card in cards:
print(" {} of {}".format(get_card_value(card), get_suit_string(card)))
hand_value = int(calculate_hand_value(cards))
print("\nThe Total value of your hand is:\n{} points".format(hand_value))
display_cards(get_cards())
print("\n\nDone!\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment