Skip to content

Instantly share code, notes, and snippets.

@myokoym
Last active September 28, 2015 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myokoym/0773c19fc7df4a351b70 to your computer and use it in GitHub Desktop.
Save myokoym/0773c19fc7df4a351b70 to your computer and use it in GitHub Desktop.
require "ruby-poker"
class Player
attr_reader :name, :cards
attr_accessor :hand
def initialize(name)
@name = name
@cards = []
@hand = nil
end
end
n_players = 3
players = n_players.times.collect.with_index do |i|
Player.new("player#{i + 1}")
end
class Game
attr_reader :players, :cards, :field_cards
def initialize(players)
@cards = []
%w(S H D C).each do |mark|
numbers = (2..9).to_a + %w(T J Q K A)
numbers.each do |number|
@cards << "#{number}#{mark}"
end
end
@cards.shuffle!
@field_cards = []
@players = players
2.times do
@players.each do |player|
player.cards << @cards.pop
end
end
end
def open
@field_cards << @cards.pop
end
def make_hand(your_cards, field_cards)
max_hand = nil
field_cards.combination(3) do |cards|
hand = PokerHand.new(your_cards + cards)
max_hand ||= hand
if hand > max_hand
max_hand = hand
end
end
max_hand
end
def winner(players=@players, field_cards=@field_cards)
players.each do |player|
player.hand = make_hand(player.cards, field_cards)
end
players.sort_by {|player| player.hand }.last
end
def percentage
cards = @cards.dup
players = @players.dup
field_cards = @field_cards.dup
winners = {}
all = 0
cards.combination(5 - field_cards.size) do |cards|
winner = winner(players, field_cards + cards).name
winners[winner] ||= {}
winners[winner][:score] ||= 0
winners[winner][:score] += 1
all += 1
end
winners.each_entry do |name, status|
winners[name][:percentage] = status[:score] * 100 / all
end
winners
end
end
game = Game.new(players)
game.open
game.open
game.open
p game.players
p game.field_cards
p game.winner.name
p game.winner.hand.rank
game.open
p game.percentage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment