Here I have these code:
//the variables and struct I uses and struct definition
int menu_flag = 0; // initialised menu flag to 0
int selected_item = 0; // selected item flag to 0
int selected_difficulty = 0;
menu_item game_difficulties[] = {
{"DIFFICULTY: NORMAL", 265, 440},
{"DIFFICULTY: HARD", 265, 440}};
menu_item menu_items[] = {
{"NEW GAME", 430, 365, handle_game_mode},
{"GAME DIFFICULTY", 450, 440, select_difficulty, game_difficulties},
{"EXIT GAME", 450, 520, _exit_game},
};
//struct definition from a header file
typedef struct
{
const char* item_string;
int x;
int y;
void (*action)(void);
struct menu_item *sub_menu;
}menu_item;
//draw the menu
void draw_general_menu()
{
drawString(380, 240, "TETRIS", COLOR_RED, 3);
for (int i = 0; i < sizeof(menu_items) / sizeof(menu_item); i++)
{
drawString(menu_items[i].x, menu_items[i].y, menu_items[i].item_string, 0xFFFFFF, 1);
if (i == selected_item)
{
// Highlight the selected item
uart_dec(selected_item);
print("n");
if (selected_item == 1)
{ // highlight item number 1
drawLineWithThicknessARGB32(779, 430, 779, 480, 0xFFFFFF, 1); // Right line of difficulty
drawLineWithThicknessARGB32(254, 430, 254, 480, 0xFFFFFF, 1); // Left line of difficulty
}
else
{// highlight item number 0 and 2
drawLineWithThicknessARGB32(menu_items[i].x - 20, menu_items[i].y - 20, menu_items[i].x - 20, menu_items[i].y + 20, COLOR_WHITE, 1); // left line
drawLineWithThicknessARGB32(menu_items[i].x + 140, menu_items[i].y - 20, menu_items[i].x + 140, menu_items[i].y + 20, COLOR_WHITE, 1); // right line
}
}
else
{
drawLineWithThicknessARGB32(menu_items[i].x - 20, menu_items[i].y - 20, menu_items[i].x - 20, menu_items[i].y + 20, COLOR_BLACK, 1);
drawLineWithThicknessARGB32(menu_items[i].x + 140, menu_items[i].y - 20, menu_items[i].x + 140, menu_items[i].y + 20, COLOR_BLACK, 1);
}
}
}
//logic to move between items on menu
void handle_menu()
{
draw_general_menu();
while (!menu_flag)
{
_uart_scanning_callback();
if (_is_enter_or_space_command())
{
menu_items[selected_item].action();
}
else if (_is_up_command() && !menu_cmd_delay)
{
selected_item = max(0, selected_item - 1);
draw_general_menu();
}
else if (_is_down_command() && !menu_cmd_delay)
{
selected_item = min(sizeof(menu_items)
/ sizeof(menu_item) - 1,
selected_item + 1);
draw_general_menu();
}
}
if (should_exit_game_mode)
{
menu_flag = 1;
//menu_cmd_delay_clear_callback();
}
}
When I test it on QEMU, it will starts at “NEW GAME” and then if I choose to go up or down, it will go to the last item or the first item, highlight both item 0 (first) and item 1 or the last item (2) and item 1, instead of just highlighting one item after I move up or down using w and s key. What could be the problem here and how can I fix it so that when I move up or down, it will highlight only one item at a time ?