BaseMenu.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package pathgame.gameplay.menu;
  2. import me.hammerle.snuviengine.api.KeyBinding;
  3. import pathgame.gameplay.Gamestate;
  4. import pathgame.gameplay.Keys;
  5. import pathgame.gameplay.Level;
  6. /**
  7. * Base class of the menus
  8. *
  9. * @author julia
  10. */
  11. public abstract class BaseMenu
  12. {
  13. private final int id;
  14. private int index = 0;
  15. public abstract MenuButton[] getOptions();
  16. private int returnId;
  17. /**
  18. * Contructor generating and initializing the menu
  19. *
  20. * @param id the id of the desired menu
  21. */
  22. public BaseMenu(int id)
  23. {
  24. this.id = id;
  25. }
  26. /**
  27. * Returns the index of the active menu button
  28. *
  29. * @return the index of the active menu button
  30. */
  31. public int getActiveIndex()
  32. {
  33. return index;
  34. }
  35. /**
  36. * Returns if this is the OptionMenu
  37. *
  38. * @return if this is the OptionMenu
  39. */
  40. public boolean isOptionMenu()
  41. {
  42. return false;
  43. }
  44. /**
  45. * Updates the menu state every gametick based on user input and returns the
  46. * id of the current menu
  47. *
  48. * @param gamestate the gamestate
  49. * @param level a level containing the current map and the current player
  50. *
  51. * @return the id of the current menu
  52. */
  53. public int tick(Gamestate gamestate, Level level)
  54. {
  55. returnId = id;
  56. if(isKeyPressed(Keys.UP_KEY) || isKeyPressed(Keys.CAM_UP_KEY))
  57. {
  58. int length = getOptions().length;
  59. index = ((index - 1) + length) % length;
  60. }
  61. else if(isKeyPressed(Keys.DOWN_KEY) || isKeyPressed(Keys.CAM_DOWN_KEY))
  62. {
  63. index = (index + 1) % getOptions().length;
  64. }
  65. else if(isKeyPressed(Keys.CONFIRM_KEY))
  66. {
  67. getOptions()[index].run(gamestate, level);
  68. }
  69. if(returnId != id)
  70. {
  71. index = 0;
  72. }
  73. return returnId;
  74. }
  75. /**
  76. * Sets the id of the current menu
  77. *
  78. * @param id the id of the current menu
  79. *
  80. */
  81. public void setReturnId(int id)
  82. {
  83. returnId = id;
  84. }
  85. /**
  86. * Resets the index of the current button to the first button
  87. *
  88. */
  89. public void resetIndex()
  90. {
  91. index = 0;
  92. }
  93. /**
  94. * Returns if the key of the parameter is pressed
  95. *
  96. * @param key the key that is checked
  97. * @return if the key is pressed
  98. */
  99. private boolean isKeyPressed(KeyBinding key)
  100. {
  101. return key.getTime() == 1 || (key.getTime() >= 20 && key.getTime() % 5 == 1);
  102. }
  103. }