Skip to content

Instantly share code, notes, and snippets.

@townofdon
Created January 3, 2020 05:57
Show Gist options
  • Save townofdon/80f66dc896f0ee77928853d55ce377d5 to your computer and use it in GitHub Desktop.
Save townofdon/80f66dc896f0ee77928853d55ce377d5 to your computer and use it in GitHub Desktop.
ruby deck of cards
#
# Simulates a shuffled deck of cards.
# This demonstrates *one* way to simulate drawing
# 5 cards at a time from a deck of cards.
# This logic could easily be applied to games such
# as Blackjack or Texas Hold'em.
#
# Note - I included a card.val method specifically for
# checking a card's value for comparison in Poker (e.g.
# a straight is 5 consecutive card vals of the same suite).
# However, additional funcs would need to be added to check
# if a combination of cards contain a match
#
# Additionally, a `blackjack_val` method would need
# to be added which returns the numeric value for a card, or
# a wildcard (1 or 11 - recommend "%") if the card is an Ace.
#
puts "5 Card Draw"
20.times { print "-" }
class Card
def initialize (name, suite)
@name = name
@suite = suite
end
def name
@name
end
def suite
@suite
end
def to_s
_print_me
end
def to_str
_print_me
end
def val
_card_val
end
private
def _name_val
if @name == "A"
return 1
elsif @name == "1"
return 2
elsif @name == "2"
return 3
elsif @name == "3"
return 4
elsif @name == "4"
return 5
elsif @name == "5"
return 6
elsif @name == "6"
return 7
elsif @name == "7"
return 8
elsif @name == "8"
return 9
elsif @name == "9"
return 10
elsif @name == "10"
return 11
elsif @name == "Q"
return 12
elsif @name == "K"
return 13
end
0
end
def _suite_val
num_cards_in_suite = 13
return 0 * num_cards_in_suite if @suite == "hearts"
return 1 * num_cards_in_suite if @suite == "clubs"
return 2 * num_cards_in_suite if @suite == "spaids"
return 3 * num_cards_in_suite if @suite == "diamonds"
0
end
def _card_val
_name_val + _suite_val
end
def _print_me
"#{@name} of #{@suite}"
end
end
def build_deck
deck = []
names = ['A'].concat(("1".."10").to_a).concat(['Q', 'K'])
suites = ['hearts', 'clubs', 'spaids', 'diamonds']
for suite in suites
for name in names
deck << Card.new(name, suite)
end
end
deck = deck.shuffle!.shuffle!.shuffle!
end
@deck = build_deck
def looop
puts
puts
puts
puts "Press [Enter]"
# pause for user input
gets.chomp
i = 5
while i > 0 && @deck.length > 0
# draw one card out of deck and display it
puts @deck.shift
i -= 1
end
puts
puts "#{@deck.length} cards left in deck"
end
while @deck.length > 0
begin
looop
rescue Exception => e
puts e, "please try again"
end
end
puts "No more cards!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment