【发布时间】:2016-10-13 08:05:17
【问题描述】:
所以我正在尝试重新创建一款名为 Ciao Ciao 的棋盘游戏。我还没有完成,但我一直被卡住,非常感谢一些帮助。到目前为止,我已经制作了以下 3 个类和 rspec 文件:
播放器类
require_relative 'die'
class Player
attr_reader :name
attr_accessor :token, :position, :point
def initialize(name, token, position, point)
@name = name
@token = token
@position = position
@point = point
end
def advance
@position += @number #basically I want the player to advance when he rolls between 1-4 but not sure how to connect it to the Die class here.
end
def lie
@token -= 1 #here I want the player to lose a token if he rolls between 5-6
@position == 0 #and have to start again from position 0
end
def score
@token -= 1
@position == 0
@point += 1
end
end
游戏类
require_relative 'player'
require_relative 'die'
class Game
def initialize(title)
@title = title
@players = []
end
def join(player)
@players << player
end
def play
puts "There are #{@players.size} players in the current round of #{@title}."
@players.each do |player|
die = Die.new
case die.roll
when 1..4
puts "#{player.name} just rolled #{die.roll}!"
player.advance
puts "#{player.name} advances to #{player.position}!"
when 5..6
puts "#{player.name} just rolled #{die.roll}!"
player.lie
puts "#{player.name} is down to #{player.token} and starts at #{player.name}!"
end
puts "#{player.name} has #{player.point} points and is at #{player.position}. He has #{player.token} token(s) left."
if player.position >= 10
player.score
puts "#{player.name} scores a point for reaching the endzone!"
end
if player.token == 0
@players.delete(player)
puts "#{player.name} has been eliminated."
end
end
end
end
模具类
class Die
attr_reader :number
def initialize
end
def roll
@number = rand(1..6)
end
end
rspec 文件
require_relative 'game'
describe Game do
before do
@game = Game.new("chaochao")
@initial_token == 4
@initial_position == 0
@initial_point == 0
@player = Player.new("iswg", @initial_token, @initial_position, @initial_point)
@game.join(@player)
end
it "advances the player if a number between 1 and 4 is rolled" do
@game.stub(:roll).and_return(3)
@game.play
@player.position.should == @initial_position + 3
end
it "makes the player lie if a number between 5 and 6 is rolled" do
@game.stub(:roll).and_return(5)
@game.play
@player.token.should == @initial_token - 1
end
end
我在运行 rspec 文件时不断收到以下错误消息:
失败:
1) 如果掷出 1 到 4 之间的数字,游戏会推进玩家
失败/错误:@game.play
无方法错误:
未定义的方法-' for nil:NilClass
# ./player.rb:19:inlie'
# ./game.rb:24:in block in play'
# ./game.rb:16:ineach'
# ./game.rb:16:in play'
# ./game_spec.rb:17:inblock (2 个级别) in '
2) 如果掷出 5 到 6 之间的数字,游戏会使玩家撒谎
失败/错误:@game.play
无方法错误:
未定义的方法+' for nil:NilClass
# ./player.rb:15:inadvance'
# ./game.rb:21:in block in play'
# ./game.rb:16:ineach'
# ./game.rb:16:in play'
# ./game_spec.rb:23:inblock (2 个级别) in '
所以错误消息指向 Player 类下的 Advance/lie 方法,但我不知道我做错了什么。也请随时指出其他错误。提前非常感谢。
【问题讨论】:
-
查看您的示例设置。不是初始化
@initial_token,而是将其与 4 进行比较。无论好坏,当您引用未初始化的实例变量时,它总是返回nil— 因此,您要求的是 nil,而不是设置实例变量等于某个值并继续前进。
标签: ruby class rspec instance-variables accessor