Skip to content

Instantly share code, notes, and snippets.

@rogfrich
Created March 21, 2020 19:25
Show Gist options
  • Save rogfrich/385a765ce2882fff54f0e4038c05547d to your computer and use it in GitHub Desktop.
Save rogfrich/385a765ce2882fff54f0e4038c05547d to your computer and use it in GitHub Desktop.
"""
Specification:
A function initDeck which creates a list Deck of 52 entries containing the numbers 1-52. Needs to be recallable so delete or overwrite Dec.
Second function Deal which randomises the order of list Deck, then in a loop 1-13 creates or overwrites a two-dimensional array Hand[0-3][0-12] by copying the value in the next entry in Deck.
Master routine to call both and print out the values in Hand.
Deck and Hand to be global.
"""
import random
def init_deck():
"""
Create a fresh deck, ordered 0 to 51
"""
deck = []
for i in range(52):
deck.append(i)
return deck
def shuffle_deck(deck):
"""
Return a randomised deck
"""
random.shuffle(deck)
assert len(deck) == 52
return(deck)
def deal(deck, number_of_players, cards_in_hand):
"""
deal the cards
"""
hands = []
for _ in range(number_of_players):
current_hand = []
for _ in range(cards_in_hand):
current_hand.append(deck.pop())
hands.append(current_hand)
return hands
NUMBER_OF_PLAYERS = 3
CARDS_IN_HAND = 13
deck = init_deck()
shuffled_deck = shuffle_deck(deck)
hands = deal(shuffled_deck, NUMBER_OF_PLAYERS, CARDS_IN_HAND)
# Print "2D list" - this is the first card in the first hand.
print(hands[0][0])
# Some simple tests
all_cards = []
for hand in hands:
all_cards += hand
# Do we have the right number of cards?
assert len(all_cards) == NUMBER_OF_PLAYERS * CARDS_IN_HAND
# Are all the cards unique?
unique_cards = set(all_cards)
assert len(unique_cards) == NUMBER_OF_PLAYERS * CARDS_IN_HAND
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment