這將是相當抽象的,我希望你不介意。
遊戲管理器
會是什麼game manager
實際上做?
你說你想讓它在內存中運行 - 爲什麼?應用程序基於輸入/輸出運行。除非你想以某種定時響應格式(發送通知消息等)來使用它,否則遊戲經理的想法實際上是無用的。
你需要的是一種處理系統中個人遊戲的方法。這可能需要大量的JavaScript實現,但從Rails的角度來看,沒有必要在後端過度使用。
請記住,你只是在尋找實時邏輯。這並不意味着您必須在服務器上運行實時應用程序。相反,您可以在後端使用Rails的模型和業務邏輯來處理它。
這只是一個簡單的例子:
#app/models/game.rb
class Game < ActiveRecord::Base
#columns id | name | active (bool) | created_at | updated_at
has_many :players
end
#app/models/player.rb
class Player < ActiveRecord::Base
#columns id | game_id | user_id | created_at | updated_at
belongs_to :game
belongs_to :user
alias_attribute :joined, :created_at
end
#app/models/user.rb
class User < ActiveRecord::Base
has_many :players
has_many :games, through: :players
end
這是一個非常簡單的例子,但它應該給你如下:
#config/routes.rb
resources :games, only: [:index, :show] do
resources :sessions, path: "", path_names: { new: "join", destroy: "leave" show: "" }, only: [:new, :destroy] #-> url.com/games/:game_id/join
end
#app/controllers/games_controller.rb
class SessionsController < ApplicationController
def new
@game = Game.find params[:game_id]
@session = @game.players.new player_params
if @session.save
redirect_to @game #-> takes you to url.com/game/23
else
redirect_to root_url, notice: "Sorry, you cannot join this game"
end
end
private
def player_params
params.require(:user).permit(:x, :y, :z)
end
end
我知道這不是嚴格CRUD
,但我希望你能理解它的工作原理。
然後,您可以讓你的邏輯你的模型裏面:
#app/models/player.rb
class Player < ActiveRecord::Base
belongs_to :game
belongs_to :user
alias_attribute :joined, :created_at
validates :user, uniqueness: { scope: :game, message: "You're already in this game!" }
end
的這個實時方面會從你的服務器如何快速響應的要求。如果你有一個JS前端(爲了讓它看起來很漂亮),你可以用JSON(如API)來ping後端,並在前端處理它們並作出迴應。
-
消息
使用Pusher
與Redis
。
實時通知的東西將是一個多一點參與的事情來實現,而不是編程方式,但機智。
向連接的客戶端發送推送通知相對簡單 - 只需在Redis中排列消息並使用Pusher將消息發送出去即可。但是,如果你想在沒有輸入的情況下調用消息(如果有時間更新或IE等),你需要在服務器上每運行一個x
秒鐘就有一些CRON腳本運行。
這是您可能需要一些單獨功能的地方,但我認爲Rails可以通過一些rake
命令來處理它。具有這種類型功能的資源負載是必須理解的。
NICE - 在Rails中製作基於回合的遊戲是一個偉大的項目:) –