blob: faf82e149f9c435589088c0062c791cdbaecdaad (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
|
package o1game.Server
// TODO: TLS/SSL / import javax.net.ssl.SSLServerSocketFactory
import java.lang.Thread.{currentThread, sleep}
import java.net.{ServerSocket, Socket}
import o1game.constants.*
import o1game.Model.Adventure
import o1game.Model.Entity
import java.lang.System.currentTimeMillis
import scala.util.Try
/** Converts this string to an array of bytes (probably for transmission).
*
* @param str the string to convert
* @return an array of bytes representing the string in UTF8.
*/
def stringToByteArray(str: String): Array[Byte] =
str.toVector.map(_.toByte).toArray
/** `Server` exists to initialize a server for the game
* and run it with its method `startServer`.
*
* @param port the TCP port the server should listen on
* @param maxClients the maximum number of clients that may be in the game
* simultaneously.
* @param timeLimit the time limit clients should have to execute their turns.
* @param joinAfterStart whether new clients are accepted after the game has
* been started
*/
class Server(
port: Int,
maxClients: Int,
val timeLimit: Int,
val joinAfterStart: Boolean
):
private val socket = ServerSocket(port)
private val clientGetter = ConnectionGetter(socket)
private val clients: Clients = Clients(maxClients)
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 =
while true do
this.serverStep()
sleep(POLL_INTERVAL)
private def serverStep(): Unit =
if this.adventure.isEmpty || this.joinAfterStart then
this.receiveNewClient()
this.readFromAll()
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 =>
c.getName.foreach(n => a.addPlayer(n))
)
startGameForClient(c)
)
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!
* Apparently guard clauses are bad because they use return or something,
* but assertions should be fine, as long as they enforce the function
* contract?
*/
private def startGameForClient(c: Client): Unit =
assert(this.adventure.isDefined)
c.gameStart()
val name = c.getName
val entity: Option[Entity] = name match
case Some(n) => this.adventure match
case Some(a) => a.getPlayer(n)
case None => None
case None => None
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`.
*
* @return describes if a client was added
*/
private def receiveNewClient(): Boolean =
this.clientGetter.newClient() match
case Some(c) =>
clients.addClient(Client(c))
true
case None =>
false
/** Sends `message` to all clients
*
* @param message the message to send
*/
private def writeToAll(message: String): Unit =
this.clients.mapAndRemove(c =>
val output = c.socket.getOutputStream
output.write(message.toVector.map(_.toByte).toArray)
output.flush()
)
private def writeToClient(message: String, client: Client): Unit =
val success = Try( () =>
val output = client.socket.getOutputStream
output.write(stringToByteArray(message))
output.flush()
)
if success.isFailure then
client.failedProtocol()
/** Sends every client's `dataToThisClient` to the client */
private def writeClientDataToClients(): Unit =
this.clients.mapAndRemove(c =>
val output = c.socket.getOutputStream
val data = c.dataToThisClient()
output.write(data.toVector.map(_.toByte).toArray)
output.flush()
)
/** Reads data sent by clients and stores it in the `Client`s of `clients` */
private def readFromAll(): Unit =
clients.mapAndRemove(c =>
val input = c.socket.getInputStream
while input.available() != 0 do
val bytesRead = input.read(buffer)
if bytesRead != -1 then
c.receiveData(buffer.take(bytesRead).toVector)
)
end Server
|