Module: PokerEngine::Game

Defined in:
lib/poker_engine/game.rb

Constant Summary collapse

POSITIONS_ORDER =
{
  preflop: i(UTG MP CO D SB BB).freeze,
  postflop: i(SB BB UTG MP CO D).freeze,
}.freeze

Class Method Summary collapse

Class Method Details

.initial_state(players, small_blind: 10, big_blind: 20, deck_seed: 1) ⇒ Object

TODO: remove blinds defaults



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 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) ⇒ Object



17
18
19
20
21
# 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) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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) ⇒ Object



12
13
14
15
# File 'lib/poker_engine/game.rb', line 12

def start(*args, &handler)
  state = initial_state(*args)
  run(state, &handler)
end