aboutsummaryrefslogtreecommitdiff
path: root/Week14 Route 66/src/com/camilstaps/route66/Crossing.java
diff options
context:
space:
mode:
authorCamil Staps2015-05-29 12:06:42 +0200
committerCamil Staps2015-05-29 12:06:42 +0200
commita68fa3c3c96c38b811755022089cb8aee2f5521c (patch)
treeef1463ba40bffedfb22aeca5547c7129c2dc3aca /Week14 Route 66/src/com/camilstaps/route66/Crossing.java
parentOverviewer without Map (diff)
Intermediate commit: works partially, but sometimes cars go over each other (Crossing.isAllowed() is not synchronized)
Diffstat (limited to 'Week14 Route 66/src/com/camilstaps/route66/Crossing.java')
-rw-r--r--Week14 Route 66/src/com/camilstaps/route66/Crossing.java61
1 files changed, 61 insertions, 0 deletions
diff --git a/Week14 Route 66/src/com/camilstaps/route66/Crossing.java b/Week14 Route 66/src/com/camilstaps/route66/Crossing.java
new file mode 100644
index 0000000..eba5bfe
--- /dev/null
+++ b/Week14 Route 66/src/com/camilstaps/route66/Crossing.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2015 Camil Staps
+ */
+package com.camilstaps.route66;
+
+import OO14route66.Direction;
+import OO14route66.Model;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author camilstaps
+ */
+public class Crossing {
+
+ private final Model model;
+ private Direction allowed;
+ private boolean waiting = false;
+ private int requests = 0;
+
+ public Crossing(Model model, Direction allowed) {
+ this.model = model;
+ this.allowed = allowed;
+ }
+
+ public Direction getAllowed() {
+ return allowed;
+ }
+
+ public synchronized void doSwitch() {
+ waiting = true;
+ while (!model.isNoCarsOnCrossing());
+ System.err.println("Switching");
+ if (allowed == Direction.East || allowed == Direction.West) {
+ allowed = Direction.North;
+ } else {
+ allowed = Direction.East;
+ }
+ requests = 0;
+ System.err.println("Switched to " + allowed);
+ waiting = false;
+ //notifyAll();
+ }
+
+ public boolean isAllowed(Direction direction) {
+ return !waiting && (direction == allowed || Direction.opposite(direction) == allowed);
+ }
+
+ public boolean doRequest() {
+ //if (++requests >= 2) {
+ if (waiting) {
+ return false;
+ }
+ doSwitch();
+ return true;
+ //}
+ //return false;
+ }
+
+}