2017-08-12 216 views
0

我想使它,所以我可以生成一组选项来选择和使用向上和向下箭头用户可以在它们之间导航当前选项被突出显示,如果你按回车键即可调用该选项包含的功能。pygame选择菜单导航使用箭头键和返回

不好意思,我让它更干净,但是尝试了几件事情来尝试获得预期的结果。

选择功能正常工作本身

def selection(text, selected_status, x, y, function): 
if selected_status: 
    fill_rect(black, x, y, display_width - x, font_size + 2) 
    fill_rect(settings[3], x, y, display_width - x, font_size +2) 
    message_to_screen("["+ text + "]", settings[3], black, x, y) 
    if event_handler() == pygame.K_RETURN: 
     function() 
     return True 
elif not selected_status: 
    fill_rect(black, x, y, display_width - x, font_size + 2) 
    message_to_screen("["+ text + "]", black, settings[3], x, y) 
    return False 

选择处理程序的问题。似乎我必须在某些时间点击箭头键才能让它们工作。 event_handler只是抓住当前按下的键并返回它。总的来说,这只是一团糟。

def selection_handler(selection_param_array, x, y): 
    text_array = selection_param_array[0] 
    selected_status_array = selection_param_array[1] 
    function_array = selection_param_array[2] 
    index = 0 
    chosen = False 
    original_y = y 
    while not chosen: 
     y = original_y 

     for i in range(len(selected_status_array)): 
      if selected_status_array[i] == selected_status_array[index]: 
       selected_status_array[i] = True 
      else: 
       selected_status_array[i] = False 
      selection(text_array[i], selected_status_array[i], x, y, function_array[i]) 
      y += font_size 

     if event_handler() == pygame.K_UP and index > 0: 
      index -= 1 
     elif event_handler() == pygame.K_DOWN and index < len(selection_param_array): 
      index += 1 
     elif event_handler() == pygame.K_RETURN: 
      chosen = True 
      function_array[index]() 
     pygame.display.update() 

回答

0

而不是仅仅检查按键是否被按下现在,你需要使用pygame.event.get()获取自上次pygame.event.get()通话所发生的所有事件。常用的语法是这样的:

for event in pygame.event.get(): 
    if event.type == pygame.KEYDOWN: 
     if event.key == pygame.K_UP: 
      index += 1 
     elif event.key == pygame.K_DOWN: 
      index -= 1 
     elif event.key == pygame.K_RETURN: 
      chosen = True 
      function_array[index]() 
      break 
index %= len(selection_param_array) 

另外,如果你在程序的开始通话from pygame.locals import *,你可以省略所有的按键和事件类型的pygame.,让您得到更可读的代码:

for event in pygame.event.get(): 
    if event.type == KEYDOWN: 
     if event.key == K_UP: 
      index += 1 
     elif event.key == K_DOWN: 
      index -= 1 
     elif event.key == K_RETURN: 
      chosen = True 
      function_array[index]() 
      break 
index %= len(selection_param_array) 

这将取代您的if event_handler() == pygame.K_UP and index > 0: ... function_array[index]()代码。 请注意,上面的代码在选择内容时会从列表的顶部循环到底部,我不知道是否需要这样做。您可以通过在event.key ==行上重新引入索引比较并删除index %= len(selection_param_array)来阻止它发生。

+0

事件处理程序实际上就是它的代码,它只是返回它在遍历事件时发现的内容 –

+0

在这种情况下,您可能会遇到不同的问题。 event_handler代码在当前代码中被调用三次。这意味着每次调用时都会清除事件队列,因此每个事件只能以一次比较显示。 – LeopardShark