-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
MultiplayerScreen.kt
363 lines (307 loc) · 12.7 KB
/
MultiplayerScreen.kt
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package com.unciv.ui.multiplayer
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.unciv.UncivGame
import com.unciv.logic.*
import com.unciv.logic.event.EventBus
import com.unciv.logic.multiplayer.*
import com.unciv.logic.multiplayer.storage.FileStorageRateLimitReached
import com.unciv.models.translations.tr
import com.unciv.ui.pickerscreens.PickerScreen
import com.unciv.ui.utils.*
import com.unciv.ui.crashhandling.launchCrashHandling
import com.unciv.ui.crashhandling.postCrashHandlingRunnable
import com.unciv.ui.images.ImageGetter
import com.unciv.ui.popup.Popup
import com.unciv.ui.popup.ToastPopup
import java.io.FileNotFoundException
import java.time.Duration
import java.time.Instant
import com.unciv.ui.utils.AutoScrollPane as ScrollPane
class MultiplayerScreen(previousScreen: BaseScreen) : PickerScreen() {
private var selectedGame: OnlineMultiplayerGame? = null
private val editButtonText = "Game settings"
private val editButton = createEditButton()
private val addGameText = "Add multiplayer game"
private val addGameButton = createAddGameButton()
private val copyGameIdText = "Copy game ID"
private val copyGameIdButton = createCopyGameIdButton()
private val copyUserIdText = "Copy user ID"
private val copyUserIdButton = createCopyUserIdButton()
private val refreshText = "Refresh list"
private val refreshButton = createRefreshButton()
private val rightSideTable = createRightSideTable()
private val leftSideTable = GameList(::selectGame)
private val events = EventBus.EventReceiver()
init {
setDefaultCloseAction(previousScreen)
scrollPane.setScrollingDisabled(false, true)
topTable.add(createMainContent()).row()
setupHelpButton()
setupRightSideButton()
events.receive(MultiplayerGameDeleted::class, {it.name == selectedGame?.name}) {
unselectGame()
}
game.onlineMultiplayer.requestUpdate()
}
private fun setupRightSideButton() {
rightSideButton.setText("Join game".tr())
rightSideButton.onClick { joinMultiplayerGame(selectedGame!!) }
}
private fun createRightSideTable(): Table {
val table = Table()
table.defaults().uniformX()
table.defaults().fillX()
table.defaults().pad(10.0f)
table.add(copyUserIdButton).padBottom(30f).row()
table.add(copyGameIdButton).row()
table.add(editButton).row()
table.add(addGameButton).padBottom(30f).row()
table.add(refreshButton).row()
return table
}
fun createRefreshButton(): TextButton {
val btn = refreshText.toTextButton()
btn.onClick { game.onlineMultiplayer.requestUpdate() }
return btn
}
fun createAddGameButton(): TextButton {
val btn = addGameText.toTextButton()
btn.onClick {
game.setScreen(AddMultiplayerGameScreen(this))
}
return btn
}
fun createEditButton(): TextButton {
val btn = editButtonText.toTextButton().apply { disable() }
btn.onClick {
game.setScreen(EditMultiplayerGameInfoScreen(selectedGame!!, this))
}
return btn
}
fun createCopyGameIdButton(): TextButton {
val btn = copyGameIdText.toTextButton().apply { disable() }
btn.onClick {
val gameInfo = selectedGame?.preview
if (gameInfo != null) {
Gdx.app.clipboard.contents = gameInfo.gameId
ToastPopup("Game ID copied to clipboard!", this)
}
}
return btn
}
private fun createCopyUserIdButton(): TextButton {
val btn = copyUserIdText.toTextButton()
btn.onClick {
Gdx.app.clipboard.contents = game.settings.userId
ToastPopup("UserID copied to clipboard", this)
}
return btn
}
private fun createMainContent(): Table {
val mainTable = Table()
mainTable.add(ScrollPane(leftSideTable).apply { setScrollingDisabled(true, false) }).center()
mainTable.add(rightSideTable)
return mainTable
}
private fun setupHelpButton() {
val tab = Table()
val helpButton = "Help".toTextButton()
helpButton.onClick {
val helpPopup = Popup(this)
helpPopup.addGoodSizedLabel("To create a multiplayer game, check the 'multiplayer' toggle in the New Game screen, and for each human player insert that player's user ID.")
.row()
helpPopup.addGoodSizedLabel("You can assign your own user ID there easily, and other players can copy their user IDs here and send them to you for you to include them in the game.")
.row()
helpPopup.addGoodSizedLabel("").row()
helpPopup.addGoodSizedLabel("Once you've created your game, the Game ID gets automatically copied to your clipboard so you can send it to the other players.")
.row()
helpPopup.addGoodSizedLabel("Players can enter your game by copying the game ID to the clipboard, and clicking on the 'Add multiplayer game' button")
.row()
helpPopup.addGoodSizedLabel("").row()
helpPopup.addGoodSizedLabel("The symbol of your nation will appear next to the game when it's your turn").row()
helpPopup.addCloseButton()
helpPopup.open()
}
tab.add(helpButton)
tab.x = (stage.width - helpButton.width)
tab.y = (stage.height - helpButton.height)
stage.addActor(tab)
}
fun joinMultiplayerGame(selectedGame: OnlineMultiplayerGame) {
val loadingGamePopup = Popup(this)
loadingGamePopup.addGoodSizedLabel("Loading latest game state...")
loadingGamePopup.open()
launchCrashHandling("JoinMultiplayerGame") {
try {
game.onlineMultiplayer.loadGame(selectedGame)
} catch (ex: Exception) {
val message = getLoadExceptionMessage(ex)
postCrashHandlingRunnable {
loadingGamePopup.reuseWith(message, true)
}
}
}
}
private fun unselectGame() {
selectedGame = null
editButton.disable()
copyGameIdButton.disable()
rightSideButton.disable()
descriptionLabel.setText("")
}
fun selectGame(name: String) {
val multiplayerGame = game.onlineMultiplayer.getGameByName(name)
if (multiplayerGame == null) {
// Should never happen
unselectGame()
return
}
selectedGame = multiplayerGame
if (multiplayerGame.preview != null) {
copyGameIdButton.enable()
} else {
copyGameIdButton.disable()
}
editButton.enable()
rightSideButton.enable()
descriptionLabel.setText(buildDescriptionText(multiplayerGame))
}
private fun buildDescriptionText(multiplayerGame: OnlineMultiplayerGame): StringBuilder {
val descriptionText = StringBuilder()
val ex = multiplayerGame.error
if (ex != null) {
descriptionText.append("Error while refreshing:".tr()).append(' ')
val message = getLoadExceptionMessage(ex)
descriptionText.appendLine(message.tr())
}
val lastUpdate = multiplayerGame.lastUpdate
descriptionText.appendLine("Last refresh: ${formattedElapsedTime(lastUpdate)} ago".tr())
val preview = multiplayerGame.preview
if (preview?.currentPlayer != null) {
val currentTurnStartTime = Instant.ofEpochMilli(preview.currentTurnStartTime)
descriptionText.appendLine("Current Turn: [${preview.currentPlayer}] since ${formattedElapsedTime(currentTurnStartTime)} ago".tr())
}
return descriptionText
}
private fun formattedElapsedTime(lastUpdate: Instant): String {
val durationToNow = Duration.between(lastUpdate, Instant.now())
val elapsedMinutes = durationToNow.toMinutes()
if (elapsedMinutes < 120) return "[$elapsedMinutes] [Minutes]"
val elapsedHours = durationToNow.toHours()
if (elapsedHours < 48) {
return "[${elapsedHours}] [Hours]"
} else {
return "[${durationToNow.toDays()}] [Days]"
}
}
fun getLoadExceptionMessage(ex: Exception) = when (ex) {
is FileStorageRateLimitReached -> "Server limit reached! Please wait for [${ex.limitRemainingSeconds}] seconds"
is FileNotFoundException -> "File could not be found on the multiplayer server"
is UncivShowableException -> ex.message!! // some of these seem to be translated already, but not all
else -> "Unhandled problem, [${ex::class.simpleName}] ${ex.message}"
}
}
private class GameList(
onSelected: (String) -> Unit
) : VerticalGroup() {
private val gameDisplays = mutableMapOf<String, GameDisplay>()
private val events = EventBus.EventReceiver()
init {
padTop(10f)
padBottom(10f)
events.receive(MultiplayerGameAdded::class) {
val multiplayerGame = UncivGame.Current.onlineMultiplayer.getGameByName(it.name)
if (multiplayerGame == null) return@receive
addGame(it.name, multiplayerGame.preview, multiplayerGame.error, onSelected)
}
events.receive(MultiplayerGameNameChanged::class) {
val gameDisplay = gameDisplays.remove(it.oldName)
if (gameDisplay == null) return@receive
gameDisplay.changeName(it.name)
gameDisplays[it.name] = gameDisplay
children.sort()
}
events.receive(MultiplayerGameDeleted::class) {
val gameDisplay = gameDisplays.remove(it.name)
if (gameDisplay == null) return@receive
gameDisplay.remove()
}
for (game in UncivGame.Current.onlineMultiplayer.games) {
addGame(game.name, game.preview, game.error, onSelected)
}
}
private fun addGame(name: String, preview: GameInfoPreview?, error: Exception?, onSelected: (String) -> Unit) {
val gameDisplay = GameDisplay(name, preview, error, onSelected)
gameDisplays[name] = gameDisplay
addActor(gameDisplay)
children.sort()
}
}
private class GameDisplay(
multiplayerGameName: String,
preview: GameInfoPreview?,
error: Exception?,
private val onSelected: (String) -> Unit
) : Table(), Comparable<GameDisplay> {
var gameName: String = multiplayerGameName
private set
val gameButton = TextButton(gameName, BaseScreen.skin)
val turnIndicator = createIndicator("OtherIcons/ExclamationMark")
val errorIndicator = createIndicator("StatIcons/Malcontent")
val refreshIndicator = createIndicator("EmojiIcons/Turn")
val statusIndicators = HorizontalGroup()
val events = EventBus.EventReceiver()
init {
padBottom(5f)
updateTurnIndicator(preview)
updateErrorIndicator(error != null)
add(statusIndicators)
add(gameButton)
onClick { onSelected(gameName) }
events.receive(MultiplayerGameUpdateStarted::class, { it.name == gameName }, {
statusIndicators.addActor(refreshIndicator)
})
events.receive(MultiplayerGameUpdateUnchanged::class, { it.name == gameName }, {
refreshIndicator.remove()
})
events.receive(MultiplayerGameUpdated::class, { it.name == gameName }) {
updateTurnIndicator(it.preview)
updateErrorIndicator(false)
refreshIndicator.remove()
}
events.receive(MultiplayerGameUpdateFailed::class, { it.name == gameName }) {
updateErrorIndicator(true)
refreshIndicator.remove()
}
}
fun changeName(newName: String) {
gameName = newName
gameButton.setText(newName)
}
private fun updateTurnIndicator(preview: GameInfoPreview?) {
if (preview?.isUsersTurn() == true) {
statusIndicators.addActor(turnIndicator)
} else {
turnIndicator.remove()
}
}
private fun updateErrorIndicator(hasError: Boolean) {
if (hasError) {
statusIndicators.addActor(errorIndicator)
} else {
errorIndicator.remove()
}
}
private fun createIndicator(imagePath: String): Actor {
val image = ImageGetter.getImage(imagePath)
image.setSize(50f)
val container = Container(image)
container.padRight(5f)
return container
}
override fun compareTo(other: GameDisplay): Int = gameName.compareTo(other.gameName)
override fun equals(other: Any?): Boolean = (other is GameDisplay) && (gameName == other.gameName)
override fun hashCode(): Int = gameName.hashCode()
}