Итак, вот как вы можете сократить создание действия и использовать Map
, чтобы избежать расширенной конструкции case
.
Map
поддерживает отображение между реальным символом из вашего файла "script"и действие, которое будет выполнено;Я использовал существующий интерфейс Runnable
, чтобы обернуть это.
class AutoClicker {
private Robot robot;
private final Map<Character, Runnable> runnables = new HashMap<>();
public AutoClicker() {
try {
robot = new Robot();
} catch (AWTException ex) {
System.out.println("Problem in AutoClicker constructor: " + ex);
}
// fill the map
runnables.put(' ', click(KeyEvent.VK_SPACE));
runnables.put('.', click(KeyEvent.VK_PERIOD));
runnables.put('"', oneModifier(KeyEvent.VK_SHIFT, KeyEvent.VK_QUOTE));
runnables.put('/', click(KeyEvent.VK_SLASH));
runnables.put('\\', click(KeyEvent.VK_BACK_SLASH));
runnables.put('+', oneModifier(KeyEvent.VK_SHIFT, KeyEvent.VK_EQUALS));
runnables.put('!', oneModifier(KeyEvent.VK_SHIFT, KeyEvent.VK_1));
// the VK_<X> events are sequential, as are the keys being pressed
for (int i = 0; i < 10; i++) {
runnables.put((char) ('0' + i), click(KeyEvent.VK_0 + i));
}
// for upper case letters, you can add another for loop starting from 'A'
// and adding oneModifier(KeyEvent.VK_SHIFT, KeyEvent.VK_A + i) actions
}
// create an action. You might want to split that into two methods,
// one performing the click (without wrapping) and a parameter less.
private Runnable wrapInPressAndRelease(int button, Optional<Runnable> wrapped) {
return () -> {
robot.keyPress(button);
robot.delay(10);
// "click" does not run anything in between press/release,
// the modified click runs the click itself
wrapped.ifPresent(Runnable::run);
robot.keyRelease(button);
if (wrapped.isPresent()) {
// why is there delay after modified action?
robot.delay(10);
}
};
}
// you can inline those methods, I left them in to retain a connection to your original code
public Runnable click(int button) {
return wrapInPressAndRelease(button, Optional.empty());
}
public Runnable oneModifier(int pressing, int button) {
return wrapInPressAndRelease(pressing, Optional.of(click(button)));
}
public Runnable twoModifier(int pressing1, int pressing2, int button) {
// wrap the already wrapped click into another
return wrapInPressAndRelease(pressing1, Optional.of(oneModifier(pressing2, button)));
}
// now we can use the stored actions.
// not sure why you created the intermediate text int array, I removed that.
public void clickingENG(String tmp) {
for (int i = 0; i < tmp.length(); i++) {
char fromEngine = tmp.charAt(i);
Runnable robotAction = runnables.getOrDefault(fromEngine,
click(fromEngine - 32, Optional.empty()));
robotAction.run();
}
click(KeyEvent.VK_ENTER, Optional.empty()).run();
}
}