Created
April 27, 2023 10:27
-
-
Save zjor/403a0839fda13ca1b11ce33cd05fdff2 to your computer and use it in GitHub Desktop.
Implementation of a state machine, an example of a traffic light
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.zjor; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.ScheduledExecutorService; | |
import java.util.concurrent.TimeUnit; | |
import static com.github.zjor.Sandbox.State.GREEN; | |
import static com.github.zjor.Sandbox.State.RED; | |
import static com.github.zjor.Sandbox.State.RED_YELLOW; | |
import static com.github.zjor.Sandbox.State.YELLOW; | |
import static com.github.zjor.Sandbox.Transition.of; | |
/** | |
* 🔴🟡🟢⚪ | |
*/ | |
public class Sandbox { | |
public enum State { | |
RED, | |
YELLOW, | |
RED_YELLOW, | |
GREEN | |
} | |
public record Transition(State next, long delay) { | |
public static Transition of(State next, long delay) { | |
return new Transition(next, delay); | |
} | |
} | |
private Map<State, Transition> transitions = new HashMap<>(); | |
{ | |
transitions.put(RED, of(RED_YELLOW, 2000L)); | |
transitions.put(RED_YELLOW, of(GREEN, 500L)); | |
transitions.put(GREEN, of(YELLOW, 1500L)); | |
transitions.put(YELLOW, of(RED, 500L)); | |
} | |
private State state = RED; | |
private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); | |
public void render(State state) { | |
switch (state) { | |
case RED -> System.out.print("\r[ \uD83D\uDD34⚪⚪ ]==|"); | |
case RED_YELLOW -> System.out.print("\r[ \uD83D\uDD34\uD83D\uDFE1⚪ ]==|"); | |
case GREEN -> System.out.print("\r[ ⚪⚪\uD83D\uDFE2 ]==|"); | |
case YELLOW -> System.out.print("\r[ ⚪\uD83D\uDFE1⚪ ]==|"); | |
} | |
} | |
public void start() { | |
executorService.schedule(() -> tick(), 0, TimeUnit.MILLISECONDS); | |
} | |
public void tick() { | |
var t = transitions.get(state); | |
render(state); | |
state = t.next; | |
executorService.schedule(() -> tick(), t.delay, TimeUnit.MILLISECONDS); | |
} | |
/* | |
(state, condition) -> (action, state') | |
red -> red_yellow -> green -> yellow | |
(state, delay, state') | |
*/ | |
public static void main(String[] args) { | |
(new Sandbox()).start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment