我正在构建一个纸牌游戏(基本的 52 张纸牌套牌 4 花色 * 13 等级),我已经决定使用 MongoDB 来完成这个项目。
我的基本模型是: --> Game --> Deck --> Cards --> Players --> Hand (as Deck) --> Cards --> Final (as Deck) --> Cards --> Closing (作为甲板)-> 卡片
理想情况下,我想将游戏牌组中的牌转移到玩家拥有的各种牌堆中。
但是,执行以下操作:game.players[0].hand.cards.push(game.deck.cards.shift(1))
不起作用,相关卡不会从游戏的牌组中移除(因为 #delete 从未调用过),并且不会添加到玩家的手上(根据我有限的理解,Mongoid 会仅将新对象添加到嵌入式集合。)
所以要将一张牌从一堆移到另一堆,我基本上必须这样做:game = Game.first player = game.players.first
card = game.deck.cards.shift
copy = Card.new(card.card_id) #read,create
player.hand.cards << copy
if player.save!
card.delete #delete
game.save
end
不是惊天动地的困难,但我基本上是在做一个 READ、一个 DESTROY 和一个 CREATE,基本上可以模拟一个非常简单的 UPDATE。
有什么我想念的吗?这是 Mongoid ODM 的限制吗?在集合之间移动文档是一个巨大的禁忌吗?
我非常愿意接受有关该模型的建议,因为我不知道嵌入式文档是否适合此类问题。
下面是对应的样板
class Deck
include Mongoid::Document
field :is_deck, :type => Boolean
embedded_in :game
embedded_in :player
embeds_many :cards
end
class Card
include PlayingCards
include Mongoid::Document
embedded_in :deck
field :card_id, :type => Integer
field :idx, :type => Integer #used to maintain shuffled order since mongodb is insertion order
field :rank, :type => String
field :suit, :type => String
end
class Game
include Mongoid::Document
embeds_one :deck #deck players draw from
embeds_many :players
field :current_player, type: Integer
field :num_players, type: Integer
end
class Player
include Mongoid::Document
embedded_in :game
embeds_one :hand, class_name: "Deck"
embeds_one :closing, class_name: "Deck"
embeds_one :final, class_name: "Deck"
end
提前致谢!