有趣的是,在文章的底部,他写道:
“你可以节省很多面试时间。不要花费太多精力,只需让候选人描述一下他们在使用策略、访问者和命令模式时实际应用过哪些框架之外的情况。”
这可能意味着您可以使用设计模式来对游戏规则进行建模(参见上文)。有人曾经这样做过吗?使用设计模式设计大富翁游戏?如果有,它的工作效果如何?
这是我设计大富翁的方式。我假设采用动态类型语言,因为这可以使一切变得更容易。具体来说,采用Ruby。
您需要一个简单的Game
对象,它主要是一个包装了一个大小为40的Array
的便利类。 Game
对象还记录了可用houses
和hotels
的数量以及两个机会和社区公益基金卡堆栈。提供了一些方便的方法,如current_turn
和next_turn!
——两者都返回一个Player
对象;next_turn!
增加回合索引,如果必要,则循环到0。
玩家可以落地的所有位置都必须继承自Property
的超类。 Property
类定义了一些共同的属性,例如rent
、owner
、set
、houses
、purchasable?
和upgradeable?
。 rent
和owner
属性可以是nil
。 set
属性返回一个Array
,其中包含组内所有属性。 set
属性的大小可以在1到4之间变化。 houses
属性表示酒店的5个'houses'。
Game
对象具有一个Player
对象的Array
,每个对象都带有像position
(从0到39的整数)、money
(没有上限——银行技术上永远不会“用完钱”)、get_out_of_jail_frees
和in_jail?
(因为位置对此不足)。Game
对象还具有跟踪轮换的索引。
具体属性规则都被编码在各自的子类中。因此,例如,在Railroad
上实现rent
的方法是:
def rent
owned_count = self.set.select { |rr| rr.owner == self.owner }.size
return 25 * 2 ** (owned_count - 1)
end
可以通过一堆闭包简单地实现“机会”和“社区救济”卡牌,这些闭包需要以游戏和玩家对象作为参数。例如:
# Second place in a beauty contest
COMMUNITY_CHEST_CARDS << lambda do |game, player|
player.money += 10
end
# Advance token to Boardwalk
CHANCE_CARDS << lambda do |game, player|
game.advance_token!(player, 39)
end
# Advance token to nearest railroad, pay double
CHANCE_CARDS << lambda do |game, player|
new_position = [5, 15, 25, 35].detect do |p|
p > player.position
end || 5
game.advance_token!(player, new_position)
# Pay rent again, no-op if unowned
game.properties[new_position].pay_rent!(player)
end
等等,advance_token!
方法显然处理像通过前进的事情。
显然,还有更多细节 - 这是一个相当复杂的游戏,但希望这能给你正确的想法。对于面试来说,这肯定已经足够了。
可以通过向 Game
对象添加一个 house_rules
Array
来打开或关闭房间规则。这将允许实现类似这样的 FreeParking
属性:
class Game
def house_rules
@house_rules ||= []
end
def kitty
# Initialize the kitty to $500.
@kitty ||= 500
end
def kitty=(new_kitty)
@kitty = new_kitty
end
end
class FreeParking < Property
def rent
if self.game.house_rules.include?(:free_parking_kitty)
# Give the player the contents of the kitty, and then reset it to zero.
return -(_, self.game.kitty = self.game.kitty, 0)[0]
else
return 0
end
end
end
我认为你在这里走了错误的道路。
...which probably means that you can use design patterns to model the rules of the game (see above).
...which probably means that you can use design patterns to model the rules of the game
这并不意味着你可以使用设计模式来建模游戏规则,而是说无论你在解决方案中做什么,它很可能会落到一些已知的设计模式上。把你的解决方案看作一组相互连接的模式比从头开始描述所有内容更容易。