From 9c878306b4756615484328dd53af941d1a9aa6a1 Mon Sep 17 00:00:00 2001 From: mike Date: Sat, 15 Apr 2023 19:36:36 -0400 Subject: [PATCH] Updated ConnectedClient --- .../src/ca/cosc3p91/a4/game/GameEngine.java | 6 +++--- .../src/ca/cosc3p91/a4/util/network/Server.java | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Assignment 4/src/ca/cosc3p91/a4/game/GameEngine.java b/Assignment 4/src/ca/cosc3p91/a4/game/GameEngine.java index 1aed480..1ae1fca 100644 --- a/Assignment 4/src/ca/cosc3p91/a4/game/GameEngine.java +++ b/Assignment 4/src/ca/cosc3p91/a4/game/GameEngine.java @@ -140,9 +140,9 @@ public class GameEngine { } public void updateMap(Map map) { - for (Building b : map.contains){ - if ((b instanceof ResourceBuilding)) { - ((ResourceBuilding) b).update(map.getTownHall()); + for (int i = 0; i < map.contains.size(); i++) { + if ((map.contains.get(i) instanceof ResourceBuilding)) { + ((ResourceBuilding) map.contains.get(i)).update(map.getTownHall()); } } } diff --git a/Assignment 4/src/ca/cosc3p91/a4/util/network/Server.java b/Assignment 4/src/ca/cosc3p91/a4/util/network/Server.java index 6432fc9..c1f81f0 100644 --- a/Assignment 4/src/ca/cosc3p91/a4/util/network/Server.java +++ b/Assignment 4/src/ca/cosc3p91/a4/util/network/Server.java @@ -10,6 +10,7 @@ import java.rmi.ServerException; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Queue; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; public class Server implements Runnable { @@ -84,11 +85,13 @@ public class Server implements Runnable { private final int port; private final Queue pendingRequests = new PriorityQueue<>(); private final ReentrantLock requestLock = new ReentrantLock(); + private final AtomicBoolean allowUpdate; private final HashMap sentMessages = new HashMap<>(); private final DatagramSocket serverSocket; private final long clientID; private volatile boolean running = true; private final Thread processingThread; + private final Thread gameEngineThread; private final Map clientMap; public ConnectedClient(DatagramSocket serverSocket, GameEngine engine, long clientID, long messageID, InetAddress address, int port){ @@ -97,8 +100,17 @@ public class Server implements Runnable { this.port = port; this.clientID = clientID; this.clientMap = engine.generateInitialMap(); + this.allowUpdate = new AtomicBoolean(true); processingThread = new Thread(this); processingThread.start(); + gameEngineThread = new Thread(() -> { + while (true) { + if (this.allowUpdate.get()) { + engine.updateMap(clientMap); + } + } + }); + gameEngineThread.start(); sendMessage(new Message.Sent(PacketTable.ACK, clientID, messageID)); } @@ -135,7 +147,9 @@ public class Server implements Runnable { requestLock.lock(); if (!pendingRequests.isEmpty()) { Message.Received request = pendingRequests.remove(); + allowUpdate.set(false); processRequest(request); + allowUpdate.set(true); } requestLock.unlock();