2015-04-07 87 views
1

我试图让xposypos根据玩家进入的方向进行更改。该程序成功询问Where to?但位置不变。该脚本也始终默认为最后一个条件(puts("You're drunk."))根据用户的输入更改变量

例如:

然而,我的输出是:

> 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 
+0

只是一个小边评论 - 在Ruby中,你并不总是需要大约函数参数的括号内。例如,这里的大多数'puts(...)'都可以成为'puts ...'。我注意到,这看起来像Ruby的方式来做事,尽管你的代码仍然是正确的。 –

+1

你忘记了'chomp!'你的输入。 – squiguy

+0

另一方面说明:至少就我所知,它是'elsif',而不是'elseif'。 –

回答

0

它看起来就像你有两个主要的问题,至少我可以看到。首先,elseif应该是elsif。我很惊讶你没有收到语法错误。

二,Kernel::gets返回输入的下一行,最大为,包括的换行符。这意味着您必须在最后删除换行符,以便与不具有\r\n\n的字符串(取决于您的平台)进行比较可以进行比较。这是非常简单:只需更换

compass = gets 

compass = gets.chomp 

String#chomp reference

另外,如果你想之前和之后摆脱所有空格,你可以使用

compass = gets.strip 

String#strip reference

+0

在这种情况下最好使用'chomp',因为它只会在用户想要保留空白的情况下删除记录分隔符。 – squiguy

+0

@squiguy这取决于案件。例如,如果OP要确保即使意外空间不影响选择哪个选项,剥离也是最好的。但是,如果他想要空格,那么是的,chomp是最好的。 –

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