我一直在尝试学习 Ruby,这样我就可以建立一个网站,并被告知 Learning Ruby the Hard Way 是一个很好的起点。我一直在做练习,但卡在了ex36。我们应该写一个基于迷你文本的决策游戏(选择你的冒险风格)。我写了我的并认为它是有道理的,不过我正在尝试一些新功能。
我尝试制作一些随着玩家在故事中进行而变化的变量,而结局取决于这些变量(灵魂、生命、财富、债务)。
我拿走了叙述者说话,但留下了双引号
soul = 1
life = 1
riches = 0
debt = 0
def score
if soul == 1 && life == 1
puts ""
gold_score
elsif soul <= 0 && life == 1
puts ""
puts ""
gold_score
elsif soul > 1 && life == 1
puts ""
gold_score
else
puts ""
exit(0)
end
end
def gold_score
if riches == 0 || debt == 0
puts ""
exit(0)
elsif riches == 0 || debt == -1
puts ""
exit(0)
elsif riches == 1 || debt == 0
puts ""
exit(0)
else
puts ""
exit(0)
end
end
def dead(why)
puts ""
life = 0
score
end
def start
puts ""
puts ""
print "> "
choice = $stdin.gets.chomp
if choice == "left" || choice == "Left"
pirates_room
elsif choice == "right" || choice == "Right"
trex_room
else
dead("")
end
end
def gold_room
puts ""
puts ""
puts ""
puts "."
puts ""
puts ""
print "> "
choice = $stdin.gets.chomp
if choice == "1"
puts ""
soul = soul + 1
score
elsif choice == "2"
puts ""
riches = riches + 1
score
else
puts ""
puts ""
score
end
end
def pirates_room
puts ""
puts ""
puts ""
puts ""
print "> "
choice = $stdin.gets.chomp
if choice.include? ""
puts ""
dead("")
elsif choice.include?("beer") || choice.include?("keg")
puts ""
puts ""
puts ""
soul = soul - 1
gold_room
elsif choice.include?("Cthulhu") || choice.include?("bible")
puts ""
puts ""
puts ""
puts ""
debt = -1
puts ""
gold_room
else
pirates_room
end
end
def trex_room
puts ""
puts ""
puts ""
print "> "
choice = $stdin.gets.chomp
if choice.include?("stay") || choice.include?("Stay")
dead("")
elsif choice.include?("pray") || choice.include?("Pray")
puts ""
puts ""
puts ""
puts ""
puts ""
gold_room
else
trex_room
end
end
start
我运行了它,问题似乎出在我放在开头的变量上。每次我尝试“处理”它们(添加一个数字,或者查看它们是大于还是小于一个数字)都会出现错误。
我一直在寻找发生这种情况的情况,我有一些:
ex36.rb:106:in `pirates_room': undefined method `-' for nil:NilClass (NoMethodError)
from ex36.rb:55:in `start'
from ex36.rb:143:in `<main>'
ex36.rb:81:in `gold_room': undefined method `+' for nil:NilClass (NoMethodError)
from ex36.rb:115:in `pirates_room'
from ex36.rb:55:in `start'
from ex36.rb:143:in `<main>'
ex36.rb:8:in `score': undefined local variable or method `soul' for main:Object (NameError)
from ex36.rb:44:in `dead'
from ex36.rb:59:in `start'
from ex36.rb:122:in `<main>'
我究竟做错了什么?我的编码经验为零,所以我可能只是犯了一些基本错误,我试图在这里找到答案,但是有类似错误的答案似乎不适用于这种情况,或者至少我没有不明白它们是如何应用的。我不能定义变量然后用方法改变它们吗?
谢谢您的帮助。