CLIOptionScreen.java

  1. package com.github.quizclash.plugin.cli.screen;

  2. import com.github.quizclash.application.TerminationException;
  3. import com.github.quizclash.application.action.Action;
  4. import com.github.quizclash.application.screen.OptionScreen;
  5. import com.github.quizclash.domain.Displayable;
  6. import com.github.quizclash.plugin.cli.CLIWindowManager;

  7. import java.util.List;
  8. import java.util.ListIterator;

  9. public class CLIOptionScreen extends OptionScreen {
  10.   private final CLIWindowManager cliWindow;
  11.   private int userOption;

  12.   public CLIOptionScreen(String screenName,
  13.                          List<? extends Displayable> displayableList,
  14.                          CLIWindowManager cliWindow) {
  15.     super(screenName, displayableList);
  16.     this.cliWindow = cliWindow;
  17.   }

  18.   @Override
  19.   public void render() {
  20.     cliWindow.clearAllCanvas();
  21.     cliWindow.printAnimated(this.getScreenName(), 20);
  22.     cliWindow.moveOnCanvas(0, 2);
  23.     List<? extends Displayable> optionList = this.getScreenOptions();
  24.     userOption = selectFromOptions(optionList);
  25.   }

  26.   @Override
  27.   public Action<Integer> getOptionInput() {
  28.     return new Action<>(userOption);
  29.   }

  30.   private int selectFromOptions(List<? extends Displayable> optionList) {
  31.     ListIterator<? extends Displayable> gameModeListIterator = optionList.listIterator();
  32.     while (gameModeListIterator.hasNext()) {
  33.       cliWindow.println(gameModeListIterator.nextIndex() + 1 + ") " + gameModeListIterator
  34.           .next()
  35.           .getDisplayName());
  36.     }
  37.     cliWindow.moveToActionField();
  38.     int selected = 0;
  39.     while (selected == 0) {
  40.       selected = cliWindow.getRangeSelect(1, optionList.size());
  41.       if (selected == 0) {
  42.         cliWindow.clearActionField();
  43.         System.out.print("\u001b[1D");
  44.         System.out.print("\u001b[1A");
  45.         cliWindow.print("Please only enter numeric values!");
  46.         try {
  47.           Thread.sleep(2000);
  48.         } catch (InterruptedException e) {
  49.           throw new TerminationException("QuizClash was interrupted");
  50.         }
  51.         cliWindow.clearActionField();
  52.         System.out.print("\u001b[1D");
  53.         System.out.print("\u001b[1A");
  54.       }
  55.     }
  56.     return selected;
  57.   }
  58. }