所以我正在试图重新创建一个叫做Ciao Ciao的棋盘游戏。我没有接近完成,但我一直陷入困境,真的很感谢一些帮助。到目前为止,我已经做了以下3类和RSpec文件:Ruby初学者:类,实例变量,访问器,rspec
Player类
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
Game类
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。在'
2)游戏 未定义的方法-' for nil:NilClass # ./player.rb:19:in
谎言 ' #./game.rb:24:in block in play' # ./game.rb:16:in
每个' #./game.rb:16:in play' # ./game_spec.rb:17:in
块(2级):播放 NoMethodError使th È玩家谎言如果图5和6之间的一个数被轧制 故障/错误:@ game.play NoMethodError: 未定义的方法+' for nil:NilClass # ./player.rb:15:in
预先 ' #./game.rb:21:in block in play' # ./game.rb:16:in
每个' #./game。 rb:16:play' # ./game_spec.rb:23:in
block(2 levels)in'
所以错误信息指向Player类下的advance/lie方法,但我不知道我做了什么错误。另外请随时指出其他错误。非常感谢提前。
看看你的示例设置。你不用初始化'@initial_token',而是将它与4进行比较。无论好坏,当你引用一个未初始化的实例变量时,它总是返回'nil' - 因此,而是设置一个实例变量,你问的是零等于一些价值并继续前进。 – dodecaphonic