2014-06-26 58 views
0

我正在寫一個文字冒險遊戲的瞭解Ruby的硬盤的方式行使36:http://ruby.learncodethehardway.org/book/ex36.html紅寶石:如何退出一個函數,然後返回到它

我想包括「指令」作爲一個選項的球員可以隨時使用,但是一旦播放器退出Room()函數並輸入了intructions()函數,我不確定如何將它們返回到適當的房間。我可以讓指令()始終將玩家返回到開始位置,但有沒有辦法讓他們回到同一位置?

下面是一個簡單的例子,很抱歉它是不完整的......我仍然在建設它的中間:

puts 
puts <<INTRO 
"Welcome to the Cave of Indifference. 
It doesn't much care for you. Beware! 
There are deadly areas of this cave, but if you seek 
it you may find the secret treasure and escape with your life." 
INTRO 
puts 
puts "Type \'Instructions\' at any time for direction" 
puts 

sword = false 
monster = true 
treasure = false 

def Command() 
    puts ">>> " 
end 

def dead(how) 
    puts how.to_s 
    puts "PLAYER DEAD!" 
    Process.exit(0) 
end 

def instruction() 
    puts "Rooms will have individual instructions" 
    puts "but here are some general items." 
    puts "west, east, north, south: goes that direction" 
    puts "look: look around the room" 
    puts "take: to take item or object" 
end 

def Room1() 
    puts "You are now at the cave entrance." 
    puts "You may go west or east. OR exit with your life!" 
    Command(); choice = gets.chomp() 

    if choice.downcase == "exit" && treasure = true 
     puts "Congratulations! You win!" 
     Process.break 
    elsif choice.downcase == "exit" && treasure = false 
     puts "Seriously?! Giving up already?" 
     puts "Fine. Here is what happens:" 
     dead("You stumble on your exit from the cave and trip 
     on a rock. The fall cracks your skull and you bleed 
     to death. Bye bye!") 
    elsif choice.downcase.include? "right" 
     #INPUT 
    elsif choice.downcase.include? "left" 
     #INPUT 
    elsif choice.downcase.include? "instructions" 
     instructions() 
    else 
     "That command makes no sense, try again." 
    end  
end 

Room1() 

我還假設有與代碼中的許多問題,他很感激你的幫助,但不用擔心我會繼續這方面的工作,並使它真正好玩:)

回答

1

,您可以給指令方法的最後位置。

def instruction(last_room) 
    #do stuff 
    last_room.call() 
end 

你會調用該函數,像這樣:

instructions(method(:Room1)),其中Room1是要返回到方法的名稱。

+0

這是我完美的工作,謝謝! – Superman2971

1

你的問題是不具有指令返回Room1(或RoomX)。沒有你做任何特別的事情就會做到這一點。你需要的是這樣的:

@room = :Room1 
while true 
    send(@room) 
end 

,然後設置變量@room來控制你是哪個房間

這不是在世界上最偉大的方式來做到這一點,但它會得到。你開始了。