aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/Server/Server.scala
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/scala/Server/Server.scala')
-rw-r--r--src/main/scala/Server/Server.scala25
1 files changed, 22 insertions, 3 deletions
diff --git a/src/main/scala/Server/Server.scala b/src/main/scala/Server/Server.scala
index 2f78e6b..faf82e1 100644
--- a/src/main/scala/Server/Server.scala
+++ b/src/main/scala/Server/Server.scala
@@ -3,13 +3,13 @@ package o1game.Server
// TODO: TLS/SSL / import javax.net.ssl.SSLServerSocketFactory
-import java.lang.Thread.sleep
+import java.lang.Thread.{currentThread, sleep}
import java.net.{ServerSocket, Socket}
import o1game.constants.*
import o1game.Model.Adventure
import o1game.Model.Entity
-import scala.util.Try
+import java.lang.System.currentTimeMillis
import scala.util.Try
/** Converts this string to an array of bytes (probably for transmission).
@@ -43,6 +43,7 @@ class Server(
private val buffer: Array[Byte] = Array.ofDim(1024)
private var bufferIndex = 0
private var adventure: Option[Adventure] = None
+ private var previousTurn = 0.0
/** Starts the server. Won't terminate under normal circumstances. */
def startServer(): Unit =
@@ -57,6 +58,11 @@ class Server(
this.writeClientDataToClients()
this.clients.removeNonCompliant()
this.clients.foreach(_.interpretData())
+ if this.canExecuteTurns then
+ println("taking turns")
+ this.clients.inRandomOrder(_.act())
+ this.writeToAll("next turn!")
+ this.previousTurn = currentTimeMillis() / 1000
if this.adventure.isDefined && this.joinAfterStart then
this.clients.foreach( c => if c.isReadyForGameStart then
this.adventure.foreach(a =>
@@ -67,6 +73,7 @@ class Server(
else if this.adventure.isEmpty && !this.clients.isEmpty && this.clients.forall(_.isReadyForGameStart) then
this.adventure = Some(Adventure(this.clients.names))
this.clients.foreach(startGameForClient(_))
+ this.previousTurn = currentTimeMillis() / 1000
/** Helper function to start the game for the specified client c.
* MAY ONLY BE USED IF `this.adventure` is Some!
@@ -83,10 +90,22 @@ class Server(
case Some(a) => a.getPlayer(n)
case None => None
case None => None
- entity.map(c.giveEntity(_))
+ entity.foreach(c.giveEntity(_))
this.writeToClient(s"$timeLimit", c)
+ /** Helper function to determine if the next turn can be taken */
+ private def canExecuteTurns: Boolean =
+ val requirement1 = this.adventure.isDefined
+ val requirement2 = !this.clients.isEmpty // nice! you can just return
+ // to the game after everyone
+ // left and everything is just
+ // as before!
+ val allPlayersReady = this.clients.forall(_.isReadyToAct)
+ val requirement3 = (allPlayersReady
+ || currentTimeMillis() / 1000 >= previousTurn + timeLimit)
+ requirement1 && requirement2 && requirement3
+
/** Receives a new client and stores it in `clients`.
*