Reputation: 33
Ok guys, this in a Dungeon Text Adventure project that runs on terminal.
When user says he wants to "go north" it splits the string: first word checks for method and second word for parameter. That happens someplace else, i copy pasted the 2 methods that are giving me the following problem:
When it calls go(north) and north isn't a valid connection, it shows the options and asks user for direction again, the input the user enters at that moment is stored as Nil for some reason.
Why?? I also tried STDIN.gets.chomp.downcase! and had same Nil results
Here's the code:
def find_room_in_direction(direction)
##-> if room connects with other on that direction, returns connection
if find_room_in_dungeon(@player.location).connections.include?(direction.to_sym)
return find_room_in_dungeon(@player.location).connections[direction.to_sym]
##-> if direction connection is not found,
##-> show possible connections & return trigger to ask again inside go()
elsif !find_room_in_dungeon(@player.location).connections.include?(direction.to_sym)
puts "I don't see any #{direction}..."
puts "This room only connects #{(find_room_in_dungeon(@player.location)).connections.keys.join(', ')}"
puts "Where should we go?"
return :redo
end
end
def go(direction)
current_direction = @player.location
new_direction = find_room_in_direction(direction)
##-> if REDO trigger received, ask for new direction & try again
if new_direction == :redo
puts "REDOING DIRECTION"
##-> HERE IS THE PROBLEM:
##-> this does ask for input
new_direction = gets.chomp.downcase!
##-> but it saves Nil instead of the input, so that puts shows ''
puts "#{new_direction}"
##-> so this call trows an error: cant call method to Nil
new_direction = find_room_in_direction(new_direction)
##-> if user entered valid direction from start, the following would run
elsif new_direction != :redo && current_direction != new_direction
@player.location = new_direction
puts "You go #{direction},"
puts "and enter #{show_current_description}"
end
end
Any suggestions? Thanks!
Upvotes: 1
Views: 322
Reputation: 1754
You are using downcase!
instead of downcase
. downcase!
changes a string in-place and returns nil if there were no changes (which is what is happening here).
str = "teSt"
puts str.downcase # test
puts str # teSt
str.downcase!
puts str # test
See the documentation for downcase!
Upvotes: 5
Reputation: 1582
Just bang chomp. As for downcase there are two variants - chomp and chomp!
Upvotes: 0