今天開始先把 app/channels/chat_room_channel.rb 中操作遊戲的程式碼搬出來
用 PORO(Plain Old Ruby Object) 的方式,把 GameRoom 的 game_data 欄位組成物件,操作完再存回資料庫。
class Game
  GAME_INIT = 0
  GAME_PROCESSING = 1
  GAME_ENDING = 2
  GAME_COMPLETED = 3
  attr_accessor :name, :state, :game_room_id, :game_room
  def initialize(game_room)
    @game_room = game_room
    params = game_room.game_data || {}
    @name = params.dig :name
    @players = []
    @current_player = nil
    @deck = []
    @discards = []
    @state = GAME_INIT
    @fire_token = nil
    @info_token = nil
  end
  def save
    game_room.game_data ||= {}
    game_room.game_data['state'] = state
    game_room.save
  end
end
Demo url -> https://ironman2023-hanabi.zeabur.app/