只有在用户输入' x'先输入

时间:2014-06-28 09:20:47

标签: ruby

我正在制作基于文本的冒险游戏。我的代码如下:

case move
when "go north"
puts "you hurl yourself at the now weakened door".
when "attack"
puts "You break the weakened door!"

仅当用户在此之前键入"attack"时,我才希望puts "go north"打开破门信息。如果他们在"attack"之前键入"go north",我希望它能说出其他内容。如何检查ruby是否已将特定命令输入到case语句中?

编辑:

这是我更新的代码:

states = []

case move
when "help"
  help
when "quit"
  quit
when "inventory"
  @inventory
when "go north"
  puts "You hurl your shackled self toward the door. The chains cut into your wrists     and ankles, but you seem to be making progress."
  states << :north # add the state to the pile
  when 'attack chains'
     if states.include? :north # does our pile of state contains :in_north
      puts "You slam your shackled fists against the wall. You broke the chains!"
    else
      puts "You smash your shackled fists on the ground. Nothing happens."
    end
when "go south"
  puts "Your back shivers against the cold surface of the stone wall."
when "go east"
  puts "You tug to your right, but the chains hold fast."
when "go west"
  puts "You tug to your left, but the chains hold fast."

else
   puts "Unknown command."
end
end

这不起作用,我不认为状态:北方正在被添加。 有什么想法吗?

3 个答案:

答案 0 :(得分:3)

你没有。你想要有任何一种状态(某种状态机):

states = [] # list of states or "flags"
loop do
  case gets.chomp
  when 'go north'
    if states.include? :in_north
      puts "You're already north !"
    else
      puts "<You go north ...>"
      states << :in_north # add the state to the pile
    end
  when 'attack'
    if states.include? :in_north # does our pile of state contains :in_north
      puts "You attack the wolf before you !"
    else
      puts "You need to be north to attack !"
    end
end

答案 1 :(得分:0)

你有一个额外的&#34;结束&#34;在你的代码中。固定它。 顺便说一下,&#34;&lt;&lt;&#;运营商并不适用于所有ruby版本。 尝试使用&#34; states.push(:north)来看看它是怎么回事。

states = []

case move
when "help"
  help
when "quit"
  quit
when "inventory"
  @inventory
when "go north"
  puts "You hurl your shackled self toward the door. The chains cut into your wrists     and ankles, but you seem to be making progress."
  states << :north # add the state to the pile
when "attack chains"
    if states.include? :north # does our pile of state contains :in_north
      puts "You slam your shackled fists against the wall. You broke the chains!"
    else
      puts "You smash your shackled fists on the ground. Nothing happens."
    end
when "go south"
  puts "Your back shivers against the cold surface of the stone wall."
when "go east"
  puts "You tug to your right, but the chains hold fast."
when "go west"
  puts "You tug to your left, but the chains hold fast."
else
   puts "Unknown command."
end

答案 2 :(得分:-1)

case [gets.chomp, gets.chomp]
when ["go north", "attack"] then puts "You break the weakened door!"
when ["attack", "go north"] then puts "something else"
end