私はウェブサイトを構築できるように Ruby を学ぼうとしてきましたが、Ruby を難しい方法で学ぶことから始めるのが良いと言われました。私は演習を行ってきましたが、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>'
私は何を間違っていますか?私はコーディングの経験がないので、おそらくいくつかの基本的なエラーを行っているだけです。ここで回答を見つけようとしましたが、同様のエラーのある回答はこのケースには当てはまらないか、少なくとも私は当てはまりません'それらがどのように適用されるか理解できません。変数を定義して、途中でメソッドを変更することはできませんか?
助けてくれてありがとう。