ELEC2645 (2018/19) / Mbed 2 deprecated el17lw

Dependencies:   mbed

Menu/Menu.cpp

Committer:
lewisgw
Date:
2019-04-04
Revision:
14:9861fe85c803
Parent:
13:bcf6bb69c597
Child:
18:304700b5d8f8

File content as of revision 14:9861fe85c803:

#include "Menu.h"

// Define the finite state machine for three different states: running game, display
// menu and display controls, {ouput,{a,b,c,d}} where a,b,c,d are inputs.
// The ouputs have been assigned to 0,1,2.  
// There are four different relevent input combinations that have been assigned to
// 0,1,2,3.
State _fsm[3] = { 
  {0,{0,1,0,0}},
  {1,{1,1,0,2}},
  {2,{2,1,2,0}}
};   

// Constructor and distructor
Menu::Menu() {}

Menu::~Menu() {}

void Menu::init() {
  // Initialise at the highest level, starting state is the menu.
  _state = 1;  
  _controller.init();
}

void Menu::run(N5110 &lcd, Gamepad &gamepad) {
  set_input(gamepad.check_event(Gamepad::START_PRESSED), 
    gamepad.check_event(Gamepad::BACK_PRESSED),
    gamepad.check_event(Gamepad::X_PRESSED));
  // Select the current output, execute that output via the output function
  // and update to the next state depending on the input.
  _output = _fsm[_state].output;
  output(lcd, gamepad);
  _state = _fsm[_state].next_state[_menu_input];    
}

void Menu::output(N5110 &lcd, Gamepad &gamepad) {
  // 0, 1 and 2 have been assigned to the output of each state respectivley.
  if (_output == 0) {
    run_game(lcd, gamepad);
  } else if (_output == 1) {
    display_menu(lcd, gamepad);
  } else {
    display_controls(lcd, gamepad);
  }
}

void Menu::set_input(bool start, bool back, bool x) {
  // 0, 1, 2, 3 have been assigned to each relevent input combination:
  // if nothing is pressed, input = 0.
  // if only back is pressed, input = 1.
  // if only start is pressed, input = 2.
  // if only X is pressed, input = 3.
  if (!start && !back && !x) {
    _menu_input = 0;
  } else if (!start && back) {
    _menu_input = 1;
  } else if (start && !back) {
    _menu_input = 2;
  } else if (x) {
    _menu_input = 3;
  }
} 

void Menu::run_game(N5110 &lcd, Gamepad &gamepad) {
  _controller.run_game_engine(lcd, gamepad);
}

void Menu::display_controls(N5110 &lcd, Gamepad &gamepad) {
  lcd.printString("JOYSTICK:",0,0);
  lcd.printString("-Move left",0,1);
  lcd.printString("-Move right",0,2);
  lcd.printString("-Duck",0,3);
  lcd.printString("A:",0,4);
  lcd.printString("-Jump   (back)",0,5);
}

void Menu::display_menu(N5110 &lcd, Gamepad &gamepad) {
  // Displays the menu and resets the controller to ensure a new game is 
  // ready to start when the state is switched to run game.
  _controller.init();
  lcd.printString("Menu",30,0);
  lcd.printString("START- Play!",0,1);   
  lcd.printString("X- Controls",0,2);   
}