module PokerEngine::Game

Constants

POSITIONS_ORDER

Public Instance Methods

initial_state(players, small_blind: 10, big_blind: 20, deck_seed: 1) click to toggle source

TODO: remove blinds defaults

# File lib/poker_engine/game.rb, line 40
def initial_state(players, small_blind: 10, big_blind: 20, deck_seed: 1)
  reversed_position_order = POSITIONS_ORDER[:preflop].reverse
  positions = players.map.with_index do |player, index|
    last_index = players.count - 1

    [player[:id], reversed_position_order[last_index - index]]
  end.to_h

  normalized_players = players.map do |id:, balance:, **|
    [
      id,
      {
        id: id,
        active: true,
        balance: balance,
        money_in_pot: 0,
        position: positions[id],
        cards: [],
        last_move: {},
      },
    ]
  end.to_h

  Hamster.from(
    players: normalized_players,
    aggressor_id: nil,
    board: [],
    small_blind: small_blind,
    big_blind: big_blind,
    pot: 0,
    pending_request: false,
    winner_ids: [],
    top_hands: {},
    game_ended: false,
    last_action: { type: :game_start },
    current_stage: nil,
    current_player_id: nil,
    deck: Card.french_deck.shuffle(random: Random.new(deck_seed))
  )
end
next(outer_state, player_action, &handler) click to toggle source
# File lib/poker_engine/game.rb, line 17
def next(outer_state, player_action, &handler)
  state = Reducer.call Hamster.from(outer_state), player_action

  run(state, &handler)
end
run(state, &handler) click to toggle source
# File lib/poker_engine/game.rb, line 23
def run(state, &handler)
  subscribed_reducer = lambda do |old_state, action|
    new_state = Reducer.call old_state, action
    handler&.call action, Hamster.to_ruby(new_state)

    new_state
  end

  loop do
    break Hamster.to_ruby(state) if state[:pending_request] || state[:game_ended]

    actions = NextActions.call(state)
    state = actions.reduce(state, &subscribed_reducer)
  end
end
start(*args, &handler) click to toggle source
# File lib/poker_engine/game.rb, line 12
def start(*args, &handler)
  state = initial_state(*args)
  run(state, &handler)
end