Compare commits

...

10 Commits
1.0.7 ... 1.1.0

Author SHA1 Message Date
TeamCity
8e511d2a11 ci: bump version to v1.1.0 2025-11-14 10:38:15 +00:00
e60fe7c98d feat(ci): Polling Added polling for when the game starts and a card gets played (#58)
Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #58
2025-11-14 09:11:32 +01:00
370de175db feat(ci): Polling
Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #53
2025-11-13 11:07:08 +01:00
5d245d0011 feat(ui): implement tie & trump menu, fixed some critical bugs (#52)
Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #52
Co-authored-by: Janis <janis.e.20@gmx.de>
Co-committed-by: Janis <janis.e.20@gmx.de>
2025-11-13 08:20:30 +01:00
c220e54bb8 feat(ui): added js routing, updated ingame ui, added tricktable (#50)
This merge request has full JS routing for calling specific endpoints. Game is fully playable but doesn't have polling yet. This version already has the UI changes adressed in MR #43 so first merge MR #43 and then this one or only merge this one because it already has the UI changes :)

Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #50
Reviewed-by: Janis <janis-e@gmx.de>
2025-11-12 11:44:21 +01:00
TeamCity
b847d3c054 ci: bump version to v1.0.9 2025-11-07 16:54:36 +00:00
c7dd72ecc2 fix: removed trailing 2025-11-07 17:52:12 +01:00
42a5adbae0 fix: removed trailing 2025-11-07 17:46:55 +01:00
TeamCity
ae9a8f2af9 ci: bump version to v1.0.8 2025-11-07 16:28:11 +00:00
7adc8b8645 fix: trailing 2025-11-07 17:25:35 +01:00
25 changed files with 1337 additions and 344 deletions

View File

@@ -1,2 +1,2 @@
-J--add-opens=java.base/java.util=ALL-UNNAMED
-J--add-opens=java.base/java.lang=ALL-UNNAMED
-J--add-opens=java.base/java.lang=ALL-UNNAMED

View File

@@ -100,3 +100,22 @@
### Bug Fixes
* removed trailing ([5e503cb](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/5e503cbc364f7cb23926976acc6cee575eadd9d6))
## (2025-11-07)
### Bug Fixes
* trailing ([7adc8b8](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/7adc8b8645390cd18d63b4eee6db8ef448b7a46a))
## (2025-11-07)
### Bug Fixes
* removed trailing ([c7dd72e](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/c7dd72ecc2786ef63daf2b4288093025a8e22bfd))
* removed trailing ([42a5adb](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/42a5adbae01802587a48a9de15bad44b5ef014cf))
## (2025-11-14)
### Features
* **ci:** Polling ([370de17](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/370de175db65edf87e7ab211190977b540a39d85))
* **ci:** Polling Added polling for when the game starts and a card gets played ([#58](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/58)) ([e60fe7c](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/e60fe7c98dcab05949140a8a54ed6e4e2fbbc022))
* **ui:** added js routing, updated ingame ui, added tricktable ([#50](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/50)) ([c220e54](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/c220e54bb8d87f4f0f37a089bcd993e8df806123)), closes [#43](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/43) [#43](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/43)
* **ui:** implement tie & trump menu, fixed some critical bugs ([#52](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/52)) ([5d245d0](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/5d245d0011a5fb03193514303b45702cd8329224))

View File

@@ -3,7 +3,7 @@
--background-image: url('/assets/images/background.png') !important;
--color: #f8f9fa !important; /* Light text on dark bg */
--highlightscolor: rgba(131, 131, 131, 0.75) !important;
--background-color: #192734;
/* Bootstrap variable overrides for dark mode */
--bs-body-color: var(--color);
--bs-link-color: #66b2ff;

View File

@@ -2,4 +2,5 @@
--background-image: url('/assets/images/img.png');
--color: black;
--highlightscolor: rgba(0, 0, 0, 0.75);
--background-color: rgba(228, 232, 237, 1);
}

View File

@@ -14,7 +14,7 @@
--bs-border-color: rgba(0, 0, 0, 0.125) !important;
--bs-heading-color: var(--color) !important;
}
@background-color: var(--background-color);
@highlightcolor: var(--highlightscolor);
@background-image: var(--background-image);
@color: var(--color);
@@ -22,12 +22,19 @@
0% { transform: translateX(-100vw); }
100% { transform: translateX(0); }
}
.game-field-background {
background-image: @background-image;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
max-width: 1400px;
margin: 0 auto;
min-height: 100vh;
}
.lobby-background {
background-color: @background-color;
width: 100%;
height: 100vh;
}
.navbar-header{
@@ -45,8 +52,11 @@
.bottom-div {
position: fixed;
bottom: 0;
left: 0;
left: 50%;
transform: translateX(-50%);
max-width: 1400px;
width: 100%;
margin: 0;
text-align: center;
padding: 10px;
}
@@ -71,6 +81,14 @@ body {
overflow: auto;
}
.navbar-drop-shadow {
box-shadow: 0 1px 15px 0 #000000
}
.ingame-side-shadow {
box-shadow: 0 1px 15px 0 #000000
}
#sessions {
display: flex;
flex-direction: column;
@@ -105,45 +123,21 @@ body {
font-size: 40px;
font-family: Arial, serif;
}
#playercards {
display: flex;
flex-direction: row;
justify-content: center;
height: 20%;
img {
animation: slideIn 0.5s ease-out forwards;
animation-fill-mode: backwards;
&:nth-child(1) { animation-delay: 0.5s; }
&:nth-child(2) { animation-delay: 1s; }
&:nth-child(3) { animation-delay: 1.5s; }
&:nth-child(4) { animation-delay: 2s; }
&:nth-child(5) { animation-delay: 2.5s; }
&:nth-child(6) { animation-delay: 3s; }
&:nth-child(7) { animation-delay: 3.5s; }
}
}
#card-slide {
div {
animation: slideIn 0.5s ease-out forwards;
animation-fill-mode: backwards;
&:nth-child(1) { animation-delay: 0.5s; }
&:nth-child(2) { animation-delay: 1s; }
&:nth-child(3) { animation-delay: 1.5s; }
&:nth-child(4) { animation-delay: 2s; }
&:nth-child(5) { animation-delay: 2.5s; }
&:nth-child(6) { animation-delay: 3s; }
&:nth-child(7) { animation-delay: 3.5s; }
}
.ingame-cards-slide {
div {
animation: slideIn 0.5s ease-out forwards;
animation-fill-mode: backwards;
&:nth-child(1) { animation-delay: 0.5s; }
&:nth-child(2) { animation-delay: 1s; }
&:nth-child(3) { animation-delay: 1.5s; }
&:nth-child(4) { animation-delay: 2s; }
&:nth-child(5) { animation-delay: 2.5s; }
&:nth-child(6) { animation-delay: 3s; }
&:nth-child(7) { animation-delay: 3.5s; }
}
}
#cardsplayed {
display: flex;
flex-direction: row;
height: 10%;
min-height: 10%
}
#playedcardplayer {
display: flex;
flex-direction: column;
@@ -177,11 +171,6 @@ body {
font-size: 20px;
}
#trumpsuit {
display: flex;
flex-direction: row;
margin-left: 4%;
}
#nextPlayers {
display: flex;
flex-direction: column;
@@ -205,4 +194,52 @@ body {
color: @color;
font-size: 1.5em;
font-family: Arial, serif;
}
}
.score-table {
background-color: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 10px;
margin-bottom: 20px;
backdrop-filter: blur(8px);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.score-header {
font-weight: bold;
color: #000000;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
.score-row {
color: #000000;
}
/* In-game centered stage and blurred sides overlay */
.ingame-stage {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem 1rem;
}
/* Wrapper that adds a backdrop blur to the background outside the centered card */
.blur-sides {
position: relative;
}
/* Create an overlay that blurs everything behind it, except the central content area */
.blur-sides::before {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
/* fallback: subtle vignette if backdrop-filter unsupported */
background: radial-gradient(ellipse at center, rgba(0,0,0,0) 30%, rgba(0,0,0,0.35) 100%);
}
@supports ((-webkit-backdrop-filter: blur(8px)) or (backdrop-filter: blur(8px))) {
.blur-sides::before {
background: rgba(0,0,0,0.08);
-webkit-backdrop-filter: blur(10px) saturate(110%);
backdrop-filter: blur(10px) saturate(110%);
}
}

View File

@@ -2,28 +2,26 @@ package controllers
import auth.{AuthAction, AuthenticatedRequest}
import de.knockoutwhist.control.GameState.{InGame, Lobby, SelectTrump, TieBreak}
import exceptions.{CantPlayCardException, GameFullException, NotEnoughPlayersException, NotHostException, NotInThisGameException}
import exceptions.*
import logic.PodManager
import model.sessions.{PlayerSession, UserSession}
import logic.game.GameLobby
import model.sessions.UserSession
import play.api.*
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.*
import java.util.UUID
import javax.inject.*
import scala.concurrent.ExecutionContext
import scala.util.Try
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
@Singleton
class IngameController @Inject()(
val controllerComponents: ControllerComponents,
val authAction: AuthAction,
val podManager: PodManager
) extends BaseController {
class IngameController @Inject() (
val cc: ControllerComponents,
val podManager: PodManager,
val authAction: AuthAction,
implicit val ec: ExecutionContext
) extends AbstractController(cc) {
def game(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val game = podManager.getGame(gameId)
game match {
@@ -38,12 +36,12 @@ class IngameController @Inject()(
case SelectTrump =>
Ok(views.html.ingame.selecttrump(
g.getPlayerByUser(request.user),
g.logic
g
))
case TieBreak =>
Ok(views.html.ingame.tie(
g.getPlayerByUser(request.user),
g.logic
g
))
case _ =>
InternalServerError(s"Invalid game state for in-game view. GameId: $gameId" + s" State: ${g.logic.getCurrentState}")
@@ -51,7 +49,6 @@ class IngameController @Inject()(
case None =>
NotFound("Game not found")
}
//NotFound(s"Reached end of game method unexpectedly. GameId: $gameId")
}
def startGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val game = podManager.getGame(gameId)
@@ -64,30 +61,70 @@ class IngameController @Inject()(
}
}
if (result.isSuccess) {
Redirect(routes.IngameController.game(gameId))
Ok(Json.obj(
"status" -> "success",
"redirectUrl" -> routes.IngameController.game(gameId).url
))
} else {
val throwable = result.failed.get
throwable match {
case _: NotInThisGameException =>
BadRequest(throwable.getMessage)
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _: NotHostException =>
Forbidden(throwable.getMessage)
Forbidden(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _: NotEnoughPlayersException =>
BadRequest(throwable.getMessage)
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _ =>
InternalServerError(throwable.getMessage)
InternalServerError(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
}
}
}
def kickPlayer(gameId: String, playerToKick: UUID): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
def kickPlayer(gameId: String, playerToKick: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val game = podManager.getGame(gameId)
game.get.leaveGame(playerToKick)
Redirect(routes.IngameController.game(gameId))
val playerToKickUUID = UUID.fromString(playerToKick)
val result = Try {
game.get.leaveGame(playerToKickUUID)
}
if(result.isSuccess) {
Ok(Json.obj(
"status" -> "success",
"redirectUrl" -> routes.IngameController.game(gameId).url
))
} else {
InternalServerError(Json.obj(
"status" -> "failure",
"errorMessage" -> "Something went wrong."
))
}
}
def leaveGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val game = podManager.getGame(gameId)
game.get.leaveGame(request.user.id)
Redirect(routes.MainMenuController.mainMenu())
val result = Try {
game.get.leaveGame(request.user.id)
}
if (result.isSuccess) {
Ok(Json.obj(
"status" -> "success",
"redirectUrl" -> routes.MainMenuController.mainMenu().url
))
} else {
InternalServerError(Json.obj(
"status" -> "failure",
"errorMessage" -> "Something went wrong."
))
}
}
def joinGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val game = podManager.getGame(gameId)
@@ -119,7 +156,10 @@ class IngameController @Inject()(
val game = podManager.getGame(gameId)
game match {
case Some(g) =>
val cardIdOpt = request.body.asFormUrlEncoded.flatMap(_.get("cardId").flatMap(_.headOption))
val jsonBody = request.body.asJson
val cardIdOpt: Option[String] = jsonBody.flatMap { jsValue =>
(jsValue \ "cardID").asOpt[String]
}
cardIdOpt match {
case Some(cardId) =>
var optSession: Option[UserSession] = None
@@ -131,27 +171,51 @@ class IngameController @Inject()(
}
optSession.foreach(_.lock.unlock())
if (result.isSuccess) {
NoContent
Ok(Json.obj(
"status" -> "success",
"redirectUrl" -> routes.IngameController.game(gameId).url
))
} else {
val throwable = result.failed.get
throwable match {
case _: CantPlayCardException =>
BadRequest(throwable.getMessage)
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _: NotInThisGameException =>
BadRequest(throwable.getMessage)
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _: IllegalArgumentException =>
BadRequest(throwable.getMessage)
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _: IllegalStateException =>
BadRequest(throwable.getMessage)
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
case _ =>
InternalServerError(throwable.getMessage)
InternalServerError(Json.obj(
"status" -> "failure",
"errorMessage" -> throwable.getMessage
))
}
}
case None =>
BadRequest("cardId parameter is missing")
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> "cardId Parameter is missing"
))
}
case None =>
NotFound("Game not found")
NotFound(Json.obj(
"status" -> "failure",
"errorMessage" -> "Game not found"
))
}
}
}

View File

@@ -0,0 +1,27 @@
package controllers
import auth.{AuthAction, AuthenticatedRequest}
import logic.PodManager
import play.api.mvc.{Action, AnyContent, BaseController, ControllerComponents}
import play.api.routing.JavaScriptReverseRouter
import javax.inject.Inject
class JavaScriptRoutingController @Inject()(
val controllerComponents: ControllerComponents,
val authAction: AuthAction,
val podManager: PodManager
) extends BaseController {
def javascriptRoutes(): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
Ok(
JavaScriptReverseRouter("jsRoutes")(
routes.javascript.MainMenuController.createGame,
routes.javascript.IngameController.startGame,
routes.javascript.IngameController.kickPlayer,
routes.javascript.IngameController.leaveGame,
routes.javascript.IngameController.playCard,
routes.javascript.PollingController.polling
)
).as("text/javascript")
}
}

View File

@@ -3,6 +3,7 @@ package controllers
import auth.{AuthAction, AuthenticatedRequest}
import logic.PodManager
import play.api.*
import play.api.libs.json.Json
import play.api.mvc.*
import javax.inject.*
@@ -29,18 +30,28 @@ class MainMenuController @Inject()(
}
def createGame(): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val postData = request.body.asFormUrlEncoded
if (postData.isDefined) {
val gamename = postData.get.get("lobbyname").flatMap(_.headOption).getOrElse(s"${request.user.name}'s Game")
val playeramount = postData.get.get("playeramount").flatMap(_.headOption).getOrElse("")
val jsonBody = request.body.asJson
if (jsonBody.isDefined) {
val gamename: String = (jsonBody.get \ "lobbyname").asOpt[String]
.getOrElse(s"${request.user.name}'s Game")
val playeramount: String = (jsonBody.get \ "playeramount").asOpt[String]
.getOrElse(throw new IllegalArgumentException("Player amount is required."))
val gameLobby = podManager.createGame(
host = request.user,
name = gamename,
maxPlayers = playeramount.toInt
)
Redirect(routes.IngameController.game(gameLobby.id))
Ok(Json.obj(
"status" -> "success",
"redirectUrl" -> routes.IngameController.game(gameLobby.id).url
))
} else {
BadRequest("Invalid form submission")
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> "Invalid form submission"
))
}
}

View File

@@ -0,0 +1,134 @@
package controllers
import auth.{AuthAction, AuthenticatedRequest}
import de.knockoutwhist.cards.Hand
import logic.PodManager
import logic.game.{GameLobby, PollingEvents}
import logic.game.PollingEvents.{CardPlayed, LobbyUpdate, NewRound, ReloadEvent}
import model.sessions.UserSession
import model.users.User
import play.api.libs.json.{JsArray, JsValue, Json}
import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents, Result}
import util.WebUIUtils
import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class PollingController @Inject() (
val cc: ControllerComponents,
val podManager: PodManager,
val authAction: AuthAction,
implicit val ec: ExecutionContext
) extends AbstractController(cc) {
private def buildCardPlayResponse(game: GameLobby, hand: Option[Hand], newRound: Boolean): JsValue = {
val currentRound = game.logic.getCurrentRound.get
val currentTrick = game.logic.getCurrentTrick.get
val trickCardsJson = Json.toJson(
currentTrick.cards.map { case (card, player) =>
Json.obj("cardId" -> WebUIUtils.cardtoString(card), "player" -> player.name)
}
)
val scoreTableJson = Json.toJson(
game.getLogic.getPlayerQueue.get.toList.map { player =>
Json.obj(
"name" -> player.name,
"tricks" -> currentRound.tricklist.count(_.winner.contains(player))
)
}
)
val stringHand = hand.map { h =>
val cardStrings = h.cards.map(WebUIUtils.cardtoString)
Json.toJson(cardStrings).as[JsArray]
}.getOrElse(Json.arr())
val firstCardId = currentTrick.firstCard.map(WebUIUtils.cardtoString).getOrElse("BLANK")
val nextPlayer = game.getLogic.getPlayerQueue.get.duplicate().nextPlayer().name
Json.obj(
"status" -> "cardPlayed",
"animation" -> newRound,
"handData" -> stringHand,
"currentPlayerName" -> game.logic.getCurrentPlayer.get.name,
"trumpSuit" -> currentRound.trumpSuit.toString,
"trickCards" -> trickCardsJson,
"scoreTable" -> scoreTableJson,
"firstCardId" -> firstCardId,
"nextPlayer" -> nextPlayer
)
}
private def buildLobbyUsersResponse(game: GameLobby, userSession: UserSession): JsValue = {
Json.obj(
"status" -> "lobbyUpdate",
"host" -> userSession.host,
"users" -> game.getUsers.map(u => Json.obj(
"name" -> u.name,
"id" -> u.id,
"self" -> (u.id == userSession.id)
))
)
}
def handleEvent(event: PollingEvents, game: GameLobby, userSession: UserSession): Result = {
event match {
case NewRound =>
val player = game.getPlayerByUser(userSession.user)
val hand = player.currentHand()
val jsonResponse = buildCardPlayResponse(game, hand, true)
Ok(jsonResponse)
case CardPlayed =>
val player = game.getPlayerByUser(userSession.user)
val hand = player.currentHand()
val jsonResponse = buildCardPlayResponse(game, hand, false)
Ok(jsonResponse)
case LobbyUpdate =>
Ok(buildLobbyUsersResponse(game, userSession))
case ReloadEvent =>
val jsonResponse = Json.obj(
"status" -> "reloadEvent",
"redirectUrl" -> routes.IngameController.game(game.id).url
)
Ok(jsonResponse)
}
}
// --- Main Polling Action ---
def polling(gameId: String): Action[AnyContent] = authAction.async { implicit request: AuthenticatedRequest[AnyContent] =>
val playerId = request.user.id
// 1. Safely look up the game
podManager.getGame(gameId) match {
case Some(game) =>
// 2. Short-Poll Check (Check for missed events)
if (game.getPollingState.nonEmpty) {
val event = game.getPollingState.dequeue()
Future.successful(handleEvent(event, game, game.getUserSession(playerId)))
} else {
val eventPromise = game.registerWaiter(playerId)
eventPromise.future.map { event =>
game.removeWaiter(playerId)
handleEvent(event, game, game.getUserSession(playerId))
}.recover {
case _: Throwable =>
game.removeWaiter(playerId)
NoContent
}
}
case None =>
// Game not found
Future.successful(NotFound("Game not found."))
}
}
}

View File

@@ -2,21 +2,23 @@ package logic.game
import de.knockoutwhist.cards.{Hand, Suit}
import de.knockoutwhist.control.GameLogic
import de.knockoutwhist.control.GameState.{Lobby, MainMenu}
import de.knockoutwhist.control.GameState.{InGame, Lobby, MainMenu}
import de.knockoutwhist.control.controllerBaseImpl.sublogic.util.{MatchUtil, PlayerUtil}
import de.knockoutwhist.events.global.{GameStateChangeEvent, SessionClosed}
import de.knockoutwhist.events.player.PlayerEvent
import de.knockoutwhist.events.global.{CardPlayedEvent, GameStateChangeEvent, SessionClosed}
import de.knockoutwhist.events.player.{PlayerEvent, ReceivedHandEvent}
import de.knockoutwhist.player.Playertype.HUMAN
import de.knockoutwhist.player.{AbstractPlayer, PlayerFactory}
import de.knockoutwhist.rounds.{Match, Round, Trick}
import de.knockoutwhist.utils.events.{EventListener, SimpleEvent}
import exceptions.*
import logic.game.PollingEvents.{CardPlayed, LobbyUpdate, NewRound, ReloadEvent}
import model.sessions.{InteractionType, UserSession}
import model.users.User
import java.util.UUID
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.concurrent.Promise as ScalaPromise
class GameLobby private(
val logic: GameLogic,
@@ -29,7 +31,19 @@ class GameLobby private(
logic.createSession()
private val users: mutable.Map[UUID, UserSession] = mutable.Map()
private val pollingState: mutable.Queue[PollingEvents] = mutable.Queue()
private val waitingPromises: mutable.Map[UUID, ScalaPromise[PollingEvents]] = mutable.Map()
def registerWaiter(playerId: UUID): ScalaPromise[PollingEvents] = {
val promise = ScalaPromise[PollingEvents]()
waitingPromises.put(playerId, promise)
promise
}
def removeWaiter(playerId: UUID): Unit = {
waitingPromises.remove(playerId)
}
def addUser(user: User): UserSession = {
if (users.size >= maxPlayers) throw new GameFullException("The game is full!")
if (users.contains(user.id)) throw new IllegalArgumentException("User is already in the game!")
@@ -39,17 +53,28 @@ class GameLobby private(
host = false
)
users += (user.id -> userSession)
addToQueue(LobbyUpdate)
userSession
}
override def listen(event: SimpleEvent): Unit = {
event match {
case event: ReceivedHandEvent =>
addToQueue(NewRound)
users.get(event.playerId).foreach(session => session.updatePlayer(event))
case event: CardPlayedEvent =>
addToQueue(CardPlayed)
case event: PlayerEvent =>
users.get(event.playerId).foreach(session => session.updatePlayer(event))
case event: GameStateChangeEvent =>
if (event.oldState == MainMenu && event.newState == Lobby) {
return
}
if (event.oldState == Lobby && event.newState == InGame) {
addToQueue(ReloadEvent)
}else {
addToQueue(ReloadEvent)
}
users.values.foreach(session => session.updatePlayer(event))
case event: SessionClosed =>
users.values.foreach(session => session.updatePlayer(event))
@@ -58,6 +83,15 @@ class GameLobby private(
}
}
private def addToQueue(event: PollingEvents): Unit = {
if (waitingPromises.nonEmpty) {
waitingPromises.values.foreach(_.success(event))
waitingPromises.clear()
} else {
pollingState.enqueue(event)
}
}
/**
* Start the game if the user is the host.
* @param user the user who wants to start the game.
@@ -94,6 +128,7 @@ class GameLobby private(
throw new NotInThisGameException("You are not in this game!")
}
users.remove(userId)
addToQueue(LobbyUpdate)
}
/**
@@ -183,7 +218,9 @@ class GameLobby private(
def getLogic: GameLogic = {
logic
}
def getPollingState: mutable.Queue[PollingEvents] = {
pollingState
}
private def getPlayerBySession(userSession: UserSession): AbstractPlayer = {
val playerOption = getMatch.totalplayers.find(_.id == userSession.id)
if (playerOption.isEmpty) {
@@ -233,7 +270,11 @@ class GameLobby private(
}
trickOpt.get
}
def getUsers: Set[User] = {
users.values.map(d => d.user).toSet
}
}
object GameLobby {

View File

@@ -0,0 +1,8 @@
package logic.game
enum PollingEvents {
case CardPlayed
case NewRound
case ReloadEvent
case LobbyUpdate
}

View File

@@ -7,7 +7,7 @@ import model.users.User
import java.util.UUID
import java.util.concurrent.locks.{Lock, ReentrantLock}
class UserSession(user: User, val host: Boolean) extends PlayerSession {
class UserSession(val user: User, val host: Boolean) extends PlayerSession {
var canInteract: Option[InteractionType] = None
val lock: ReentrantLock = ReentrantLock()

View File

@@ -8,6 +8,10 @@ import scalafx.scene.image.Image
object WebUIUtils {
def cardtoImage(card: Card): Html = {
views.html.render.card.apply(f"images/cards/${cardtoString(card)}.png")(card.toString)
}
def cardtoString(card: Card) = {
val s = card.suit match {
case Spades => "S"
case Hearts => "H"
@@ -29,6 +33,7 @@ object WebUIUtils {
case Three => "3"
case Two => "2"
}
views.html.render.card.apply(f"images/cards/$cv$s.png")(card.toString)
f"$cv$s"
}
}

View File

@@ -3,68 +3,91 @@
@(player: de.knockoutwhist.player.AbstractPlayer, gamelobby: logic.game.GameLobby)
@main("Ingame") {
<div class="py-5 ms-4 me-4">
<div class="lobby-background vh-100">
<main class="game-field-background vh-100 ingame-side-shadow">
<div class="py-5 container-xxl">
<div class="row ms-4 me-4">
<div class="col-4 mt-5 text-start">
<h4 class="fw-semibold mb-1">Current Player</h4>
<p class="fs-5 text-primary">@gamelobby.getLogic.getCurrentPlayer.get.name</p>
@if(!TrickUtil.isOver(gamelobby.getLogic.getCurrentMatch.get, gamelobby.getLogic.getPlayerQueue.get)) {
<div class="row ms-4 me-4">
<div class="col-4 mt-5 text-start">
<h4 class="fw-semibold mb-1">Current Player</h4>
<p class="fs-5 text-primary" id="current-player-name">@gamelobby.getLogic.getCurrentPlayer.get.name</p>
@if(!TrickUtil.isOver(gamelobby.getLogic.getCurrentMatch.get, gamelobby.getLogic.getPlayerQueue.get)) {
<h4 class="fw-semibold mb-1">Next Player</h4>
@for(nextplayer <- gamelobby.getLogic.getPlayerQueue.get.duplicate()) {
<p class="fs-5 text-primary">@nextplayer</p>
<p class="fs-5 text-primary" id="next-player-name">@nextplayer</p>
}
}
</div>
}
</div>
<div class="d-flex col-md-4 text-center justify-content-center g-3 mb-5">
@for((cardplayed, player) <- gamelobby.getLogic.getCurrentTrick.get.cards) {
<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">
@util.WebUIUtils.cardtoImage(cardplayed) width="100%"/>
</div>
<div class="card-body p-2 bg-transparent">
<small class="fw-semibold text-secondary">@player</small>
<div class="col-4 text-center">
<div class="score-table mt-5" id="score-table-body">
<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>
@for(player <- gamelobby.getLogic.getPlayerQueue.get.toList.sortBy { p =>
-(gamelobby.getLogic.getCurrentRound.get.tricklist.filter { trick => trick.winner.contains(p) }.size)
}) {
<div class="d-flex justify-content-between score-row pt-1">
<div style="width: 50%" class="text-truncate">@player.name</div>
<div style="width: 50%">
@(gamelobby.getLogic.getCurrentRound.get.tricklist.filter { trick => trick.winner.contains(player) }.size)
</div>
</div>
}
</div>
}
<div class="d-flex justify-content-center g-3 mb-5" id="trick-cards-container">
@for((cardplayed, player) <- gamelobby.getLogic.getCurrentTrick.get.cards) {
<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">
@util.WebUIUtils.cardtoImage(cardplayed) width="100%"/>
</div>
<div class="card-body p-2 bg-transparent">
<small class="fw-semibold text-secondary">@player</small>
</div>
</div>
</div>
}
</div>
</div>
<div class="col-4 mt-5 text-end">
<h4 class="fw-semibold mb-1">Trumpsuit</h4>
<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>
<div class="d-inline-block border rounded shadow-sm p-1 bg-light" id="first-card-container">
@if(gamelobby.getLogic.getCurrentTrick.get.firstCard.isDefined) {
@util.WebUIUtils.cardtoImage(gamelobby.getLogic.getCurrentTrick.get.firstCard.get) width="80px"/>
} else {
@views.html.render.card.apply("images/cards/1B.png")("Blank Card") width="80px"/>
}
</div>
</div>
</div>
<div class="col-md-4 text-end">
<h4 class="fw-semibold mb-1">Trumpsuit</h4>
<p class="fs-5 text-primary">@gamelobby.getLogic.getCurrentRound.get.trumpSuit</p>
<h5 class="fw-semibold mt-4 mb-1">First Card</h5>
<div class="d-inline-block border rounded shadow-sm p-1 bg-light">
@if(gamelobby.getLogic.getCurrentTrick.get.firstCard.isDefined) {
@util.WebUIUtils.cardtoImage(gamelobby.getLogic.getCurrentTrick.get.firstCard.get) width="80px"/>
} else {
@views.html.render.card.apply("images/cards/1B.png")("Blank Card") width="80px"/>
}
<div class="row justify-content-center g-2 mt-4 bottom-div" style="backdrop-filter: blur(4px); margin-left: 0; margin-right: 0;">
<div class="row justify-content-center ingame-cards-slide" id="card-slide">
@for(i <- player.currentHand().get.cards.indices) {
<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, '@gamelobby.id')">
@util.WebUIUtils.cardtoImage(player.currentHand().get.cards(i)) width="120px" style="border-radius: 6px"/>
</div>
</div>
}
</div>
</div>
</div>
<div class="row">
</div>
<div class="row justify-content-center g-2 mt-4 bottom-div" style="backdrop-filter: blur(4px);">
<div class="row justify-content-center" id="card-slide">
@for(i <- player.currentHand().get.cards.indices) {
<div class="col-auto handcard" style="border-radius: 6px">
<form action="@(routes.IngameController.playCard(gamelobby.id))" method="post" class="m-0 p-0" style="border-radius: 6px">
<input type="hidden" name="cardId" value="@i" />
<button type="submit" class="btn btn-outline-light p-0 border-0 shadow-none" style="border-radius: 6px">
@util.WebUIUtils.cardtoImage(player.currentHand().get.cards(i)) width="120px" style="border-radius: 6px"/>
</button>
</form>
</div>
}
</div>
</div>
</div>
</main>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
pollForUpdates('@gamelobby.id');
});
</script>
}

View File

@@ -1,27 +1,72 @@
@(player: de.knockoutwhist.player.AbstractPlayer, logic: de.knockoutwhist.control.GameLogic)
@(player: de.knockoutwhist.player.AbstractPlayer, gamelobby: logic.game.GameLobby)
@main("Selecting Trumpsuit...") {
<div id="selecttrumpsuit" class="game-field game-field-background">
@if(player.equals(logic.getCurrentMatch.get.roundlist.last.winner.get)) {
<h1>Knockout Whist</h1>
<p>You (@player.toString) have won the last round! Select a trumpsuit for the next round!</p>
<p>Available trumpsuits are displayed below:</p>
<div id="playercards">
@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.Clubs))
@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.Diamonds))
</div>
<p>Your cards</p>
<div class="ingame-stage blur-sides">
<div class="container py-4">
<div class="row justify-content-center">
<div class="col-12">
<div class="card shadow-sm">
<div class="card-header text-center">
<h3 class="mb-0">Select Trump Suit</h3>
</div>
<div class="card-body">
@if(player.equals(gamelobby.logic.getCurrentMatch.get.roundlist.last.winner.get)) {
<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.
</div>
<div id="playercards">
@for(card <- player.currentHand().get.cards) {
@util.WebUIUtils.cardtoImage(card)
}
<div class="row justify-content-center col-auto mb-5">
<div class="col-auto handcard">
<form action="@routes.IngameController.playTrump(gamelobby.id)" method="post">
<input type="hidden" name="cardId" value="0" />
<button type="submit" class="btn btn-outline-light p-0 border-0 shadow-none" name="trump" value="0" style="border-radius: 6px">
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Spades)) width="120px" style="border-radius: 6px"/>
</button>
</form>
</div>
<div class="col-auto handcard">
<form action="@routes.IngameController.playTrump(gamelobby.id)" method="post">
<input type="hidden" name="cardId" value="1" />
<button type="submit" class="btn btn-outline-light p-0 border-0 shadow-none" name="trump" value="1" style="border-radius: 6px">
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Hearts)) width="120px" style="border-radius: 6px"/>
</button>
</form>
</div>
<div class="col-auto handcard">
<form action="@routes.IngameController.playTrump(gamelobby.id)" method="post">
<input type="hidden" name="cardId" value="2" />
<button type="submit" class="btn btn-outline-light p-0 border-0 shadow-none" name="trump" value="2" style="border-radius: 6px">
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Diamonds)) width="120px" style="border-radius: 6px"/>
</button>
</form>
</div>
<div class="col-auto handcard">
<form action="@routes.IngameController.playTrump(gamelobby.id)" method="post">
<input type="hidden" name="cardId" value="3" />
<button type="submit" class="btn btn-outline-light p-0 border-0 shadow-none" name="trump" value="3" style="border-radius: 6px">
@util.WebUIUtils.cardtoImage(de.knockoutwhist.cards.Card(de.knockoutwhist.cards.CardValue.Ace, de.knockoutwhist.cards.Suit.Clubs)) width="120px" style="border-radius: 6px"/>
</button>
</form>
</div>
</div>
<div class="row justify-content-center ingame-cards-slide" id="card-slide">
@for(i <- player.currentHand().get.cards.indices) {
<div class="col-auto" style="border-radius: 6px">
@util.WebUIUtils.cardtoImage(player.currentHand().get.cards(i)) width="120px" style="border-radius: 6px"/>
</div>
}
</div>
} else {
<div class="alert alert-warning" role="alert" aria-live="polite">
@gamelobby.logic.getCurrentMatch.get.roundlist.last.winner.get.name is choosing a trumpsuit. The new round will start once a suit is picked.
</div>
}
</div>
</div>
</div>
</div>
</div>
} else {
<h1>Knockout Whist</h1>
<p>@player.toString is choosing a trumpsuit. Starting new round when @player.toString picked a trumpsuit...</p>
}
</div>
</div>
}

View File

@@ -1,27 +1,107 @@
@(player: de.knockoutwhist.player.AbstractPlayer, logic: de.knockoutwhist.control.GameLogic)
@(player: de.knockoutwhist.player.AbstractPlayer, gamelobby: logic.game.GameLobby)
@main("Tie") {
<div id="tie" class="game-field game-field-background">
<h1>Knockout Whist</h1>
<p>The last Round was tied between
@for(players <- logic.playerTieLogic.getTiedPlayers) {
@players
}
</p>
@if(player.equals(logic.playerTieLogic.currentTiePlayer())) {
<p>Pick a card between 1 and @logic.playerTieLogic.highestAllowedNumber()! The resulting card will be your card for the cut.</p>
} else {
<p>@logic.playerTieLogic.currentTiePlayer() is currently picking his number for the cut.</p>
<p>Currently picked Cards:</p>
<div id="cardsplayed">
@for((player, card) <- logic.playerTieLogic.getSelectedCard) {
<div id="playedcardplayer">
<p>@player</p>
@util.WebUIUtils.cardtoImage(card)
</div>
}
</div>
}
<div class="ingame-stage blur-sides">
<div class="container py-4">
<div class="row justify-content-center">
<div class="col-12 col-md-10 col-lg-8">
<div class="card shadow-sm">
<div class="card-header text-center">
<h3 class="mb-0">Tie Break</h3>
</div>
<div class="card-body">
<div class="mb-3">
<p class="card-text">
The last round was tied between:
<span class="ms-1">
@for(players <- gamelobby.logic.playerTieLogic.getTiedPlayers) {
<span class="badge text-bg-secondary me-1">@players</span>
}
</span>
</p>
</div>
@if(player.equals(gamelobby.logic.playerTieLogic.currentTiePlayer())) {
@defining(gamelobby.logic.playerTieLogic.highestAllowedNumber()) { maxNum =>
<div class="alert alert-info" role="alert" aria-live="polite">
Pick a number between 1 and @{maxNum + 1}. The resulting card will be your card for the cut.
</div>
<form class="row g-2 align-items-center" method="post" action="@routes.IngameController.playTie(gamelobby.id)">
<div class="col-auto">
<label for="tieNumber" class="col-form-label">Your number</label>
</div>
<div class="col-auto">
<input type="number" id="tieNumber" class="form-control" name="tie" min="1" max="@{maxNum + 1}" placeholder="1" required>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary">Confirm</button>
</div>
</form>
<h6 class="mt-4 mb-3">Currently Picked Cards</h6>
<div id="cardsplayed" class="row g-3 justify-content-center">
@if(gamelobby.logic.playerTieLogic.getSelectedCard.nonEmpty) {
@for((player, card) <- gamelobby.logic.playerTieLogic.getSelectedCard) {
<div class="col-6">
<div class="card shadow-sm border-0 h-100 text-center">
<div class="card-body d-flex flex-column justify-content-between">
<p class="card-text fw-semibold mb-2 text-primary">@player</p>
<div class="card-img-top">
@util.WebUIUtils.cardtoImage(card)
</div>
</div>
</div>
</div>
}
} else {
<div class="col-12">
<div class="alert alert-info text-center" role="alert">
<i class="bi bi-info-circle me-2"></i>
No cards have been selected yet.
</div>
</div>
}
</div>
}
} else {
<div class="alert alert-warning" role="alert" aria-live="polite">
<strong>@gamelobby.logic.playerTieLogic.currentTiePlayer()</strong> is currently picking a number for the cut.
</div>
<h6 class="mt-4 mb-3">Currently Picked Cards</h6>
<div id="cardsplayed" class="row g-3 justify-content-center">
@if(gamelobby.logic.playerTieLogic.getSelectedCard.nonEmpty) {
@for((player, card) <- gamelobby.logic.playerTieLogic.getSelectedCard) {
<div class="col-6 col-sm-4 col-md-3 col-lg-2">
<div class="card shadow-sm border-0 h-100 text-center">
<div class="card-body d-flex flex-column justify-content-between">
<p class="card-text fw-semibold mb-2 text-primary">@player</p>
<div class="card-img-top">
@util.WebUIUtils.cardtoImage(card)
</div>
</div>
</div>
</div>
}
} else {
<div class="col-12">
<div class="alert alert-info text-center" role="alert">
<i class="bi bi-info-circle me-2"></i>
No cards have been selected yet.
</div>
</div>
}
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}

View File

@@ -1,82 +1,75 @@
@(user: Option[model.users.User], gamelobby: logic.game.GameLobby)
@main("Lobby") {
<div class="container">
<div class="row">
<div class="col">
<div class="p-3 fs-1 d-flex align-items-center">
<div class="text-center" style="flex-grow: 1;">
Lobby-Name: @gamelobby.name
<main class="lobby-background vh-100" id="lobbybackground">
<div class="container d-flex flex-column" style="height: calc(100vh - 1rem);">
<div class="row">
<div class="col">
<div class="p-3 fs-1 d-flex align-items-center">
<div class="text-center" style="flex-grow: 1;">
Lobby-Name: @gamelobby.name
</div>
<div class="btn btn-danger ms-auto" onclick="leaveGame('@gamelobby.id')">Exit</div>
</div>
<form action="@(routes.IngameController.leaveGame(gamelobby.id))">
<button type="submit" class="btn btn-danger ms-auto">Exit</button>
</form>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="p-3 text-center fs-4">Playeramount: @gamelobby.getPlayers.size / @gamelobby.maxPlayers</div>
<div class="row">
<div class="col">
<div class="p-3 text-center fs-4">Playeramount: @gamelobby.getPlayers.size / @gamelobby.maxPlayers</div>
</div>
</div>
</div>
<div class="row justify-content-center">
@if((gamelobby.getUserSession(user.get.id).host)) {
@for(playersession <- gamelobby.getPlayers.values) {
<div class="col-auto">
<div class="card" style="width: 18rem;">
<img src="@routes.Assets.versioned("images/profile.png")" alt="Profile" class="card-img-top w-50 mx-auto mt-3" />
<div class="card-body">
<div class="row justify-content-center align-items-center flex-grow-1">
@if((gamelobby.getUserSession(user.get.id).host)) {
<div id="players" class="justify-content-center align-items-center d-flex">
@for(playersession <- gamelobby.getPlayers.values) {
<div class="col-auto my-auto m-3">
<div class="card" style="width: 18rem;">
<img src="@routes.Assets.versioned("images/profile.png")" alt="Profile" class="card-img-top w-50 mx-auto mt-3" />
<div class="card-body">
@if(playersession.id == user.get.id) {
<h5 class="card-title">@playersession.name (You)</h5>
<a href="#" class="btn btn-danger disabled" aria-disabled="true" tabindex="-1">Remove</a>
} else {
<h5 class="card-title">@playersession.name</h5>
<div class="btn btn-danger" onclick="removePlayer('@gamelobby.id', '@playersession.id')">Remove</div>
}
</div>
</div>
</div>
}
</div>
<div class="col-12 text-center mb-5">
<div class="btn btn-success" onclick="startGame('@gamelobby.id')">Start Game</div>
</div>
} else {
<div id="players" class="justify-content-center align-items-center d-flex">
@for(playersession <- gamelobby.getPlayers.values) {
<div class="col-auto my-auto m-3"> <div class="card" style="width: 18rem;">
<img src="@routes.Assets.versioned("images/profile.png")" alt="Profile" class="card-img-top w-50 mx-auto mt-3" />
<div class="card-body">
@if(playersession.id == user.get.id) {
<h5 class="card-title">@playersession.name (You)</h5>
@* <p class="card-text">Your text could be here!</p>*@
<a href="#" class="btn btn-danger disabled" aria-disabled="true" tabindex="-1">Remove</a>
} else {
<h5 class="card-title">@playersession.name</h5>
@* <p class="card-text">Your text could be here!</p>*@
<form action="@(routes.IngameController.kickPlayer(gamelobby.id, playersession.id))" method="post">
<button type="submit" class="btn btn-danger">Remove</button>
</form>
}
</div>
</div>
</div>
}
</div>
<div class="col-12 text-center mt-3">
<p class="fs-4">Waiting for the host to start the game...</p>
<div class="spinner-border mt-1" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
}
<div class="row">
<div class="col text-center mt-3">
<a href="@(routes.IngameController.startGame(gamelobby.id))" class="btn btn-success">Start Game</a>
</div>
</div>
} else {
@for(playersession <- gamelobby.getPlayers.values) {
<div class="col-auto">
<div class="card" style="width: 18rem;">
<img src="@routes.Assets.versioned("images/profile.png")" alt="Profile" class="card-img-top w-50 mx-auto mt-3" />
<div class="card-body">
@if(playersession.id == user.get.id) {
<h5 class="card-title">@playersession.name (You)</h5>
} else {
<h5 class="card-title">@playersession.name</h5>
}
</div>
</div>
</div>
}
<div class="row">
<div class="col mt-3">
<p class="text-center fs-4">Waiting for the host to start the game...</p>
</div>
</div>
<div class="row">
<div class="col mt-1">
<div class="text-center">
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
</main>
<script>
document.addEventListener('DOMContentLoaded', () => {
pollForUpdates('@gamelobby.id');
});
</script>
}

View File

@@ -18,16 +18,11 @@
<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>
<body class="d-flex flex-column min-vh-100 game-field-background">
<main>
<body class="d-flex flex-column min-vh-100">
@* And here's where we render the `Html` object containing
* the page content. *@
@content
</main>
<footer class="footer">
</footer>
<script src="@routes.JavaScriptRoutingController.javascriptRoutes()" type="text/javascript"></script>
<script src="@routes.Assets.versioned("javascripts/main.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>
</body>

View File

@@ -2,8 +2,8 @@
@main("Create Game") {
@navbar(user)
<form action="@routes.MainMenuController.createGame()" method="post" class="game-field-background">
<div class="w-50 mx-auto">
<main class="lobby-background flex-grow-1">
<div class="w-25 mx-auto">
<div class="mt-3">
<label for="lobbyname" class="form-label">Lobby-Name</label>
<input type="text" class="form-control" id="lobbyname" name="lobbyname" placeholder="Lobby 1" required>
@@ -25,8 +25,8 @@
</div>
</div>
<div class="mt-3 text-center">
<button type="submit" class="btn btn-success">Create Game</button>
<div class="btn btn-success" onclick="createGameJS()">Create Game</div>
</div>
</div>
</form>
</main>
}

View File

@@ -1,6 +1,6 @@
@(user: Option[model.users.User])
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container d-flex justify-content-left">
<nav class="navbar navbar-expand-lg bg-body-tertiary navbar-drop-shadow">
<div class="container d-flex justify-content-start">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navBar" aria-controls="navBar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

View File

@@ -2,75 +2,179 @@
@main("Rules") {
@navbar(user)
<div id="rules">
<div class="container my-4">
<div class="card shadow-sm rounded-3">
<div class="card-header text-white text-center">
<h4 class="mb-0 text-body">Game Rules Overview</h4>
</div>
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-striped table-hover mb-0 align-middle">
<thead class="table-dark">
<tr>
<th scope="col">Section</th>
<th scope="col">Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>Players</td>
<td>Two to seven players. The aim is to be the last player left in the game.</td>
</tr>
<tr>
<td>Aim</td>
<td>To be the last player left at the end of the game, with the object in each hand being to win a majority of tricks.</td>
</tr>
<tr>
<td>Equipment</td>
<td>A standard 52-card pack is used.</td>
</tr>
<tr>
<td>Card Ranks</td>
<td>In each suit, cards rank from highest to lowest: A K Q J 10 9 8 7 6 5 4 3 2.</td>
</tr>
<tr>
<td>Deal (First Hand)</td>
<td>The dealer deals seven cards to each player. One card is turned up to determine the trump suit for the round.</td>
</tr>
<tr>
<td>Deal (Subsequent Hands)</td>
<td>The deal rotates clockwise. The player who took the most tricks in the previous hand selects the trump suit. If there's a tie, players cut cards to decide who calls trumps. One fewer card is dealt in each successive hand until the final hand consists of one card each.</td>
</tr>
<tr>
<td>Play</td>
<td>The player to the dealer's left (eldest hand) leads the first trick. Any card can be led. Other players must follow suit if possible. A player with no cards of the suit led may play any card.</td>
</tr>
<tr>
<td>Winning a Trick</td>
<td>The highest card of the suit led wins, unless a trump is played, in which case the highest trump wins. The winner of the trick leads the next.</td>
</tr>
<tr>
<td>Leading Trumps</td>
<td>Some rules disallow leading trumps before the suit has been 'broken' (a trump has been played to the lead of another suit). Leading trumps is always permissible if a player holds only trumps.</td>
</tr>
<tr>
<td>Knockout</td>
<td>At the end of each hand, any player who took no tricks is knocked out and takes no further part in the game.</td>
</tr>
<tr>
<td>Winning the Game</td>
<td>The game is won when a player takes all the tricks in a round, as all other players are knocked out, leaving only one player remaining.</td>
</tr>
<tr>
<td>Dog Life</td>
<td>The first player who takes no tricks is awarded a "dog's life". In the next hand, that player is dealt one card and can decide which trick to play it to. Each time a trick is played the "dog" may either play the card or knock on the table and wait to play it later. If the dog wins a trick, the player to the left leads the next and the dog re-enters the game properly in the next hand. If the dog fails, they are knocked out.</td>
</tr>
</tbody>
</table>
<main class="lobby-background flex-grow-1">
<div class="container my-4" style="max-width:980px;">
<div class="card rules-card shadow-sm rounded-3 overflow-hidden">
<div class="card-header text-center py-3 border-0">
<h3 class="mb-0 rules-title">Game Rules Overview</h3>
</div>
<div class="card-body p-0">
<style>
</style>
<div class="accordion rules-accordion" id="rulesAccordion">
<div class="accordion-item">
<h2 class="accordion-header" id="headingPlayers">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePlayers" aria-expanded="true" aria-controls="collapsePlayers">
Players
</button>
</h2>
<div id="collapsePlayers" class="accordion-collapse collapse show" aria-labelledby="headingPlayers" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
Two to seven players. The aim is to be the last player left in the game.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingAim">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseAim" aria-expanded="false" aria-controls="collapseAim">
Aim
</button>
</h2>
<div id="collapseAim" class="accordion-collapse collapse" aria-labelledby="headingAim" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
To be the last player left at the end of the game, with the object in each hand being to win a majority of tricks.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingEquipment">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseEquipment" aria-expanded="false" aria-controls="collapseEquipment">
Equipment
</button>
</h2>
<div id="collapseEquipment" class="accordion-collapse collapse" aria-labelledby="headingEquipment" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
A standard 52-card pack is used.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingRanks">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseRanks" aria-expanded="false" aria-controls="collapseRanks">
Card Ranks
</button>
</h2>
<div id="collapseRanks" class="accordion-collapse collapse" aria-labelledby="headingRanks" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
In each suit, cards rank from highest to lowest: A K Q J 10 9 8 7 6 5 4 3 2.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingDealFirst">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseDealFirst" aria-expanded="false" aria-controls="collapseDealFirst">
Deal (First Hand)
</button>
</h2>
<div id="collapseDealFirst" class="accordion-collapse collapse" aria-labelledby="headingDealFirst" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
The dealer deals seven cards to each player. One card is turned up to determine the trump suit for the round.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingDealSubsequent">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseDealSubsequent" aria-expanded="false" aria-controls="collapseDealSubsequent">
Deal (Subsequent Hands)
</button>
</h2>
<div id="collapseDealSubsequent" class="accordion-collapse collapse" aria-labelledby="headingDealSubsequent" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
The deal rotates clockwise. The player who took the most tricks in the previous hand selects the trump suit. If there's a tie, players cut cards to decide who calls trumps. One fewer card is dealt in each successive hand until the final hand consists of one card each.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingPlay">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePlay" aria-expanded="false" aria-controls="collapsePlay">
Play
</button>
</h2>
<div id="collapsePlay" class="accordion-collapse collapse" aria-labelledby="headingPlay" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
The player to the dealer's left (eldest hand) leads the first trick. Any card can be led. Other players must follow suit if possible. A player with no cards of the suit led may play any card.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingWinningTrick">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWinningTrick" aria-expanded="false" aria-controls="collapseWinningTrick">
Winning a Trick
</button>
</h2>
<div id="collapseWinningTrick" class="accordion-collapse collapse" aria-labelledby="headingWinningTrick" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
The highest card of the suit led wins, unless a trump is played, in which case the highest trump wins. The winner of the trick leads the next.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingLeadingTrumps">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseLeadingTrumps" aria-expanded="false" aria-controls="collapseLeadingTrumps">
Leading Trumps
</button>
</h2>
<div id="collapseLeadingTrumps" class="accordion-collapse collapse" aria-labelledby="headingLeadingTrumps" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
Some rules disallow leading trumps before the suit has been 'broken' (a trump has been played to the lead of another suit). Leading trumps is always permissible if a player holds only trumps.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingKnockout">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseKnockout" aria-expanded="false" aria-controls="collapseKnockout">
Knockout
</button>
</h2>
<div id="collapseKnockout" class="accordion-collapse collapse" aria-labelledby="headingKnockout" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
At the end of each hand, any player who took no tricks is knocked out and takes no further part in the game.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingWinningGame">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWinningGame" aria-expanded="false" aria-controls="collapseWinningGame">
Winning the Game
</button>
</h2>
<div id="collapseWinningGame" class="accordion-collapse collapse" aria-labelledby="headingWinningGame" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
The game is won when a player takes all the tricks in a round, as all other players are knocked out, leaving only one player remaining.
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="headingDogLife">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseDogLife" aria-expanded="false" aria-controls="collapseDogLife">
Dog Life
</button>
</h2>
<div id="collapseDogLife" class="accordion-collapse collapse" aria-labelledby="headingDogLife" data-bs-parent="#rulesAccordion">
<div class="accordion-body">
The first player who takes no tricks is awarded a \"dog's life\". In the next hand, that player is dealt one card and can decide which trick to play it to. Each time a trick is played the dog may either play the card or knock on the table and wait to play it later. If the dog wins a trick, the player to the left leads the next and the dog re-enters the game properly in the next hand. If the dog fails, they are knocked out.
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</main>
}

View File

@@ -3,7 +3,8 @@
# https://www.playframework.com/documentation/latest/ScalaRouting
# ~~~~
# For the javascript routing
GET /assets/js/routes controllers.JavaScriptRoutingController.javascriptRoutes()
# Primary routes
GET / controllers.MainMenuController.index()
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
@@ -25,6 +26,12 @@ GET /logout controllers.UserController.logout()
GET /game/:id controllers.IngameController.game(id: String)
GET /game/:id/join controllers.IngameController.joinGame(id: String)
GET /game/:id/start controllers.IngameController.startGame(id: String)
POST /game/:id/kickPlayer controllers.IngameController.kickPlayer(id: String, playerId: java.util.UUID)
POST /game/:id/kickPlayer controllers.IngameController.kickPlayer(id: String, playerId: String)
POST /game/:id/trump controllers.IngameController.playTrump(id: String)
POST /game/:id/tie controllers.IngameController.playTie(id: String)
GET /game/:id/leaveGame controllers.IngameController.leaveGame(id: String)
POST /game/:id/playCard controllers.IngameController.playCard(id: String)
POST /game/:id/playCard controllers.IngameController.playCard(id: String)
# Polling
GET /polling controllers.PollingController.polling(gameId: String)

View File

@@ -77,4 +77,403 @@
})
})
})
})()
})()
function pollForUpdates(gameId) {
if (!gameId) {
console.error("Game ID is missing. Stopping poll.");
return;
}
const element = document.getElementById('card-slide');
const element2 = document.getElementById('lobbybackground');
// Safety check for the target element
if (!element && !element2) {
console.error("Polling target element not found. Stopping poll.");
// Use a timeout to retry in case the DOM loads late, passing gameId.
setTimeout(() => pollForUpdates(gameId), 5000);
return;
}
const route = jsRoutes.controllers.PollingController.polling(gameId);
// Call your specific controller endpoint
fetch(route.url)
.then(response => {
if (response.status === 204) {
console.log("Polling: Timeout reached. Restarting poll.");
// CRITICAL: Pass gameId in the recursive call
setTimeout(() => pollForUpdates(gameId), 5000);
} else if (response.ok && response.status === 200) {
response.json().then(data => {
if (data.status === "cardPlayed" && data.handData && element) {
console.log("Event received: Card played. Redrawing hand.");
const newHand = data.handData;
let newHandHTML = '';
element.innerHTML = '';
if(data.animation) {
if (!element.classList.contains('ingame-cards-slide')) {
element.classList.add('ingame-cards-slide');
}
} else {
element.classList.remove('ingame-cards-slide');
}
newHand.forEach((cardId, index) => {
const cardHtml = `
<div class="col-auto handcard" style="border-radius: 6px">
<div class="btn btn-outline-light p-0 border-0 shadow-none"
data-card-id="${index}"
style="border-radius: 6px"
onclick="handlePlayCard(this, '${gameId}')">
<img src="/assets/images/cards/${cardId}.png" width="120px" style="border-radius: 6px"/>
</div>
</div>
`;
newHandHTML += cardHtml;
});
element.innerHTML = newHandHTML;
const currentPlayerElement = document.getElementById('current-player-name');
if (currentPlayerElement) {
currentPlayerElement.textContent = data.currentPlayerName;
}
const nextPlayerElement = document.getElementById('next-player-name');
if (nextPlayerElement && data.nextPlayer) {
// Use the correctly named field from the server response
nextPlayerElement.textContent = data.nextPlayer;
} else {
// Case 2: Player name is empty or null (signal to clear display).
nextPlayerElement.textContent = "";
}
const trumpElement = document.getElementById('trump-suit');
if (trumpElement) {
trumpElement.textContent = data.trumpSuit;
}
const trickContainer = document.getElementById('trick-cards-container');
if (trickContainer) {
let trickHTML = '';
// Iterate over the array of played cards received from the server
data.trickCards.forEach(trickCard => {
// Reconstruct the HTML structure from your template
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/${trickCard.cardId}.png" width="100%"/>
</div>
<div class="card-body p-2 bg-transparent">
<small class="fw-semibold text-secondary">${trickCard.player}</small>
</div>
</div>
</div>
`;
});
trickContainer.innerHTML = trickHTML;
}
const scoreBody = document.getElementById('score-table-body');
if (scoreBody && data.scoreTable) {
let scoreHTML = '';
scoreHTML += `<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>`
data.scoreTable.forEach(score => {
scoreHTML += `
<div class="d-flex justify-content-between score-row pt-1">
<div style="width: 50%" class="text-truncate">${score.name}</div>
<div style="width: 50%">${score.tricks}</div>
</div>
`;
});
scoreBody.innerHTML = scoreHTML;
}
const firstCardContainer = document.getElementById('first-card-container');
const cardId = data.firstCardId; // This will be "KH", "S7", or "BLANK"
if (firstCardContainer) {
let imageSrc = '';
let altText = 'First Card';
// Check if a card was actually played or if it's the start of a trick
if (cardId === "BLANK") {
imageSrc = "/assets/images/cards/1B.png";
altText = "Blank Card";
} else {
imageSrc = `/assets/images/cards/${cardId}.png`;
}
// Reconstruct the image HTML (assuming the inner element needs replacement)
const newImageHTML = `
<img src="${imageSrc}" alt="${altText}" width="80px" style="border-radius: 6px"/>
`;
// Clear the container and insert the new image
firstCardContainer.innerHTML = newImageHTML;
}
} else if (data.status === "reloadEvent") {
window.location.href = data.redirectUrl;
} else if (data.status === "lobbyUpdate") {
const players = document.getElementById("players");
let newHtml = ''
if (data.host) {
data.users.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="removePlayer('${gameId}', '${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 {
data.users.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>`
})
}
players.innerHTML = newHtml;
}
pollForUpdates(gameId);
});
} else {
// Handle network or server errors
console.error(`Polling error: Status ${response.status}`);
// Wait before retrying, passing gameId correctly
setTimeout(() => pollForUpdates(gameId), 5000);
}
})
.catch(error => {
console.error("Network error during polling:", error);
// Wait before retrying on network failure, passing gameId correctly
setTimeout(() => pollForUpdates(gameId), 5000);
});
}
function createGameJS() {
let lobbyName = document.getElementById("lobbyname").value;
if (lobbyName === "") {
lobbyName = "DefaultLobby"
}
const playerAmount = document.getElementById("playeramount").value;
const jsonObj = {
lobbyname: lobbyName,
playeramount: playerAmount
}
sendGameCreationRequest(jsonObj);
}
function sendGameCreationRequest(dataObject) {
const route = jsRoutes.controllers.MainMenuController.createGame();
fetch(route.url, {
method: route.type,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dataObject)
})
.then(response => {
return response.json().then(data => {
if (!response.ok) {
return Promise.reject(data);
}
return data;
});
})
.then(data => {
if (data.status === 'success') {
window.location.href = data.redirectUrl;
}
})
.catch(error => {
if (error && error.errorMessage) {
alert(`${error.errorMessage}`);
} else {
alert('An unexpected error occurred. Please try again.');
}
});
}
function startGame(gameId) {
sendGameStartRequest(gameId)
}
function sendGameStartRequest(gameId) {
const route = jsRoutes.controllers.IngameController.startGame(gameId);
fetch(route.url, {
method: route.type,
})
.then(response => {
return response.json().then(data => {
if (!response.ok) {
return Promise.reject(data);
}
return data;
});
})
.then(data => {
// SUCCESS BLOCK: data is the { status: 'success', ... } object
if (data.status === 'success') {
window.location.href = data.redirectUrl;
}
})
.catch(error => {
if (error && error.errorMessage) {
alert(`${error.errorMessage}`);
} else {
alert('An unexpected error occurred. Please try again.');
}
});
}
function removePlayer(gameid, playersessionId) {
sendRemovePlayerRequest(gameid, playersessionId)
}
function sendRemovePlayerRequest(gameId, playersessionId) {
const route = jsRoutes.controllers.IngameController.kickPlayer(gameId, playersessionId);
fetch(route.url, {
method: route.type,
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
return response.json().then(data => {
if (!response.ok) {
return Promise.reject(data);
}
return data;
});
})
.then(data => {
// SUCCESS BLOCK: data is the { status: 'success', ... } object
if (data.status === 'success') {
window.location.href = data.redirectUrl;
}
})
.catch(error => {
if (error && error.errorMessage) {
alert(`${error.errorMessage}`);
} else {
alert('An unexpected error occurred. Please try again.');
}
});
}
function leaveGame(gameId) {
sendLeavePlayerRequest(gameId)
}
function sendLeavePlayerRequest(gameId) {
const route = jsRoutes.controllers.IngameController.leaveGame(gameId);
fetch(route.url, {
method: route.type,
})
.then(response => {
return response.json().then(data => {
if (!response.ok) {
return Promise.reject(data);
}
return data;
});
})
.then(data => {
// SUCCESS BLOCK: data is the { status: 'success', ... } object
if (data.status === 'success') {
window.location.href = data.redirectUrl;
}
})
.catch(error => {
if (error && error.errorMessage) {
alert(`${error.errorMessage}`);
} else {
alert('An unexpected error occurred. Please try again.');
}
});
}
function handlePlayCard(cardobject, gameId) {
const cardId = cardobject.dataset.cardId;
const jsonObj = {
cardID: cardId
}
sendPlayCardRequest(jsonObj, gameId, cardobject)
}
function sendPlayCardRequest(jsonObj, gameId, cardobject) {
const wiggleKeyframes = [
{ transform: 'translateX(0)' },
{ transform: 'translateX(-5px)' },
{ transform: 'translateX(5px)' },
{ transform: 'translateX(-5px)' },
{ transform: 'translateX(0)' }
];
// Define the timing options
const wiggleTiming = {
duration: 400, // 0.4 seconds
iterations: 1,
easing: 'ease-in-out',
// Fill mode ensures the final state is applied until reset
fill: 'forwards'
};
const route = jsRoutes.controllers.IngameController.playCard(gameId);
fetch(route.url, {
method: route.type,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(jsonObj)
})
.then(response => {
return response.json().then(data => {
if (!response.ok) {
return Promise.reject(data);
}
return data;
});
})
.then(data => {
if (data.status === 'success') {
//window.location.href = data.redirectUrl;
}
})
.catch(error => {
if (error && error.errorMessage.includes("You can't play this card!")) {
cardobject.parentElement.animate(wiggleKeyframes, wiggleTiming);
} else if (error && error.errorMessage) {
alert(`${error.errorMessage}`);
} else {
alert('An unexpected error occurred. Please try again.');
}
});
}

View File

@@ -1,3 +1,3 @@
MAJOR=1
MINOR=0
PATCH=7
MINOR=1
PATCH=0