所以我正在試圖重新創建一個叫做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