2017-08-06 52 views
-1

我目前在Ruby Curses中打印0-3行。我還創建了一個包含動物名稱的數組。 我的計劃目前輸出如何逐行打印數組元素,並用Ruby Curses選擇每一行?

dog + 0cat + 0bird + 0rat + 0 
dog + 1cat + 1bird + 1rat + 1 
dog + 2cat + 2bird + 2rat + 2 
dog + 3cat + 3bird + 3rat + 3 

我希望它輸出類似

dog + 0 
cat + 1 
bird + 2 
rat + 3 

有沒有辦法列出在另一條線路的陣列中的每個元素並能夠選中各個行?

這裏是我的

def draw_menu(menu, active_index=nil) 
    4.times do |i| 
    menu.setpos(i + 1, 1) 
    menu.attrset(i == active_index ? A_STANDOUT : A_NORMAL) 

    arr = [] 
    arr << "dog" 
    arr << "cat" 
    arr << "bird" 
    arr << "rat" 

    arr.each do |item| 

     menu.addstr "#{item} + #{i}" 
    end 
    end 
end 

我一直在使用arr.each嘗試和arr.each_index工作的功能,但它給了我同樣的輸出。

這是完整的程序。下面

UPDATE

使得菜單看怎麼想,但按「W」或「S」通過在菜單中滾動時,它選擇在同一時間所有的4個元素。有沒有辦法讓它一次只能選擇一個元素?

require "curses" 
include Curses 

init_screen 
start_color 
noecho 

def draw_menu(menu, active_index=nil) 
    4.times do |i| 
    menu.setpos(1, 1) 
    menu.attrset(i == active_index ? A_STANDOUT : A_NORMAL) 

    arr = [] 
    arr << "dog" 
    arr << "cat" 
    arr << "bird" 
    arr << "rat" 

    arr.each_with_index do |element, index| 
     menu.addstr "#{element} + #{index}\n" 
    end  
    end 
end 

def draw_info(menu, text) 
    menu.setpos(1, 10) 
    menu.attrset(A_NORMAL) 
    menu.addstr text 
end 

position = 0 

menu = Window.new(7,40,7,2) 
menu.box('|', '-') 
draw_menu(menu, position) 
while ch = menu.getch 
    case ch 
    when 'w' 
    draw_info menu, 'move up' 
    position -= 1 
    when 's' 
    draw_info menu, 'move down' 
    position += 1 
    when 'x' 
    exit 
    end 
    position = 3 if position < 0 
    position = 0 if position > 3 
    draw_menu(menu, position) 
end 

回答

1

不知道是什麼4.times試圖做的,但我認爲這是4倍的設置相同的文本到屏幕上的相同位置。對於4箇中的每一個,如果當前的4個項目組與active_index相同,則將其全部4個設置爲相同樣式(A_STANDOUT而不是A_NORMAL)。

什麼,似乎是爲我工作和我所承擔的目的是一樣的東西:

def draw_menu(menu, active_index=nil) 
    %w(dog cat bird rat).each_with_index do |element, index| 
    menu.setpos(index + 1, 1) 
    menu.attrset(index == active_index ? A_STANDOUT : A_NORMAL) 

    menu.addstr("%-4s + #{index}" % element) 
    end 

    menu.setpos(5, 1) # set the cursor on the line after the menu items 
end 

,然後在你的draw_info我不能看到那裏的案文進行輸出,但如果我改變了它到setpos(5, 1)它在菜單後變爲可見:

def draw_info(menu, text) 
    menu.setpos(5, 1) 
    menu.attrset(A_NORMAL) 
    menu.addstr text 
end 
+0

這很好用。你在4× – Prox

+0

上是正確的問題:%-4s做什麼?我注意到如果我將4改爲另一個數字,似乎沒有任何區別。 – Prox

+0

哦,這個詞左對齊,並確保它們都佔用至少4個空格,例如「%-4s」看起來像「老鼠 - + 3」和「%-8s」它變成了「老鼠 - ---- + 3'(用破折號代替空格,因爲SO凝聚了空格......那部分是沒有必要的,只是在我玩弄一些事情沒有排隊的例子的時候給我打擾。 。你可以保留該行爲'menu.addstr「#{element} +#{index}」'並且沒問題 –