Compare commits
1 Commits
4.6.1
...
a452e7753b
| Author | SHA1 | Date | |
|---|---|---|---|
| a452e7753b |
54
CHANGELOG.md
54
CHANGELOG.md
@@ -133,57 +133,3 @@
|
|||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
* **api:** Fixed a bug where the game would reload on game start ([#81](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/81)) ([9738a04](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/9738a04b7a3c63c8cd1450e563ec04823fb3c35a))
|
* **api:** Fixed a bug where the game would reload on game start ([#81](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/81)) ([9738a04](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/9738a04b7a3c63c8cd1450e563ec04823fb3c35a))
|
||||||
## (2025-11-23)
|
|
||||||
|
|
||||||
### ⚠ BREAKING CHANGES
|
|
||||||
|
|
||||||
* **websocket:** Implement WebSocket connection and event handling (#82)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **websocket:** Implement WebSocket connection and event handling ([#82](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/82)) ([8ca909d](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/8ca909db522dd7108a3e40ce84811eaf8695eaa5))
|
|
||||||
## (2025-11-24)
|
|
||||||
## (2025-11-26)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **api:** Implement received hand event handling and UI updates ([#83](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/83)) ([52e5033](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/52e5033afca344ae40a644196555a9655913710a)), closes [#76](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/76)
|
|
||||||
* **base:** Fixed logic for websockets and added GameStateEvent. Might've caused instability on other feature branches! ([#84](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/84)) ([b81bb3d](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/b81bb3d0aeb8500a9d7417a10e24e7f8a17d71d2))
|
|
||||||
## (2025-11-26)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **api:** Implemented card played event via websocket ([#85](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/85)) ([3c0828f](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/3c0828fdbeb507706b86f1662476c46e760533e4))
|
|
||||||
## (2025-11-26)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **api:** Implemented session closed and kick event via websocket ([#87](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/87)) ([1ef5e8a](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/1ef5e8a72fdf8a3d1ae624c8c3d7c6595017bc6f))
|
|
||||||
## (2025-12-01)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **api:** Implemented turn event via websocket ([#86](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/86)) ([2aee79b](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/2aee79bb6887008397aa0780d1d74ce96af1c202))
|
|
||||||
* GameState to Title Mapping BAC-1 ([#92](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/92)) ([6e17328](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/6e17328846745375482c97383b143d86a86e7f32))
|
|
||||||
* **ui:** Implement countless feature using the SJWP ([#89](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/89)) ([1f96290](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/1f962903712163543fd4f98e696be5e7e29d88a6))
|
|
||||||
* **ui:** Popups ([#91](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/91)) ([0037820](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/003782090509bca1c5022c308231b7560dd9b23d))
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* **api:** Fixed websocket routing ([#88](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/88)) ([46c96d4](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/46c96d4ceb935ac91fc515a1fdaef195e5ebc0a7))
|
|
||||||
* **api:** fixes - reimplemented animations ([#90](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/90)) ([cfcd967](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/cfcd967ce08ecf07f3f06826c337f684eb3b0c5f))
|
|
||||||
## (2025-12-01)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **api:** BAC-10 Websockets - Kick Users ([#93](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/93)) ([0541bb5](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/0541bb58d19efd98d134b3d0412f39b4b1001783))
|
|
||||||
## (2025-12-01)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* **api:** BAC-11 Websocket - Return to Lobby ([#94](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/94)) ([fd2467a](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/fd2467a9ea22dca64d5152a5a3e6db86d9a6f345))
|
|
||||||
## (2025-12-01)
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* **api:** BAC-23 Remove old polling code ([#95](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/95)) ([a55f0b4](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/a55f0b4b6164a47e3524422650ed99d10f9c8b0d))
|
|
||||||
|
|||||||
Submodule knockoutwhist updated: ef7397f7f1...ec94ecd46c
@@ -219,10 +219,10 @@ body {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#next-players-container {
|
#nextPlayers {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: flex-start;
|
align-items: center;
|
||||||
height: 0;
|
height: 0;
|
||||||
|
|
||||||
p {
|
p {
|
||||||
@@ -231,6 +231,10 @@ body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#invisible {
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
#selecttrumpsuit {
|
#selecttrumpsuit {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package controllers
|
package controllers
|
||||||
|
|
||||||
import auth.{AuthAction, AuthenticatedRequest}
|
import auth.{AuthAction, AuthenticatedRequest}
|
||||||
import de.knockoutwhist.control.GameState
|
|
||||||
import de.knockoutwhist.control.GameState.*
|
import de.knockoutwhist.control.GameState.*
|
||||||
import exceptions.*
|
import exceptions.*
|
||||||
import logic.PodManager
|
import logic.PodManager
|
||||||
@@ -12,7 +11,6 @@ import play.api.*
|
|||||||
import play.api.libs.json.{JsValue, Json}
|
import play.api.libs.json.{JsValue, Json}
|
||||||
import play.api.mvc.*
|
import play.api.mvc.*
|
||||||
import play.twirl.api.Html
|
import play.twirl.api.Html
|
||||||
import util.GameUtil
|
|
||||||
|
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import javax.inject.*
|
import javax.inject.*
|
||||||
@@ -31,10 +29,10 @@ class IngameController @Inject()(
|
|||||||
game match {
|
game match {
|
||||||
case Some(g) =>
|
case Some(g) =>
|
||||||
val results = Try {
|
val results = Try {
|
||||||
IngameController.returnInnerHTML(g, g.logic.getCurrentState, request.user)
|
returnInnerHTML(g, request.user)
|
||||||
}
|
}
|
||||||
if (results.isSuccess) {
|
if (results.isSuccess) {
|
||||||
Ok(views.html.main("Knockout Whist - " + GameUtil.stateToTitle(g.logic.getCurrentState))(results.get))
|
Ok(views.html.main("In-Game - Knockout Whist")(results.get))
|
||||||
} else {
|
} else {
|
||||||
InternalServerError(results.failed.get.getMessage)
|
InternalServerError(results.failed.get.getMessage)
|
||||||
}
|
}
|
||||||
@@ -43,6 +41,34 @@ class IngameController @Inject()(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def returnInnerHTML(gameLobby: GameLobby, user: User): Html = {
|
||||||
|
gameLobby.logic.getCurrentState match {
|
||||||
|
case Lobby => views.html.lobby.lobby(Some(user), gameLobby)
|
||||||
|
case InGame =>
|
||||||
|
views.html.ingame.ingame(
|
||||||
|
gameLobby.getPlayerByUser(user),
|
||||||
|
gameLobby
|
||||||
|
)
|
||||||
|
case SelectTrump =>
|
||||||
|
views.html.ingame.selecttrump(
|
||||||
|
gameLobby.getPlayerByUser(user),
|
||||||
|
gameLobby
|
||||||
|
)
|
||||||
|
case TieBreak =>
|
||||||
|
views.html.ingame.tie(
|
||||||
|
gameLobby.getPlayerByUser(user),
|
||||||
|
gameLobby
|
||||||
|
)
|
||||||
|
case FinishedMatch =>
|
||||||
|
views.html.ingame.finishedMatch(
|
||||||
|
Some(user),
|
||||||
|
gameLobby
|
||||||
|
)
|
||||||
|
case _ =>
|
||||||
|
throw new IllegalStateException(s"Invalid game state for in-game view. GameId: ${gameLobby.id}" + s" State: ${gameLobby.logic.getCurrentState}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
def startGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
|
def startGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
|
||||||
val game = PodManager.getGame(gameId)
|
val game = PodManager.getGame(gameId)
|
||||||
val result = Try {
|
val result = Try {
|
||||||
@@ -57,7 +83,7 @@ class IngameController @Inject()(
|
|||||||
Ok(Json.obj(
|
Ok(Json.obj(
|
||||||
"status" -> "success",
|
"status" -> "success",
|
||||||
"redirectUrl" -> routes.IngameController.game(gameId).url,
|
"redirectUrl" -> routes.IngameController.game(gameId).url,
|
||||||
"content" -> IngameController.returnInnerHTML(game.get, game.get.logic.getCurrentState, request.user).toString()
|
"content" -> returnInnerHTML(game.get, request.user).toString()
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
val throwable = result.failed.get
|
val throwable = result.failed.get
|
||||||
@@ -90,7 +116,7 @@ class IngameController @Inject()(
|
|||||||
val game = PodManager.getGame(gameId)
|
val game = PodManager.getGame(gameId)
|
||||||
val playerToKickUUID = UUID.fromString(playerToKick)
|
val playerToKickUUID = UUID.fromString(playerToKick)
|
||||||
val result = Try {
|
val result = Try {
|
||||||
game.get.leaveGame(playerToKickUUID, true)
|
game.get.leaveGame(playerToKickUUID)
|
||||||
}
|
}
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
Ok(Json.obj(
|
Ok(Json.obj(
|
||||||
@@ -108,7 +134,7 @@ class IngameController @Inject()(
|
|||||||
def leaveGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
|
def leaveGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
|
||||||
val game = PodManager.getGame(gameId)
|
val game = PodManager.getGame(gameId)
|
||||||
val result = Try {
|
val result = Try {
|
||||||
game.get.leaveGame(request.user.id, false)
|
game.get.leaveGame(request.user.id)
|
||||||
}
|
}
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
Ok(Json.obj(
|
Ok(Json.obj(
|
||||||
@@ -410,35 +436,3 @@ class IngameController @Inject()(
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
object IngameController {
|
|
||||||
|
|
||||||
def returnInnerHTML(gameLobby: GameLobby, gameState: GameState, user: User): Html = {
|
|
||||||
gameState match {
|
|
||||||
case Lobby => views.html.lobby.lobby(Some(user), gameLobby)
|
|
||||||
case InGame =>
|
|
||||||
views.html.ingame.ingame(
|
|
||||||
gameLobby.getPlayerByUser(user),
|
|
||||||
gameLobby
|
|
||||||
)
|
|
||||||
case SelectTrump =>
|
|
||||||
views.html.ingame.selecttrump(
|
|
||||||
gameLobby.getPlayerByUser(user),
|
|
||||||
gameLobby
|
|
||||||
)
|
|
||||||
case TieBreak =>
|
|
||||||
views.html.ingame.tie(
|
|
||||||
gameLobby.getPlayerByUser(user),
|
|
||||||
gameLobby
|
|
||||||
)
|
|
||||||
case FinishedMatch =>
|
|
||||||
views.html.ingame.finishedMatch(
|
|
||||||
Some(user),
|
|
||||||
gameLobby
|
|
||||||
)
|
|
||||||
case _ =>
|
|
||||||
throw new IllegalStateException(s"Invalid game state for in-game view. GameId: ${gameLobby.id}" + s" State: ${gameLobby.logic.getCurrentState}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ import javax.inject.*
|
|||||||
@Singleton
|
@Singleton
|
||||||
class MainMenuController @Inject()(
|
class MainMenuController @Inject()(
|
||||||
val controllerComponents: ControllerComponents,
|
val controllerComponents: ControllerComponents,
|
||||||
val authAction: AuthAction
|
val authAction: AuthAction,
|
||||||
|
val ingameController: IngameController
|
||||||
) extends BaseController {
|
) extends BaseController {
|
||||||
|
|
||||||
// Pass the request-handling function directly to authAction (no nested Action)
|
// Pass the request-handling function directly to authAction (no nested Action)
|
||||||
@@ -45,7 +46,7 @@ class MainMenuController @Inject()(
|
|||||||
Ok(Json.obj(
|
Ok(Json.obj(
|
||||||
"status" -> "success",
|
"status" -> "success",
|
||||||
"redirectUrl" -> routes.IngameController.game(gameLobby.id).url,
|
"redirectUrl" -> routes.IngameController.game(gameLobby.id).url,
|
||||||
"content" -> IngameController.returnInnerHTML(gameLobby, gameLobby.logic.getCurrentState, request.user).toString
|
"content" -> ingameController.returnInnerHTML(gameLobby, request.user).toString
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
BadRequest(Json.obj(
|
BadRequest(Json.obj(
|
||||||
@@ -69,7 +70,7 @@ class MainMenuController @Inject()(
|
|||||||
Ok(Json.obj(
|
Ok(Json.obj(
|
||||||
"status" -> "success",
|
"status" -> "success",
|
||||||
"redirectUrl" -> routes.IngameController.game(g.id).url,
|
"redirectUrl" -> routes.IngameController.game(g.id).url,
|
||||||
"content" -> IngameController.returnInnerHTML(g, g.logic.getCurrentState, request.user).toString
|
"content" -> ingameController.returnInnerHTML(g, request.user).toString
|
||||||
))
|
))
|
||||||
case None =>
|
case None =>
|
||||||
NotFound(Json.obj(
|
NotFound(Json.obj(
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
package events
|
|
||||||
|
|
||||||
import model.users.User
|
|
||||||
|
|
||||||
case class KickEvent(user: User) extends UserEvent(user) {
|
|
||||||
|
|
||||||
override def id: String = "KickEvent"
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package events
|
|
||||||
|
|
||||||
import model.users.User
|
|
||||||
|
|
||||||
case class LeftEvent(user: User) extends UserEvent(user) {
|
|
||||||
|
|
||||||
override def id: String = "LeftEvent"
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package events
|
|
||||||
|
|
||||||
import de.knockoutwhist.utils.events.SimpleEvent
|
|
||||||
|
|
||||||
case class LobbyUpdateEvent() extends SimpleEvent {
|
|
||||||
|
|
||||||
override def id: String = "LobbyUpdateEvent"
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package events
|
|
||||||
|
|
||||||
import de.knockoutwhist.utils.events.SimpleEvent
|
|
||||||
import model.users.User
|
|
||||||
|
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
abstract class UserEvent(user: User) extends SimpleEvent {
|
|
||||||
|
|
||||||
def userId: UUID = user.id
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -10,14 +10,13 @@ import de.knockoutwhist.player.Playertype.HUMAN
|
|||||||
import de.knockoutwhist.player.{AbstractPlayer, PlayerFactory}
|
import de.knockoutwhist.player.{AbstractPlayer, PlayerFactory}
|
||||||
import de.knockoutwhist.rounds.{Match, Round, Trick}
|
import de.knockoutwhist.rounds.{Match, Round, Trick}
|
||||||
import de.knockoutwhist.utils.events.{EventListener, SimpleEvent}
|
import de.knockoutwhist.utils.events.{EventListener, SimpleEvent}
|
||||||
import events.{KickEvent, LeftEvent, LobbyUpdateEvent, UserEvent}
|
|
||||||
import exceptions.*
|
import exceptions.*
|
||||||
import logic.PodManager
|
import logic.PodManager
|
||||||
import model.sessions.{InteractionType, UserSession}
|
import model.sessions.{InteractionType, UserSession}
|
||||||
import model.users.User
|
import model.users.User
|
||||||
import play.api.libs.json.{JsObject, Json}
|
import play.api.libs.json.{JsObject, Json}
|
||||||
|
|
||||||
import java.util.{Timer, TimerTask, UUID}
|
import java.util.UUID
|
||||||
import scala.collection.mutable
|
import scala.collection.mutable
|
||||||
import scala.collection.mutable.ListBuffer
|
import scala.collection.mutable.ListBuffer
|
||||||
|
|
||||||
@@ -45,7 +44,7 @@ class GameLobby private(
|
|||||||
)
|
)
|
||||||
users += (user.id -> userSession)
|
users += (user.id -> userSession)
|
||||||
PodManager.registerUserToGame(user, id)
|
PodManager.registerUserToGame(user, id)
|
||||||
logic.invoke(LobbyUpdateEvent())
|
//TODO : transmit Lobby Update transmitToAll()
|
||||||
userSession
|
userSession
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,8 +52,6 @@ class GameLobby private(
|
|||||||
event match {
|
event match {
|
||||||
case event: PlayerEvent =>
|
case event: PlayerEvent =>
|
||||||
users.get(event.playerId).foreach(session => session.updatePlayer(event))
|
users.get(event.playerId).foreach(session => session.updatePlayer(event))
|
||||||
case event: UserEvent =>
|
|
||||||
users.get(event.userId).foreach(session => session.updatePlayer(event))
|
|
||||||
case event: GameStateChangeEvent =>
|
case event: GameStateChangeEvent =>
|
||||||
if (event.oldState == MainMenu && event.newState == Lobby) {
|
if (event.oldState == MainMenu && event.newState == Lobby) {
|
||||||
return
|
return
|
||||||
@@ -96,9 +93,8 @@ class GameLobby private(
|
|||||||
* Remove the user from the game lobby.
|
* Remove the user from the game lobby.
|
||||||
*
|
*
|
||||||
* @param user the user who wants to leave the game.
|
* @param user the user who wants to leave the game.
|
||||||
* @param kicked whether the user was kicked or left voluntarily.
|
|
||||||
*/
|
*/
|
||||||
def leaveGame(userId: UUID, kicked: Boolean): Unit = {
|
def leaveGame(userId: UUID): Unit = {
|
||||||
val sessionOpt = users.get(userId)
|
val sessionOpt = users.get(userId)
|
||||||
if (sessionOpt.isEmpty) {
|
if (sessionOpt.isEmpty) {
|
||||||
throw new NotInThisGameException("You are not in this game!")
|
throw new NotInThisGameException("You are not in this game!")
|
||||||
@@ -109,14 +105,16 @@ class GameLobby private(
|
|||||||
PodManager.removeGame(id)
|
PodManager.removeGame(id)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (kicked) {
|
sessionOpt.get.websocketActor.foreach(act => act.transmitJsonToClient(Json.obj(
|
||||||
logic.invoke(KickEvent(sessionOpt.get.user))
|
"id" -> "-1",
|
||||||
} else {
|
"event" -> "SessionClosed",
|
||||||
logic.invoke(LeftEvent(sessionOpt.get.user))
|
"data" -> Json.obj(
|
||||||
}
|
"reason" -> "You left the game (or got kicked)."
|
||||||
|
)
|
||||||
|
)))
|
||||||
users.remove(userId)
|
users.remove(userId)
|
||||||
PodManager.unregisterUserFromGame(sessionOpt.get.user)
|
PodManager.unregisterUserFromGame(sessionOpt.get.user)
|
||||||
logic.invoke(LobbyUpdateEvent())
|
//TODO: transmit Lobby Update transmitToAll()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import de.knockoutwhist.events.player.{RequestCardEvent, RequestTieChoiceEvent,
|
|||||||
import de.knockoutwhist.utils.events.SimpleEvent
|
import de.knockoutwhist.utils.events.SimpleEvent
|
||||||
import logic.game.GameLobby
|
import logic.game.GameLobby
|
||||||
import model.users.User
|
import model.users.User
|
||||||
import play.api.libs.json.{JsObject, JsValue}
|
import play.api.libs.json.JsObject
|
||||||
|
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import java.util.concurrent.locks.ReentrantLock
|
import java.util.concurrent.locks.ReentrantLock
|
||||||
@@ -26,7 +26,6 @@ class UserSession(val user: User, val host: Boolean, val gameLobby: GameLobby) e
|
|||||||
else canInteract = Some(InteractionType.Card)
|
else canInteract = Some(InteractionType.Card)
|
||||||
case _ =>
|
case _ =>
|
||||||
}
|
}
|
||||||
websocketActor.foreach(_.transmitEventToClient(event))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override def id: UUID = user.id
|
override def id: UUID = user.id
|
||||||
@@ -39,49 +38,14 @@ class UserSession(val user: User, val host: Boolean, val gameLobby: GameLobby) e
|
|||||||
|
|
||||||
def handleWebResponse(eventType: String, data: JsObject): Unit = {
|
def handleWebResponse(eventType: String, data: JsObject): Unit = {
|
||||||
lock.lock()
|
lock.lock()
|
||||||
val result = Try {
|
Try {
|
||||||
eventType match {
|
eventType match {
|
||||||
case "ping" =>
|
case "Ping" =>
|
||||||
// No action needed for Ping
|
// No action needed for Ping
|
||||||
()
|
()
|
||||||
case "StartGame" =>
|
|
||||||
gameLobby.startGame(user)
|
|
||||||
case "PlayCard" =>
|
|
||||||
val maybeCardIndex: Option[String] = (data \ "cardindex").asOpt[String]
|
|
||||||
maybeCardIndex match {
|
|
||||||
case Some(index) =>
|
|
||||||
val session = gameLobby.getUserSession(user.id)
|
|
||||||
gameLobby.playCard(session, index.toInt)
|
|
||||||
case None =>
|
|
||||||
println("Card Index not found or is not a number.")
|
|
||||||
}
|
|
||||||
case "PickTrumpsuit" =>
|
|
||||||
val maybeSuitIndex: Option[Int] = (data \ "suitIndex").asOpt[Int]
|
|
||||||
maybeSuitIndex match {
|
|
||||||
case Some(index) =>
|
|
||||||
val session = gameLobby.getUserSession(user.id)
|
|
||||||
gameLobby.selectTrump(session, index)
|
|
||||||
case None =>
|
|
||||||
println("Card Index not found or is not a number.")
|
|
||||||
}
|
|
||||||
case "KickPlayer" =>
|
|
||||||
val maybePlayerId: Option[String] = (data \ "playerId").asOpt[String]
|
|
||||||
maybePlayerId match {
|
|
||||||
case Some(id) =>
|
|
||||||
val playerUUID = UUID.fromString(id)
|
|
||||||
gameLobby.leaveGame(playerUUID, true)
|
|
||||||
case None =>
|
|
||||||
println("Player ID not found or is not a valid UUID.")
|
|
||||||
}
|
|
||||||
case "ReturnToLobby" =>
|
|
||||||
gameLobby.returnToLobby(this)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
lock.unlock()
|
lock.unlock()
|
||||||
if (result.isFailure) {
|
|
||||||
val throwable = result.failed.get
|
|
||||||
throw throwable
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,19 +12,13 @@ class UserWebsocketActor(
|
|||||||
session: UserSession
|
session: UserSession
|
||||||
) extends Actor {
|
) extends Actor {
|
||||||
|
|
||||||
{
|
|
||||||
session.lock.lock()
|
|
||||||
if (session.websocketActor.isDefined) {
|
if (session.websocketActor.isDefined) {
|
||||||
val otherWebsocket = session.websocketActor.get
|
session.websocketActor.foreach(actor => actor.transmitTextToClient("Error: Multiple websocket connections detected. Closing this connection."))
|
||||||
otherWebsocket.transmitTextToClient("Error: Multiple websocket connections detected. Closing your connection.")
|
context.stop(self)
|
||||||
context.stop(otherWebsocket.self)
|
} else {
|
||||||
transmitTextToClient("Previous websocket connection closed. You are now connected.")
|
|
||||||
}
|
|
||||||
session.websocketActor = Some(this)
|
session.websocketActor = Some(this)
|
||||||
session.lock.unlock()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
override def receive: Receive = {
|
override def receive: Receive = {
|
||||||
case msg: String =>
|
case msg: String =>
|
||||||
val jsonObject = Try {
|
val jsonObject = Try {
|
||||||
@@ -67,10 +61,6 @@ class UserWebsocketActor(
|
|||||||
))
|
))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val statusOpt = (json \ "status").asOpt[String]
|
|
||||||
if (statusOpt.isDefined) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val event = eventOpt.get
|
val event = eventOpt.get
|
||||||
val data = (json \ "data").asOpt[JsObject].getOrElse(Json.obj())
|
val data = (json \ "data").asOpt[JsObject].getOrElse(Json.obj())
|
||||||
val result = Try {
|
val result = Try {
|
||||||
@@ -92,12 +82,13 @@ class UserWebsocketActor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def transmitJsonToClient(jsonObj: JsValue): Unit = {
|
def transmitJsonToClient(jsonObj: JsObject): Unit = {
|
||||||
transmitTextToClient(jsonObj.toString())
|
out ! jsonObj.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
def transmitEventToClient(event: SimpleEvent): Unit = {
|
def transmitEventToClient(event: SimpleEvent): Unit = {
|
||||||
transmitJsonToClient(WebsocketEventMapper.toJson(event, session))
|
val jsonString = WebsocketEventMapper.toJson(event)
|
||||||
|
out ! jsonString
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package model.users
|
package model.users
|
||||||
|
|
||||||
|
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
case class User(
|
case class User(
|
||||||
@@ -17,4 +16,5 @@ case class User(
|
|||||||
private def withPasswordHash(newPasswordHash: String): User = {
|
private def withPasswordHash(newPasswordHash: String): User = {
|
||||||
this.copy(passwordHash = newPasswordHash)
|
this.copy(passwordHash = newPasswordHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,5 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import de.knockoutwhist.control.GameState
|
|
||||||
import de.knockoutwhist.control.GameState.{FinishedMatch, InGame, Lobby, MainMenu, SelectTrump, TieBreak}
|
|
||||||
|
|
||||||
import scala.util.Random
|
import scala.util.Random
|
||||||
|
|
||||||
object GameUtil {
|
object GameUtil {
|
||||||
@@ -29,15 +26,4 @@ object GameUtil {
|
|||||||
code.toString()
|
code.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
def stateToTitle(gameState: GameState): String = {
|
|
||||||
gameState match {
|
|
||||||
case Lobby => "Lobby"
|
|
||||||
case MainMenu => "Main Menu"
|
|
||||||
case InGame => "In Game"
|
|
||||||
case SelectTrump => "Select Trump"
|
|
||||||
case TieBreak => "Tie Break"
|
|
||||||
case FinishedMatch => "Finished Match"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
|
import de.knockoutwhist.cards.{Card, Hand}
|
||||||
import de.knockoutwhist.cards.CardValue.*
|
import de.knockoutwhist.cards.CardValue.*
|
||||||
import de.knockoutwhist.cards.Suit.{Clubs, Diamonds, Hearts, Spades}
|
import de.knockoutwhist.cards.Suit.{Clubs, Diamonds, Hearts, Spades}
|
||||||
import de.knockoutwhist.cards.{Card, Hand}
|
|
||||||
import play.api.libs.json.{JsArray, Json}
|
import play.api.libs.json.{JsArray, Json}
|
||||||
import play.twirl.api.Html
|
import play.twirl.api.Html
|
||||||
import scalafx.scene.image.Image
|
import scalafx.scene.image.Image
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import de.knockoutwhist.utils.events.SimpleEvent
|
import de.knockoutwhist.utils.events.SimpleEvent
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsValue, Json}
|
import play.api.libs.json.{JsValue, Json}
|
||||||
import tools.jackson.databind.json.JsonMapper
|
import tools.jackson.databind.json.JsonMapper
|
||||||
import tools.jackson.module.scala.ScalaModule
|
import tools.jackson.module.scala.ScalaModule
|
||||||
import util.mapper.*
|
import util.mapper.{ReceivedHandEventMapper, SimpleEventMapper}
|
||||||
|
|
||||||
object WebsocketEventMapper {
|
object WebsocketEventMapper {
|
||||||
|
|
||||||
@@ -24,27 +23,11 @@ object WebsocketEventMapper {
|
|||||||
|
|
||||||
// Register all custom mappers here
|
// Register all custom mappers here
|
||||||
registerCustomMapper(ReceivedHandEventMapper)
|
registerCustomMapper(ReceivedHandEventMapper)
|
||||||
registerCustomMapper(GameStateEventMapper)
|
|
||||||
registerCustomMapper(CardPlayedEventMapper)
|
|
||||||
registerCustomMapper(NewRoundEventMapper)
|
|
||||||
registerCustomMapper(NewTrickEventMapper)
|
|
||||||
registerCustomMapper(TrickEndEventMapper)
|
|
||||||
registerCustomMapper(RequestCardEventMapper)
|
|
||||||
registerCustomMapper(LobbyUpdateEventMapper)
|
|
||||||
registerCustomMapper(LeftEventMapper)
|
|
||||||
registerCustomMapper(KickEventMapper)
|
|
||||||
registerCustomMapper(SessionClosedMapper)
|
|
||||||
registerCustomMapper(TurnEventMapper)
|
|
||||||
|
|
||||||
def toJson(obj: SimpleEvent, session: UserSession): JsValue = {
|
def toJson(obj: SimpleEvent): JsValue = {
|
||||||
val data: Option[JsValue] = if (customMappers.contains(obj.id)) {
|
val data = if (customMappers.contains(obj.id)) {
|
||||||
Some(customMappers(obj.id).toJson(obj, session))
|
return customMappers(obj.id).toJson(obj)
|
||||||
}else {
|
}else Json.parse(mapper.writeValueAsString(obj))
|
||||||
None
|
|
||||||
}
|
|
||||||
if (data.isEmpty) {
|
|
||||||
return Json.obj()
|
|
||||||
}
|
|
||||||
Json.obj(
|
Json.obj(
|
||||||
"id" -> ("request-" + java.util.UUID.randomUUID().toString),
|
"id" -> ("request-" + java.util.UUID.randomUUID().toString),
|
||||||
"event" -> obj.id,
|
"event" -> obj.id,
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import de.knockoutwhist.events.global.CardPlayedEvent
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsArray, JsObject, Json}
|
|
||||||
import util.WebUIUtils
|
|
||||||
|
|
||||||
object CardPlayedEventMapper extends SimpleEventMapper[CardPlayedEvent]{
|
|
||||||
|
|
||||||
override def id: String = "CardPlayedEvent"
|
|
||||||
|
|
||||||
override def toJson(event: CardPlayedEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"firstCard" -> (if (event.trick.firstCard.isDefined) WebUIUtils.cardtoString(event.trick.firstCard.get) else "BLANK"),
|
|
||||||
"playedCards" -> JsArray(event.trick.cards.map { case (card, player) =>
|
|
||||||
Json.obj("cardId" -> WebUIUtils.cardtoString(card), "player" -> player.name)
|
|
||||||
}.toList)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import controllers.IngameController
|
|
||||||
import de.knockoutwhist.events.global.GameStateChangeEvent
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
import util.GameUtil
|
|
||||||
|
|
||||||
object GameStateEventMapper extends SimpleEventMapper[GameStateChangeEvent] {
|
|
||||||
|
|
||||||
override def id: String = "GameStateChangeEvent"
|
|
||||||
|
|
||||||
override def toJson(event: GameStateChangeEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"title" -> ("Knockout Whist - " + GameUtil.stateToTitle(event.newState)),
|
|
||||||
"content" -> IngameController.returnInnerHTML(session.gameLobby, event.newState, session.user).toString
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import controllers.routes
|
|
||||||
import events.KickEvent
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object KickEventMapper extends SimpleEventMapper[KickEvent] {
|
|
||||||
|
|
||||||
override def id: String = "KickEvent"
|
|
||||||
|
|
||||||
override def toJson(event: KickEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"url" -> routes.MainMenuController.mainMenu().url,
|
|
||||||
"content" -> views.html.mainmenu.creategame(Some(session.user)).toString,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import controllers.routes
|
|
||||||
import events.{KickEvent, LeftEvent}
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object LeftEventMapper extends SimpleEventMapper[LeftEvent] {
|
|
||||||
|
|
||||||
override def id: String = "LeftEvent"
|
|
||||||
|
|
||||||
override def toJson(event: LeftEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"url" -> routes.MainMenuController.mainMenu().url,
|
|
||||||
"content" -> views.html.mainmenu.creategame(Some(session.user)).toString
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import events.LobbyUpdateEvent
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsArray, JsObject, Json}
|
|
||||||
|
|
||||||
object LobbyUpdateEventMapper extends SimpleEventMapper[LobbyUpdateEvent] {
|
|
||||||
|
|
||||||
override def id: String = "LobbyUpdateEvent"
|
|
||||||
|
|
||||||
override def toJson(event: LobbyUpdateEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"host" -> session.host,
|
|
||||||
"maxPlayers" -> session.gameLobby.maxPlayers,
|
|
||||||
"players" -> JsArray(session.gameLobby.getPlayers.values.map(player => {
|
|
||||||
Json.obj(
|
|
||||||
"id" -> player.id,
|
|
||||||
"name" -> player.name,
|
|
||||||
"self" -> (player.id == session.user.id)
|
|
||||||
)
|
|
||||||
}).toList)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import de.knockoutwhist.events.global.NewRoundEvent
|
|
||||||
import logic.game.GameLobby
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object NewRoundEventMapper extends SimpleEventMapper[NewRoundEvent]{
|
|
||||||
override def id: String = "NewRoundEvent"
|
|
||||||
|
|
||||||
override def toJson(event: NewRoundEvent, session: UserSession): JsObject = {
|
|
||||||
val gameLobby = session.gameLobby
|
|
||||||
Json.obj(
|
|
||||||
"trumpsuit" -> gameLobby.getLogic.getCurrentRound.get.trumpSuit.toString,
|
|
||||||
"players" -> gameLobby.getLogic.getCurrentMatch.get.playersIn.map(player => player.toString)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import de.knockoutwhist.events.global.NewTrickEvent
|
|
||||||
import logic.game.GameLobby
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object NewTrickEventMapper extends SimpleEventMapper[NewTrickEvent]{
|
|
||||||
override def id: String = "NewTrickEvent"
|
|
||||||
|
|
||||||
override def toJson(event: NewTrickEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
package util.mapper
|
package util.mapper
|
||||||
|
|
||||||
import de.knockoutwhist.events.player.ReceivedHandEvent
|
import de.knockoutwhist.events.player.ReceivedHandEvent
|
||||||
import model.sessions.UserSession
|
import play.api.libs.json.{JsArray, JsObject, Json}
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
import util.WebUIUtils
|
import util.WebUIUtils
|
||||||
|
|
||||||
object ReceivedHandEventMapper extends SimpleEventMapper[ReceivedHandEvent] {
|
object ReceivedHandEventMapper extends SimpleEventMapper[ReceivedHandEvent] {
|
||||||
|
|
||||||
override def id: String = "ReceivedHandEvent"
|
override def id: String = "ReceivedHandEvent"
|
||||||
override def toJson(event: ReceivedHandEvent, session: UserSession): JsObject = {
|
override def toJson(event: ReceivedHandEvent): JsObject = {
|
||||||
Json.obj(
|
Json.obj(
|
||||||
"dog" -> event.player.isInDogLife,
|
"dog" -> event.player.isInDogLife,
|
||||||
"hand" -> event.player.currentHand().map(hand => WebUIUtils.handToJson(hand))
|
"hand" -> event.player.currentHand().map(hand => WebUIUtils.handToJson(hand))
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import de.knockoutwhist.events.player.RequestCardEvent
|
|
||||||
import logic.game.GameLobby
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object RequestCardEventMapper extends SimpleEventMapper[RequestCardEvent]{
|
|
||||||
override def id: String = "RequestCardEvent"
|
|
||||||
|
|
||||||
override def toJson(event: RequestCardEvent, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"player" -> event.player.name
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import controllers.routes
|
|
||||||
import de.knockoutwhist.events.global.RoundEndEvent
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object RoundEndEventMapper extends SimpleEventMapper[RoundEndEvent] {
|
|
||||||
|
|
||||||
override def id: String = "RoundEndEvent"
|
|
||||||
|
|
||||||
override def toJson(event: RoundEndEvent, session: UserSession): JsObject = {
|
|
||||||
|
|
||||||
Json.obj(
|
|
||||||
"player" -> event.winner.name,
|
|
||||||
"tricks" -> event.amountOfTricks
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import controllers.routes
|
|
||||||
import de.knockoutwhist.events.global.SessionClosed
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object SessionClosedMapper extends SimpleEventMapper[SessionClosed] {
|
|
||||||
|
|
||||||
override def id: String = "SessionClosed"
|
|
||||||
|
|
||||||
override def toJson(event: SessionClosed, session: UserSession): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"url" -> routes.MainMenuController.mainMenu().url,
|
|
||||||
"content" -> views.html.mainmenu.creategame(Some(session.user)).toString,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,11 @@
|
|||||||
package util.mapper
|
package util.mapper
|
||||||
|
|
||||||
import de.knockoutwhist.utils.events.SimpleEvent
|
import de.knockoutwhist.utils.events.SimpleEvent
|
||||||
import logic.game.GameLobby
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.JsObject
|
import play.api.libs.json.JsObject
|
||||||
|
|
||||||
trait SimpleEventMapper[T <: SimpleEvent] {
|
trait SimpleEventMapper[T <: SimpleEvent] {
|
||||||
|
|
||||||
def id: String
|
def id: String
|
||||||
def toJson(event: T, session: UserSession): JsObject
|
def toJson(event: T): JsObject
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import de.knockoutwhist.events.global.TrickEndEvent
|
|
||||||
import de.knockoutwhist.rounds.Trick
|
|
||||||
import logic.game.GameLobby
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsObject, Json}
|
|
||||||
|
|
||||||
object TrickEndEventMapper extends SimpleEventMapper[TrickEndEvent]{
|
|
||||||
override def id: String = "TrickEndEvent"
|
|
||||||
|
|
||||||
override def toJson(event: TrickEndEvent, session: UserSession): JsObject = {
|
|
||||||
val gameLobby = session.gameLobby
|
|
||||||
Json.obj(
|
|
||||||
"playerwon" -> event.winner.name,
|
|
||||||
"playersin" -> gameLobby.getLogic.getCurrentMatch.get.playersIn.map(player => player.name),
|
|
||||||
"tricklist" -> gameLobby.getLogic.getCurrentRound.get.tricklist.map(trick => trick.winner.map(player => player.name).getOrElse("Trick in Progress"))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package util.mapper
|
|
||||||
|
|
||||||
import de.knockoutwhist.events.global.TurnEvent
|
|
||||||
import de.knockoutwhist.player.AbstractPlayer
|
|
||||||
import model.sessions.UserSession
|
|
||||||
import play.api.libs.json.{JsArray, JsObject, Json}
|
|
||||||
|
|
||||||
object TurnEventMapper extends SimpleEventMapper[TurnEvent] {
|
|
||||||
|
|
||||||
override def id: String = "TurnEvent"
|
|
||||||
|
|
||||||
override def toJson(event: TurnEvent, session: UserSession): JsObject = {
|
|
||||||
val nextPlayers = if (session.gameLobby.logic.getPlayerQueue.isEmpty) {
|
|
||||||
Json.arr()
|
|
||||||
} else {
|
|
||||||
val queue = session.gameLobby.logic.getPlayerQueue.get
|
|
||||||
JsArray(
|
|
||||||
queue.duplicate().map(player => mapPlayer(player)).toList
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Json.obj(
|
|
||||||
"currentPlayer" -> mapPlayer(event.player),
|
|
||||||
"nextPlayers" -> nextPlayers
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private def mapPlayer(player: AbstractPlayer): JsObject = {
|
|
||||||
Json.obj(
|
|
||||||
"name" -> player.name,
|
|
||||||
"dog" -> player.isInDogLife
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
<div class="row justify-content-center align-items-center flex-grow-1">
|
<div class="row justify-content-center align-items-center flex-grow-1">
|
||||||
@if((gamelobby.getUserSession(user.get.id).host)) {
|
@if((gamelobby.getUserSession(user.get.id).host)) {
|
||||||
<div class="col-12 text-center mb-5">
|
<div class="col-12 text-center mb-5">
|
||||||
<div class="btn btn-success" onclick="handleReturnToLobby()">Return to lobby</div>
|
<div class="btn btn-success" onclick="backToLobby('@gamelobby.id')">Return to lobby</div>
|
||||||
</div>
|
</div>
|
||||||
} else {
|
} else {
|
||||||
<div class="col-12 text-center mt-3">
|
<div class="col-12 text-center mt-3">
|
||||||
@@ -23,5 +23,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<script>
|
<script>
|
||||||
|
function waitForFunction(name, checkInterval = 100) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (typeof window[name] === "function") {
|
||||||
|
clearInterval(timer);
|
||||||
|
resolve(window[name]);
|
||||||
|
}
|
||||||
|
}, checkInterval);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
waitForFunction("pollForUpdates").then(fn => fn('@gamelobby.id'));
|
||||||
connectWebSocket()
|
connectWebSocket()
|
||||||
</script>
|
</script>
|
||||||
@@ -10,25 +10,12 @@
|
|||||||
<div class="row ms-4 me-4">
|
<div class="row ms-4 me-4">
|
||||||
<div class="col-4 mt-5 text-start">
|
<div class="col-4 mt-5 text-start">
|
||||||
<h4 class="fw-semibold mb-1">Current Player</h4>
|
<h4 class="fw-semibold mb-1">Current Player</h4>
|
||||||
@if(gamelobby.getLogic.getCurrentPlayer.isDefined) {
|
|
||||||
<p class="fs-5 text-primary" id="current-player-name">@gamelobby.getLogic.getCurrentPlayer.get.name</p>
|
<p class="fs-5 text-primary" id="current-player-name">@gamelobby.getLogic.getCurrentPlayer.get.name</p>
|
||||||
}else {
|
@if(!TrickUtil.isOver(gamelobby.getLogic.getCurrentMatch.get, gamelobby.getLogic.getPlayerQueue.get)) {
|
||||||
<p class="fs-5 text-primary" id="current-player-name">---</p>
|
<h4 class="fw-semibold mb-1">Next Player</h4>
|
||||||
}
|
|
||||||
@if(gamelobby.getLogic.getPlayerQueue.isDefined && gamelobby.getLogic.getCurrentMatch && !TrickUtil.isOver(gamelobby.getLogic.getCurrentMatch.get, gamelobby.getLogic.getPlayerQueue.get)) {
|
|
||||||
<h4 class="fw-semibold mb-1" id="next-players-text">Next Players</h4>
|
|
||||||
<div id="next-players-container">
|
|
||||||
@for(nextplayer <- gamelobby.getLogic.getPlayerQueue.get.duplicate()) {
|
@for(nextplayer <- gamelobby.getLogic.getPlayerQueue.get.duplicate()) {
|
||||||
<p class="fs-5 text-primary">@nextplayer @if(nextplayer.isInDogLife) {
|
<p class="fs-5 text-primary" id="next-player-name">@nextplayer</p>
|
||||||
🐶
|
|
||||||
}</p>
|
|
||||||
}
|
}
|
||||||
</div>
|
|
||||||
} else {
|
|
||||||
<h4 class="fw-semibold mb-1" style="display: none;" id="next-players-text">Next Players</h4>
|
|
||||||
<div id="next-players-container">
|
|
||||||
|
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -42,7 +29,6 @@
|
|||||||
<div style="width: 50%">TRICKS</div>
|
<div style="width: 50%">TRICKS</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if(gamelobby.getLogic.getPlayerQueue.isDefined) {
|
|
||||||
@for(player <- gamelobby.getLogic.getPlayerQueue.get.toList.sortBy { p =>
|
@for(player <- gamelobby.getLogic.getPlayerQueue.get.toList.sortBy { p =>
|
||||||
-(gamelobby.getLogic.getCurrentRound.get.tricklist.filter { trick => trick.winner.contains(p) }.size)
|
-(gamelobby.getLogic.getCurrentRound.get.tricklist.filter { trick => trick.winner.contains(p) }.size)
|
||||||
}) {
|
}) {
|
||||||
@@ -53,18 +39,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}else{
|
|
||||||
<div class="d-flex justify-content-between score-row pt-1">
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
<div class="d-flex justify-content-center g-3 mb-5" id="trick-cards-container">
|
<div class="d-flex justify-content-center g-3 mb-5" id="trick-cards-container">
|
||||||
@if(gamelobby.getLogic.getCurrentTrick.isEmpty || gamelobby.getLogic.getCurrentTrick.get.cards.isEmpty) {
|
|
||||||
<div class="col-auto">
|
|
||||||
</div>
|
|
||||||
} else {
|
|
||||||
@for((cardplayed, player) <- gamelobby.getLogic.getCurrentTrick.get.cards) {
|
@for((cardplayed, player) <- gamelobby.getLogic.getCurrentTrick.get.cards) {
|
||||||
<div class="col-auto">
|
<div class="col-auto">
|
||||||
<div class="card text-center shadow-sm border-0 bg-transparent" style="width: 7rem;
|
<div class="card text-center shadow-sm border-0 bg-transparent" style="width: 7rem;
|
||||||
@@ -78,20 +55,15 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-4 mt-5 text-end">
|
<div class="col-4 mt-5 text-end">
|
||||||
<h4 class="fw-semibold mb-1">Trumpsuit</h4>
|
<h4 class="fw-semibold mb-1">Trumpsuit</h4>
|
||||||
@if(gamelobby.getLogic.getCurrentRound.isEmpty) {
|
|
||||||
<p class="fs-5 text-primary" id="trumpsuit">No Trumpsuit</p>
|
|
||||||
}else {
|
|
||||||
<p class="fs-5 text-primary" id="trumpsuit">@gamelobby.getLogic.getCurrentRound.get.trumpSuit</p>
|
<p class="fs-5 text-primary" id="trumpsuit">@gamelobby.getLogic.getCurrentRound.get.trumpSuit</p>
|
||||||
}
|
|
||||||
|
|
||||||
<h5 class="fw-semibold mt-4 mb-1">First Card</h5>
|
<h5 class="fw-semibold mt-4 mb-1">First Card</h5>
|
||||||
<div class="d-inline-block border rounded shadow-sm p-1 bg-light" id="first-card-container">
|
<div class="d-inline-block border rounded shadow-sm p-1 bg-light" id="first-card-container">
|
||||||
@if(gamelobby.getLogic.getCurrentTrick.isDefined && gamelobby.getLogic.getCurrentTrick.get.firstCard.isDefined) {
|
@if(gamelobby.getLogic.getCurrentTrick.get.firstCard.isDefined) {
|
||||||
@util.WebUIUtils.cardtoImage(gamelobby.getLogic.getCurrentTrick.get.firstCard.get)
|
@util.WebUIUtils.cardtoImage(gamelobby.getLogic.getCurrentTrick.get.firstCard.get)
|
||||||
width="80px"/>
|
width="80px"/>
|
||||||
} else {
|
} else {
|
||||||
@@ -107,12 +79,9 @@
|
|||||||
<div class="row justify-content-center ingame-cards-slide @{
|
<div class="row justify-content-center ingame-cards-slide @{
|
||||||
!gamelobby.logic.getCurrentPlayer.contains(player) ? "inactive" |: ""
|
!gamelobby.logic.getCurrentPlayer.contains(player) ? "inactive" |: ""
|
||||||
}" id="card-slide">
|
}" id="card-slide">
|
||||||
@if(player.currentHand().isEmpty || player.currentHand().get.cards.isEmpty) {
|
|
||||||
|
|
||||||
} else {
|
|
||||||
@for(i <- player.currentHand().get.cards.indices) {
|
@for(i <- player.currentHand().get.cards.indices) {
|
||||||
<div class="col-auto handcard" style="border-radius: 6px">
|
<div class="col-auto handcard" style="border-radius: 6px">
|
||||||
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-card-id="@i" style="border-radius: 6px" onclick="handlePlayCard(this, '@player.isInDogLife')">
|
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-card-id="@i" style="border-radius: 6px" onclick="handlePlayCard(this, '@gamelobby.id', '@player.isInDogLife')">
|
||||||
@util.WebUIUtils.cardtoImage(player.currentHand().get.cards(i)) width="120px" style="border-radius: 6px"/>
|
@util.WebUIUtils.cardtoImage(player.currentHand().get.cards(i)) width="120px" style="border-radius: 6px"/>
|
||||||
</div>
|
</div>
|
||||||
@if(player.isInDogLife) {
|
@if(player.isInDogLife) {
|
||||||
@@ -123,13 +92,22 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
|
function waitForFunction(name, checkInterval = 100) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (typeof window[name] === "function") {
|
||||||
|
clearInterval(timer);
|
||||||
|
resolve(window[name]);
|
||||||
|
}
|
||||||
|
}, checkInterval);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
waitForFunction("pollForUpdates").then(fn => fn('@gamelobby.id'));
|
||||||
connectWebSocket()
|
connectWebSocket()
|
||||||
canPlayCard = @gamelobby.logic.getCurrentPlayer.contains(player);
|
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
<h3 class="mb-0">Select Trump Suit</h3>
|
<h3 class="mb-0">Select Trump Suit</h3>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
@if(gamelobby.logic.getCurrentMatch.isDefined) {
|
|
||||||
@if(player.equals(gamelobby.logic.getCurrentMatch.get.roundlist.last.winner.get)) {
|
@if(player.equals(gamelobby.logic.getCurrentMatch.get.roundlist.last.winner.get)) {
|
||||||
<div class="alert alert-info" role="alert" aria-live="polite">
|
<div class="alert alert-info" role="alert" aria-live="polite">
|
||||||
You (@player.toString) won the last round. Choose the trump suit for the next round.
|
You (@player.toString) won the last round. Choose the trump suit for the next round.
|
||||||
@@ -18,25 +17,25 @@
|
|||||||
|
|
||||||
<div class="row justify-content-center col-auto mb-5">
|
<div class="row justify-content-center col-auto mb-5">
|
||||||
<div class="col-auto handcard">
|
<div class="col-auto handcard">
|
||||||
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="0" style="border-radius: 6px" onclick="handleTrumpSelection(this)">
|
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="0" style="border-radius: 6px" onclick="handleTrumpSelection(this, '@gamelobby.id')">
|
||||||
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Spades))
|
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Spades))
|
||||||
width="120px" style="border-radius: 6px"/>
|
width="120px" style="border-radius: 6px"/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-auto handcard">
|
<div class="col-auto handcard">
|
||||||
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="1" style="border-radius: 6px" onclick="handleTrumpSelection(this)">
|
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="1" style="border-radius: 6px" onclick="handleTrumpSelection(this, '@gamelobby.id')">
|
||||||
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Hearts))
|
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Hearts))
|
||||||
width="120px" style="border-radius: 6px"/>
|
width="120px" style="border-radius: 6px"/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-auto handcard">
|
<div class="col-auto handcard">
|
||||||
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="2" style="border-radius: 6px" onclick="handleTrumpSelection(this)">
|
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="2" style="border-radius: 6px" onclick="handleTrumpSelection(this, '@gamelobby.id')">
|
||||||
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Diamonds))
|
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Diamonds))
|
||||||
width="120px" style="border-radius: 6px"/>
|
width="120px" style="border-radius: 6px"/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-auto handcard">
|
<div class="col-auto handcard">
|
||||||
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="3" style="border-radius: 6px" onclick="handleTrumpSelection(this)">
|
<div class="btn btn-outline-light p-0 border-0 shadow-none" data-trump="3" style="border-radius: 6px" onclick="handleTrumpSelection(this, '@gamelobby.id')">
|
||||||
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Clubs))
|
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Clubs))
|
||||||
width="120px" style="border-radius: 6px"/>
|
width="120px" style="border-radius: 6px"/>
|
||||||
</div>
|
</div>
|
||||||
@@ -55,7 +54,6 @@
|
|||||||
is choosing a trumpsuit. The new round will start once a suit is picked.
|
is choosing a trumpsuit. The new round will start once a suit is picked.
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -64,5 +62,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
|
function waitForFunction(name, checkInterval = 100) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (typeof window[name] === "function") {
|
||||||
|
clearInterval(timer);
|
||||||
|
resolve(window[name]);
|
||||||
|
}
|
||||||
|
}, checkInterval);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
waitForFunction("pollForUpdates").then(fn => fn('@gamelobby.id'));
|
||||||
connectWebSocket()
|
connectWebSocket()
|
||||||
</script>
|
</script>
|
||||||
@@ -110,5 +110,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
|
function waitForFunction(name, checkInterval = 100) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (typeof window[name] === "function") {
|
||||||
|
clearInterval(timer);
|
||||||
|
resolve(window[name]);
|
||||||
|
}
|
||||||
|
}, checkInterval);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
waitForFunction("pollForUpdates").then(fn => fn('@gamelobby.id'));
|
||||||
connectWebSocket()
|
connectWebSocket()
|
||||||
</script>
|
</script>
|
||||||
@@ -1,35 +1,6 @@
|
|||||||
@(user: Option[model.users.User], gamelobby: logic.game.GameLobby)
|
@(user: Option[model.users.User], gamelobby: logic.game.GameLobby)
|
||||||
|
|
||||||
<main class="lobby-background vh-100" id="lobbybackground">
|
<main class="lobby-background vh-100" id="lobbybackground">
|
||||||
<!-- Kick Modal -->
|
|
||||||
<div class="modal fade" data-backdrop="static" data-keyboard="false" data-focus="true" id="kickedModal" tabindex="-1" role="dialog" aria-labelledby="kickedModalTitle">
|
|
||||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
|
||||||
<div class="modal-content">
|
|
||||||
<div class="modal-header">
|
|
||||||
<h5 class="modal-title" id="kickedModalTitle">Kicked</h5>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
<p>You've been kicked from the lobby.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Session Closed Modal -->
|
|
||||||
<div class="modal fade" data-backdrop="static" data-keyboard="false" data-focus="true" id="sessionClosed" tabindex="-1" role="dialog" aria-labelledby="sessionClosedModalTitle">
|
|
||||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
|
||||||
<div class="modal-content">
|
|
||||||
<div class="modal-header">
|
|
||||||
<h5 class="modal-title" id="sessionClosedModalTitle">Session Closed</h5>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
<p>The session was closed.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Lobby -->
|
|
||||||
<div class="container d-flex flex-column" style="height: calc(100vh - 1rem);">
|
<div class="container d-flex flex-column" style="height: calc(100vh - 1rem);">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
@@ -44,7 +15,7 @@
|
|||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<div class="p-3 text-center fs-4" id="playerAmount">
|
<div class="p-3 text-center fs-4" id="playerAmount">
|
||||||
Players: @gamelobby.getPlayers.size / @gamelobby.maxPlayers</div>
|
Playeramount: @gamelobby.getPlayers.size / @gamelobby.maxPlayers</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="row justify-content-center align-items-center flex-grow-1">
|
<div class="row justify-content-center align-items-center flex-grow-1">
|
||||||
@@ -60,7 +31,7 @@
|
|||||||
<a href="#" class="btn btn-danger disabled" aria-disabled="true" tabindex="-1">Remove</a>
|
<a href="#" class="btn btn-danger disabled" aria-disabled="true" tabindex="-1">Remove</a>
|
||||||
} else {
|
} else {
|
||||||
<h5 class="card-title">@playersession.name</h5>
|
<h5 class="card-title">@playersession.name</h5>
|
||||||
<div class="btn btn-danger" onclick="handleKickPlayer('@playersession.id')">
|
<div class="btn btn-danger" onclick="removePlayer('@gamelobby.id', '@playersession.id')">
|
||||||
Remove</div>
|
Remove</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
@@ -69,7 +40,7 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="col-12 text-center mb-5">
|
<div class="col-12 text-center mb-5">
|
||||||
<div class="btn btn-success" onclick="startGame()">Start Game</div>
|
<div class="btn btn-success" onclick="startGame('@gamelobby.id')">Start Game</div>
|
||||||
</div>
|
</div>
|
||||||
} else {
|
} else {
|
||||||
<div id="players" class="justify-content-center align-items-center d-flex">
|
<div id="players" class="justify-content-center align-items-center d-flex">
|
||||||
@@ -98,5 +69,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<script>
|
<script>
|
||||||
|
function waitForFunction(name, checkInterval = 100) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (typeof window[name] === "function") {
|
||||||
|
clearInterval(timer);
|
||||||
|
resolve(window[name]);
|
||||||
|
}
|
||||||
|
}, checkInterval);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
waitForFunction("pollForUpdates").then(fn => fn('@gamelobby.id'));
|
||||||
connectWebSocket()
|
connectWebSocket()
|
||||||
</script>
|
</script>
|
||||||
@@ -18,17 +18,16 @@
|
|||||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
|
|
||||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
|
||||||
<script src="@routes.JavaScriptRoutingController.javascriptRoutes()" type="text/javascript"></script>
|
|
||||||
<script src="@routes.Assets.versioned("javascripts/websocket.js")" type="text/javascript"></script>
|
|
||||||
<script src="@routes.Assets.versioned("javascripts/events.js")" type="text/javascript"></script>
|
|
||||||
<script src="@routes.Assets.versioned("javascripts/interact.js")" type="text/javascript"></script>
|
|
||||||
<script src="@routes.Assets.versioned("javascripts/main.js")" type="text/javascript"></script>
|
|
||||||
|
|
||||||
<body class="d-flex flex-column min-vh-100" id="main-body">
|
<body class="d-flex flex-column min-vh-100" id="main-body">
|
||||||
@* And here's where we render the `Html` object containing
|
@* And here's where we render the `Html` object containing
|
||||||
* the page content. *@
|
* the page content. *@
|
||||||
@content
|
@content
|
||||||
</body>
|
</body>
|
||||||
|
<script src="@routes.JavaScriptRoutingController.javascriptRoutes()" type="text/javascript"></script>
|
||||||
|
<script src="@routes.Assets.versioned("javascripts/main.js")" type="text/javascript"></script>
|
||||||
|
<script src="@routes.Assets.versioned("../../public/javascripts/websocket.js")" type="text/javascript"></script>
|
||||||
|
<script src="@routes.Assets.versioned("../../public/javascripts/events.js")" type="text/javascript"></script>
|
||||||
|
<script src="@routes.Assets.versioned("../../public/javascripts/interact.js")" type="text/javascript"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
|
||||||
|
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -30,4 +30,4 @@
|
|||||||
</main>
|
</main>
|
||||||
<script>
|
<script>
|
||||||
disconnectWebSocket();
|
disconnectWebSocket();
|
||||||
</script>
|
</script>
|
||||||
@@ -1,32 +1,3 @@
|
|||||||
var canPlayCard = false;
|
|
||||||
|
|
||||||
function alertMessage(message) {
|
|
||||||
let newHtml = '';
|
|
||||||
const alertId = `alert-${Date.now()}`;
|
|
||||||
const fadeTime = 500;
|
|
||||||
const duration = 5000;
|
|
||||||
newHtml += `
|
|
||||||
<div class="fixed-top d-flex justify-content-center mt-3" style="z-index: 1050;">
|
|
||||||
<div
|
|
||||||
id="${alertId}" class="alert alert-primary d-flex align-items-center p-2 mb-0 w-auto" role="alert" style="display: none;">
|
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" class="bi flex-shrink-0 me-2" viewBox="0 0 16 16" role="img" aria-label="Warning:">
|
|
||||||
<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
|
|
||||||
</svg>
|
|
||||||
<div class="small">
|
|
||||||
<small>${message}</small>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
$('#main-body').prepend(newHtml);
|
|
||||||
const $notice = $(`#${alertId}`);
|
|
||||||
$notice.fadeIn(fadeTime);
|
|
||||||
setTimeout(function() {
|
|
||||||
$notice.fadeOut(fadeTime, function() {
|
|
||||||
$(this).parent().remove();
|
|
||||||
});
|
|
||||||
}, duration);
|
|
||||||
}
|
|
||||||
function receiveHandEvent(eventData) {
|
function receiveHandEvent(eventData) {
|
||||||
//Data
|
//Data
|
||||||
const dog = eventData.dog;
|
const dog = eventData.dog;
|
||||||
@@ -40,7 +11,7 @@ function receiveHandEvent(eventData) {
|
|||||||
//Build Hand Container
|
//Build Hand Container
|
||||||
hand.forEach((card) => {
|
hand.forEach((card) => {
|
||||||
//Data
|
//Data
|
||||||
const idx = card.idx;
|
const idx = card.idx
|
||||||
const cardS = card.card;
|
const cardS = card.card;
|
||||||
|
|
||||||
const cardHtml = `
|
const cardHtml = `
|
||||||
@@ -67,267 +38,5 @@ function receiveHandEvent(eventData) {
|
|||||||
}
|
}
|
||||||
handElement.html(newHtml);
|
handElement.html(newHtml);
|
||||||
}
|
}
|
||||||
function newRoundEvent(eventData) {
|
|
||||||
const trumpsuit = eventData.trumpsuit;
|
|
||||||
const players = eventData.players;
|
|
||||||
|
|
||||||
const tableElement = $('#score-table-body');
|
|
||||||
|
|
||||||
|
|
||||||
let tablehtml = `
|
|
||||||
<h4 class="fw-bold mb-3 text-black">Tricks Won</h4>
|
|
||||||
|
|
||||||
<div class="d-flex justify-content-between score-header pb-1">
|
|
||||||
<div style="width: 50%">PLAYER</div>
|
|
||||||
<div style="width: 50%">TRICKS</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
|
|
||||||
players.forEach(
|
|
||||||
tablehtml += `
|
|
||||||
<div class="d-flex justify-content-between score-row pt-1">
|
|
||||||
<div style="width: 50%" class="text-truncate">'${players}'</div>
|
|
||||||
<div style="width: 50%">
|
|
||||||
0
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`
|
|
||||||
);
|
|
||||||
tableElement.html(tablehtml);
|
|
||||||
|
|
||||||
const trumpsuitClass = $('#trumpsuit');
|
|
||||||
trumpsuitClass.html(trumpsuit);
|
|
||||||
|
|
||||||
}
|
|
||||||
function trickEndEvent(eventData) {
|
|
||||||
const winner = eventData.playerwon;
|
|
||||||
const players = eventData.playersin;
|
|
||||||
const tricklist = eventData.tricklist;
|
|
||||||
|
|
||||||
let newHtml = '';
|
|
||||||
|
|
||||||
let tricktable = $('#score-table-body');
|
|
||||||
|
|
||||||
newHtml += `
|
|
||||||
<h4 class="fw-bold mb-3 text-black">Tricks Won</h4>
|
|
||||||
|
|
||||||
<div class="d-flex justify-content-between score-header pb-1">
|
|
||||||
<div style="width: 50%">PLAYER</div>
|
|
||||||
<div style="width: 50%">TRICKS</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
let playercounts = new Map();
|
|
||||||
|
|
||||||
players.forEach( player => {
|
|
||||||
playercounts.set(player, 0)
|
|
||||||
});
|
|
||||||
tricklist.forEach( player => {
|
|
||||||
if ( player !== "Trick in Progress" && playercounts.has(player)) {
|
|
||||||
playercounts.set(player, playercounts.get(player) + 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
const playerorder = players.sort((playerA, playerB) => {
|
|
||||||
const countA = playercounts.get(playerA) || 0;
|
|
||||||
const countB = playercounts.get(playerB) || 0;
|
|
||||||
return countB - countA;
|
|
||||||
});
|
|
||||||
playerorder.forEach( player => {
|
|
||||||
newHtml += `
|
|
||||||
<div class="d-flex justify-content-between score-row pt-1">
|
|
||||||
<div style="width: 50%" class="text-truncate">${player}</div>
|
|
||||||
<div style="width: 50%">
|
|
||||||
${playercounts.get(player)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`
|
|
||||||
});
|
|
||||||
alertMessage(`${winner} won the trick!`)
|
|
||||||
tricktable.html(newHtml);
|
|
||||||
|
|
||||||
}
|
|
||||||
function newTrickEvent() {
|
|
||||||
const firstCardContainer = $('#first-card-container');
|
|
||||||
const emptyHtml = '';
|
|
||||||
let newHtml = '';
|
|
||||||
newHtml += `
|
|
||||||
<img src="/assets/images/cards/1B.png" alt="Blank Card" width="80px" style="border-radius: 6px"/>
|
|
||||||
`;
|
|
||||||
firstCardContainer.html(newHtml);
|
|
||||||
const playedCardsContainer = $('#trick-cards-container')
|
|
||||||
playedCardsContainer.html(emptyHtml)
|
|
||||||
}
|
|
||||||
function requestCardEvent(eventData) {
|
|
||||||
const player = eventData.player;
|
|
||||||
const handElement = $('#card-slide')
|
|
||||||
handElement.removeClass('inactive');
|
|
||||||
canPlayCard = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function receiveGameStateChange(eventData) {
|
|
||||||
const content = eventData.content;
|
|
||||||
const title = eventData.title || 'Knockout Whist';
|
|
||||||
const url = eventData.url || null;
|
|
||||||
|
|
||||||
exchangeBody(content, title, url);
|
|
||||||
}
|
|
||||||
function receiveCardPlayedEvent(eventData) {
|
|
||||||
const firstCard = eventData.firstCard;
|
|
||||||
const playedCards = eventData.playedCards;
|
|
||||||
|
|
||||||
const trickCardsContainer = $('#trick-cards-container');
|
|
||||||
const firstCardContainer = $('#first-card-container')
|
|
||||||
|
|
||||||
let trickHTML = '';
|
|
||||||
playedCards.forEach(cardCombo => {
|
|
||||||
trickHTML += `
|
|
||||||
<div class="col-auto">
|
|
||||||
<div class="card text-center shadow-sm border-0 bg-transparent" style="width: 7rem; backdrop-filter: blur(4px);">
|
|
||||||
<div class="p-2">
|
|
||||||
<img src="/assets/images/cards/${cardCombo.cardId}.png" width="100%" alt="${cardCombo.cardId}"/>
|
|
||||||
</div>
|
|
||||||
<div class="card-body p-2 bg-transparent">
|
|
||||||
<small class="fw-semibold text-secondary">${cardCombo.player}</small>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
});
|
|
||||||
trickCardsContainer.html(trickHTML);
|
|
||||||
|
|
||||||
let altText;
|
|
||||||
let imageSrc;
|
|
||||||
if (firstCard === "BLANK") {
|
|
||||||
imageSrc = "/assets/images/cards/1B.png";
|
|
||||||
altText = "Blank Card";
|
|
||||||
} else {
|
|
||||||
imageSrc = `/assets/images/cards/${firstCard}.png`;
|
|
||||||
altText = `Card ${firstCard}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newFirstCardHTML = `
|
|
||||||
<img src="${imageSrc}" alt="${altText}" width="80px" style="border-radius: 6px"/>
|
|
||||||
`;
|
|
||||||
firstCardContainer.html(newFirstCardHTML);
|
|
||||||
}
|
|
||||||
function receiveLobbyUpdateEvent(eventData) {
|
|
||||||
const host = eventData.host;
|
|
||||||
const maxPlayers = eventData.maxPlayers;
|
|
||||||
const players = eventData.players;
|
|
||||||
|
|
||||||
const lobbyPlayersContainer = $('#players');
|
|
||||||
const playerAmountBox = $('#playerAmount');
|
|
||||||
|
|
||||||
let newHtml = ''
|
|
||||||
|
|
||||||
if (host) {
|
|
||||||
players.forEach(user => {
|
|
||||||
|
|
||||||
const inner = user.self ? `<h5 class="card-title">${user.name} (You)</h5>
|
|
||||||
<a href="#" class="btn btn-danger disabled" aria-disabled="true" tabindex="-1">Remove</a>`
|
|
||||||
: ` <h5 class="card-title">${user.name}</h5>
|
|
||||||
<div class="btn btn-danger" onclick="handleKickPlayer('${user.id}')">Remove</div>`
|
|
||||||
|
|
||||||
newHtml += `<div class="col-auto my-auto m-3">
|
|
||||||
<div class="card" style="width: 18rem;">
|
|
||||||
<img src="/assets/images/profile.png" alt="Profile" class="card-img-top w-50 mx-auto mt-3" />
|
|
||||||
<div class="card-body">
|
|
||||||
${inner}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>`
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
players.forEach(user => {
|
|
||||||
|
|
||||||
const inner = user.self ? `<h5 class="card-title">${user.name} (You)</h5>` : ` <h5 class="card-title">${user.name}</h5>`
|
|
||||||
|
|
||||||
newHtml += `<div class="col-auto my-auto m-3">
|
|
||||||
<div class="card" style="width: 18rem;">
|
|
||||||
<img src="/assets/images/profile.png" alt="Profile" class="card-img-top w-50 mx-auto mt-3" />
|
|
||||||
<div class="card-body">
|
|
||||||
${inner}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>`
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
lobbyPlayersContainer.html(newHtml);
|
|
||||||
playerAmountBox.text(`Players: ${players.length} / ${maxPlayers}`);
|
|
||||||
|
|
||||||
}
|
|
||||||
function receiveKickEvent(eventData) {
|
|
||||||
$('#kickedModal').modal({
|
|
||||||
backdrop: 'static',
|
|
||||||
keyboard: false
|
|
||||||
}).modal('show');
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
receiveGameStateChange(eventData)
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
function receiveSessionClosedEvent(eventData) {
|
|
||||||
$('#sessionClosed').modal({
|
|
||||||
backdrop: 'static',
|
|
||||||
keyboard: false
|
|
||||||
}).modal('show');
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
receiveGameStateChange(eventData)
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function receiveTurnEvent(eventData) {
|
|
||||||
const currentPlayer = eventData.currentPlayer;
|
|
||||||
const nextPlayers = eventData.nextPlayers;
|
|
||||||
|
|
||||||
const currentPlayerNameContainer = $('#current-player-name');
|
|
||||||
const nextPlayersContainer = $('#next-players-container');
|
|
||||||
const nextPlayerText = $('#next-players-text');
|
|
||||||
|
|
||||||
let currentPlayerName = currentPlayer.name;
|
|
||||||
if (currentPlayer.dog) {
|
|
||||||
currentPlayerName += " 🐶";
|
|
||||||
}
|
|
||||||
currentPlayerNameContainer.text(currentPlayerName);
|
|
||||||
|
|
||||||
if (nextPlayers.length === 0) {
|
|
||||||
nextPlayerText.hide();
|
|
||||||
nextPlayersContainer.html('');
|
|
||||||
} else {
|
|
||||||
console.log("Length"+nextPlayers.length);
|
|
||||||
nextPlayerText.show();
|
|
||||||
let nextPlayersHtml = '';
|
|
||||||
nextPlayers.forEach((player) => {
|
|
||||||
let playerName = player.name;
|
|
||||||
if (player.dog) {
|
|
||||||
playerName += " 🐶";
|
|
||||||
}
|
|
||||||
nextPlayersHtml += `<p class="fs-5 text-primary">${playerName}</p>`;
|
|
||||||
});
|
|
||||||
nextPlayersContainer.html(nextPlayersHtml);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function receiveRoundEndEvent(eventData) {
|
|
||||||
const player = eventData.player
|
|
||||||
const tricks = eventData.tricks
|
|
||||||
alertMessage(`${player} won this round with ${tricks} tricks!`)
|
|
||||||
}
|
|
||||||
onEvent("ReceivedHandEvent", receiveHandEvent)
|
onEvent("ReceivedHandEvent", receiveHandEvent)
|
||||||
onEvent("GameStateChangeEvent", receiveGameStateChange)
|
|
||||||
onEvent("NewRoundEvent", newRoundEvent)
|
|
||||||
onEvent("TrickEndEvent", trickEndEvent)
|
|
||||||
onEvent("NewTrickEvent", newTrickEvent)
|
|
||||||
onEvent("RequestCardEvent", requestCardEvent)
|
|
||||||
onEvent("CardPlayedEvent", receiveCardPlayedEvent)
|
|
||||||
onEvent("LobbyUpdateEvent", receiveLobbyUpdateEvent)
|
|
||||||
onEvent("LeftEvent", receiveGameStateChange)
|
|
||||||
onEvent("KickEvent", receiveKickEvent)
|
|
||||||
onEvent("SessionClosed", receiveSessionClosedEvent)
|
|
||||||
onEvent("TurnEvent", receiveTurnEvent)
|
|
||||||
onEvent("RoundEndEvent", receiveRoundEndEvent)
|
|
||||||
|
|
||||||
globalThis.alertMessage = alertMessage
|
|
||||||
@@ -1,82 +1,7 @@
|
|||||||
function handlePlayCard(card, dog) {
|
function handlePlayCard(card, dog) {
|
||||||
|
// TODO needs implementation
|
||||||
if(!canPlayCard) return
|
|
||||||
canPlayCard = false;
|
|
||||||
|
|
||||||
const cardId = card.dataset.cardId;
|
|
||||||
|
|
||||||
console.debug(`Playing card ${cardId} from hand`)
|
|
||||||
|
|
||||||
const wiggleKeyframes = [
|
|
||||||
{ transform: 'translateX(0)' },
|
|
||||||
{ transform: 'translateX(-5px)' },
|
|
||||||
{ transform: 'translateX(5px)' },
|
|
||||||
{ transform: 'translateX(-5px)' },
|
|
||||||
{ transform: 'translateX(0)' }
|
|
||||||
];
|
|
||||||
|
|
||||||
const wiggleTiming = {
|
|
||||||
duration: 400,
|
|
||||||
iterations: 1,
|
|
||||||
easing: 'ease-in-out',
|
|
||||||
fill: 'forwards'
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
const cardslide = $('#card-slide')
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
cardindex: cardId,
|
|
||||||
isDog: dog
|
|
||||||
}
|
|
||||||
sendEventAndWait("PlayCard", payload).then(
|
|
||||||
() => {
|
|
||||||
card.parentElement.remove();
|
|
||||||
cardslide.find('.handcard').each(function(newIndex) {
|
|
||||||
|
|
||||||
const $innerButton = $(this).find('.btn');
|
|
||||||
$innerButton.attr('data-card-id', newIndex);
|
|
||||||
|
|
||||||
const isInDogLife = $innerButton.attr('onclick').includes("'true'") ? 'true' : 'false';
|
|
||||||
$innerButton.attr('onclick', `handlePlayCard(this, '${isInDogLife}')`);
|
|
||||||
|
|
||||||
console.debug(`Re-indexed card: Old index was ${$innerButton.attr('data-card-id')}, New index is ${newIndex}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
cardslide.addClass("inactive")
|
|
||||||
}
|
|
||||||
).catch(
|
|
||||||
(err) => {
|
|
||||||
canPlayCard = true;
|
|
||||||
const cardslide = $('#card-slide')
|
|
||||||
cardslide.removeClass("inactive")
|
|
||||||
card.parentElement.animate(wiggleKeyframes, wiggleTiming);
|
|
||||||
alertMessage(err.message)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSkipDogLife(button) {
|
function handleSkipDogLife(button) {
|
||||||
// TODO needs implementation
|
// TODO needs implementation
|
||||||
}
|
}
|
||||||
function startGame() {
|
|
||||||
sendEvent("StartGame")
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleTrumpSelection(object) {
|
|
||||||
const $button = $(object);
|
|
||||||
const trumpIndex = parseInt($button.data('trump'));
|
|
||||||
const payload = {
|
|
||||||
suitIndex: trumpIndex
|
|
||||||
}
|
|
||||||
sendEvent("PickTrumpsuit", payload)
|
|
||||||
|
|
||||||
}
|
|
||||||
function handleKickPlayer(playerId) {
|
|
||||||
sendEvent("KickPlayer", {
|
|
||||||
playerId: playerId
|
|
||||||
})
|
|
||||||
}
|
|
||||||
function handleReturnToLobby() {
|
|
||||||
sendEvent("ReturnToLobby")
|
|
||||||
}
|
|
||||||
@@ -217,6 +217,3 @@ function navSpa(page, title) {
|
|||||||
});
|
});
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
globalThis.exchangeBody = exchangeBody;
|
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
|
type EventHandler = (data: any) => any | Promise<any>;
|
||||||
|
|
||||||
// javascript
|
// javascript
|
||||||
let ws = null; // will be created by connectWebSocket()
|
let ws = null; // will be created by connectWebSocket()
|
||||||
const pending = new Map(); // id -> { resolve, reject, timer }
|
const pending: Map<string, any> = new Map(); // id -> { resolve, reject, timer }
|
||||||
const handlers = new Map(); // eventType -> handler(data) -> (value|Promise)
|
const handlers: Map<string, EventHandler> = new Map(); // eventType -> handler(data) -> (value|Promise)
|
||||||
|
|
||||||
|
|
||||||
let timer = null;
|
let timer = null;
|
||||||
|
|
||||||
@@ -38,8 +41,8 @@ function setupSocketHandlers(socket) {
|
|||||||
|
|
||||||
if (id && eventType) {
|
if (id && eventType) {
|
||||||
const handler = handlers.get(eventType);
|
const handler = handlers.get(eventType);
|
||||||
const sendResponse = (result) => {
|
const sendResponse = (respData) => {
|
||||||
const response = {id: id, event: eventType, status: result};
|
const response = {id: id, event: eventType, data: respData === undefined ? {} : respData};
|
||||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||||
socket.send(JSON.stringify(response));
|
socket.send(JSON.stringify(response));
|
||||||
} else {
|
} else {
|
||||||
@@ -49,17 +52,16 @@ function setupSocketHandlers(socket) {
|
|||||||
|
|
||||||
if (!handler) {
|
if (!handler) {
|
||||||
// no handler: respond with an error object in data so server can fail it
|
// no handler: respond with an error object in data so server can fail it
|
||||||
console.warn("No handler for event:", eventType);
|
|
||||||
sendResponse({error: "No handler for event: " + eventType});
|
sendResponse({error: "No handler for event: " + eventType});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Promise.resolve(handler(data === undefined ? {} : data))
|
Promise.resolve(handler(data === undefined ? {} : data))
|
||||||
.then(_ => sendResponse("success"))
|
.then(result => sendResponse(result))
|
||||||
.catch(_ => sendResponse("error"));
|
.catch(err => sendResponse({error: err?.message ? err.message : String(err)}));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
sendResponse("error");
|
sendResponse({error: err?.message ? err.message : String(err)});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -91,12 +93,7 @@ function setupSocketHandlers(socket) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// connect/disconnect helpers
|
// connect/disconnect helpers
|
||||||
function connectWebSocket(url = null) {
|
function connectWebSocket(url = "ws://localhost:9000/websocket") {
|
||||||
if (!url) {
|
|
||||||
const loc = window.location;
|
|
||||||
const protocol = loc.protocol === "https:" ? "wss:" : "ws:";
|
|
||||||
url = protocol + "//" + loc.host + "/websocket";
|
|
||||||
}
|
|
||||||
if (ws && ws.readyState === WebSocket.OPEN) return Promise.resolve();
|
if (ws && ws.readyState === WebSocket.OPEN) return Promise.resolve();
|
||||||
if (ws && ws.readyState === WebSocket.CONNECTING) {
|
if (ws && ws.readyState === WebSocket.CONNECTING) {
|
||||||
// already connecting - return a promise that resolves on open
|
// already connecting - return a promise that resolves on open
|
||||||
@@ -185,7 +182,7 @@ function sendEventAndWait(eventType, eventData, timeoutMs = 10000) {
|
|||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
|
|
||||||
function onEvent(eventType, handler) {
|
function onEvent(eventType: string, handler: EventHandler) {
|
||||||
handlers.set(eventType, handler);
|
handlers.set(eventType, handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
MAJOR=4
|
MAJOR=3
|
||||||
MINOR=6
|
MINOR=0
|
||||||
PATCH=1
|
PATCH=1
|
||||||
|
|||||||
Reference in New Issue
Block a user