Dwi Wahyudi
Senior Software Engineer (Ruby, Golang, Java)
2 Weeks ago, I wanted to have some fun writing Ruby code. It was about calculating values of hands in Holdem Poker.
Overview
https://en.wikipedia.org/wiki/Texas_hold_%27em
Royal Flush, Straight Flush, Four of a Kind, etc. You got the idea.
Card Model
So the first step is to model the card itself.
class Card
attr_accessor :suit, :rank, :value
def initialize(suit, rank, value)
@suit = suit
@rank = rank
@value = value
end
def to_s
"#{rank}#{suit}"
end
end
- Suit is clover, diamond, heart, and spade, with symbols: ♣ ♦ ♥ ♠.
- Rank is A (ace), 2, 3, 4 … J, Q and K.
- Value is value for this card, this is a bit tricky for ace.
Cards Generator
Next, I want to generate a pack of card, with all of those 4 suits and 13 ranks. In total there will be 52 card, each with unique pair of suit and rank.
require_relative 'card'
class CardsGenerator
SUITS = %w[♣ ♦ ♥ ♠]
RANKS = {
"A" => 1,
"2" => 2,
"3" => 3,
"4" => 4,
"5" => 5,
"6" => 6,
"7" => 7,
"8" => 8,
"9" => 9,
"10" => 10,
"J" => 11,
"Q" => 12,
"K" => 13
}
def perform
cards = []
SUITS.each do |suit|
RANKS.each do |rank, value|
card = Card.new
card.suit = suit
card.rank = rank
card.value = value
cards << card
end
end
cards
end
end
On next part we will try to create a deck of shuffled cards.