根据用户的输入更改变量

时间:2015-04-07 03:13:10

标签: ruby

我正在尝试根据玩家进入的方向更改xposypos。该计划成功询问Where to?但该职位没有改变。该脚本也始终默认为最后一个条件(puts("You're drunk."))

例如:

> n
0
1

但是,我的输出是:

> n
You're drunk.
0
0

这是我目前的代码:

north = "n"
west = "w"
south = "s"
east = "e"
xpos = 0
ypos = 0

puts("WHERE TO?")
compass = gets

if compass == north
    ypos = ypos + 1
elseif compass == west
    xpos = xpos - 1
elseif compass == south
    ypos = ypos - 1
elseif compass == east
    xpos = xpos + 1
else
    puts("You're drunk.") #if the player does not submit a proper direction

    puts(xpos) #for debugging. prints zero when called showing the player has not moved
    puts(ypos)
end

2 个答案:

答案 0 :(得分:1)

正如其他人所指出的,它可能是缺失的chompelseif

只是一个建议,但这呼吁case声明:

case compass
  when 'north'
    ypos = ypos + 1
  when 'west'
    xpos = xpos - 1
  when 'south'
   ypos = ypos - 1
  when 'east'
   xpos = xpos + 1
 else
  puts("You're drunk.") #if the player does not submit a proper direction
  puts(xpos)#for debugging. prints zero when called showing the player has not moved
  puts(ypos)
end

答案 1 :(得分:0)

看起来你有两个主要问题,至少我能看到。首先,elseif应为elsif。我很惊讶你没有得到语法错误。

其次,Kernel::gets返回输入的下一行,直到并包括换行符。这意味着您必须在结尾处删除换行符,以便与不具有\r\n\n的字符串进行比较,具体取决于您的平台,可以进行比较。这很简单:只需替换

compass = gets

compass = gets.chomp

String#chomp reference

或者,如果您想要摆脱之前和之后的所有空白,可以使用

compass = gets.strip

String#strip reference