Sync push

This commit is contained in:
Christoph Hagen
2021-12-03 18:03:29 +01:00
parent 4fe71136a2
commit 3db9652cad
27 changed files with 1540 additions and 898 deletions

View File

@ -32,26 +32,26 @@ async function resumeSessionRequest(token) {
async function performGetCurrentTableRequest(token) {
return fetch("player/table", { method: 'POST', body: token })
.then(convertServerResponse)
.then(convertJsonResponse)
}
async function performCreateTableRequest(token, name, visibility) {
const vis = visibility ? "public" : "private";
return fetch("/table/create/" + vis + "/" + name, { method: 'POST', body: token })
.then(convertServerResponse)
.then(convertJsonResponse)
}
async function performJoinTableRequest(tableId, token) {
return fetch("/table/join/" + tableId, { method: 'POST', body: token })
.then(convertServerResponse)
.then(function(value) {})
.then(convertJsonResponse)
}
async function performGetPublicTablesRequest(token) {
return fetch("/tables/public", { method: 'POST', body: token })
.then(convertServerResponse)
.then(function(text) {
return JSON.parse(text);
})
.then(convertJsonResponse)
}
async function performLeaveTableRequest(token) {
@ -60,10 +60,9 @@ async function performLeaveTableRequest(token) {
.then(function(value) {})
}
async function performDealCardsRequest(token) {
return fetch("/deal", { method: 'POST', body: token })
async function performPlayerActionRequest(token, action) {
return fetch("/player/action/" + action, { method: 'POST', body: token })
.then(convertServerResponse)
.then(function(value) {})
}
function convertServerResponse(response) {
@ -90,3 +89,10 @@ function convertServerResponse(response) {
throw Error("Unexpected response: " + response.statusText)
}
}
function convertJsonResponse(text) {
if (text == "") {
return null;
}
return JSON.parse(text);
}

View File

@ -1,53 +1,59 @@
/**
* This file acts as an abstraction layer between HTML and JS.
*/
* This file acts as an abstraction layer between HTML and JS.
*/
var playerName = ""
var debugSessionToken = null
const debugMode = true // Does not load session token, to allow multiple players per browser
function setDisplayStyle(id, style) {
document.getElementById(id).style.display = style
}
function hide(elementId) {
setDisplayStyle(elementId, "none")
}
function showLoginElements() {
setDisplayStyle("login-window", "table")
setDisplayStyle("top-bar", "none")
setDisplayStyle("table-list-bar", "none")
setDisplayStyle("table-list", "none")
setDisplayStyle("game-bar", "none")
setDisplayStyle("table-players", "none")
setDisplayStyle("player-cards", "none")
hide("top-bar")
hide("table-list-bar")
hide("table-list")
hide("game-bar")
hide("table-players")
hide("player-cards")
}
function showTableListElements() {
setDisplayStyle("login-window", "none")
hide("login-window")
setDisplayStyle("top-bar", "inherit")
setDisplayStyle("table-list-bar", "grid")
setDisplayStyle("table-list", "inherit")
setDisplayStyle("game-bar", "none")
setDisplayStyle("table-players", "none")
setDisplayStyle("player-cards", "none")
hide("game-bar")
hide("table-players")
hide("player-cards")
}
function showGameElements() {
setDisplayStyle("login-window", "none")
hide("login-window")
setDisplayStyle("top-bar", "inherit")
setDisplayStyle("table-list-bar", "none")
setDisplayStyle("table-list", "none")
hide("table-list-bar")
hide("table-list")
setDisplayStyle("game-bar", "grid")
setDisplayStyle("table-players", "grid")
setDisplayStyle("player-cards", "grid")
}
function showTableName(name) {
document.getElementById("table-connected-label").innerHTML = name
}
function showConnectedState() {
const label = document.getElementById("table-connected-label")
label.innerHTML = "Connected"
label.style.color = "var(--text-color)"
showConnectionState("bottom", true)
}
function showDisconnectedState() {
const label = document.getElementById("table-connected-label")
label.innerHTML = "Disconnected"
label.style.color = "var(--alert-color)"
showConnectionState("bottom", false)
}
function showDealButton() {
@ -55,7 +61,7 @@ function showDealButton() {
}
function hideDealButton() {
setDisplayStyle("deal-button", "none")
hide("deal-button")
}
function setPlayerName(name) {
@ -80,10 +86,17 @@ function clearLoginPassword() {
}
function getSessionToken() {
if (debugMode) {
return debugSessionToken
}
return localStorage.getItem('token')
}
function setSessionToken(token) {
if (debugMode) {
debugSessionToken = token
return
}
localStorage.setItem('token', token)
}
@ -111,23 +124,25 @@ function setTableListContent(content) {
document.getElementById("table-list").innerHTML = content
}
function setTablePlayerInfo(nr, name, connected, active) {
const infoElement = "table-player-name" + nr.toString()
const connectionElement = "table-player-state" + nr
const nameElement = document.getElementById(infoElement)
if (name == "") {
nameElement.innerHTML = "Empty"
nameElement.style.color = "var(--secondary-text-color)"
setDisplayStyle(connectionElement, "none")
return
}
function setTablePlayerInfo(position, name, connected, active) {
nameColor = active ? "var(--button-color)" : "var(--text-color)"
setTablePlayerElements(position, name, nameColor, connected)
}
function setEmptyPlayerInfo(position) {
setTablePlayerElements(position, "Empty", "var(--secondary-text-color)", true)
}
function setTablePlayerElements(position, name, nameColor, connected) {
const nameElement = document.getElementById("table-player-name-" + position)
nameElement.style.color = nameColor
nameElement.innerHTML = name
nameElement.style.color = active ? "var(--button-color)" : "var(--text-color)"
if (connected) {
setDisplayStyle(connectionElement, "none")
} else {
setDisplayStyle(connectionElement, "inherit")
}
showConnectionState(position, connected)
}
function showConnectionState(position, connected) {
const connectionElement = "table-player-state-" + position
setDisplayStyle(connectionElement, connected ? "none" : "inherit")
}
function setTableCard(index, card) {
@ -138,7 +153,7 @@ function setTableCard(index, card) {
function setHandCard(index, card, playable) {
const id = "player-card" + index.toString()
setCard(id, card)
document.getElementById(id).disabled = true
document.getElementById(id).disabled = !playable
}
function setCard(id, card) {
@ -147,4 +162,125 @@ function setCard(id, card) {
} else {
document.getElementById(id).style.backgroundImage = "url('/cards/" + card + ".jpeg')"
}
}
function updateTableInfo(table) {
showTableName(table.name)
// Set own cards
const cardCount = table.player.cards.length
for (let i = 0; i < cardCount; i += 1) {
const card = table.player.cards[i]
setHandCard(i+1, card.card, card.playable)
}
for (let i = cardCount; i < 8; i += 1) {
setHandCard(i+1, "", false)
}
// Show player info
console.log(table)
setInfoForPlayer(table.player, "bottom")
setActionsForOwnPlayer(table.player.actions)
if (table.hasOwnProperty("playerLeft")) {
setInfoForPlayer(table.playerLeft, "left")
} else {
setEmptyPlayerInfo("left")
}
if (table.hasOwnProperty("playerAcross")) {
setInfoForPlayer(table.playerAcross, "top")
} else {
setEmptyPlayerInfo("top")
}
if (table.hasOwnProperty("playerRight")) {
setInfoForPlayer(table.playerRight, "right")
} else {
setEmptyPlayerInfo("right")
}
// if (table.tableIsFull) {
// showDealButton()
// } else {
// hideDealButton()
// }
// TODO
// Use .hasOwnProperty() for optionals
}
function setInfoForPlayer(player, position) {
setTablePlayerInfo(position, player.name, player.connected, player.active)
}
function clearInfoForPlayer(position) {
setEmptyPlayerInfo(position)
}
function setActionsForOwnPlayer(actions) {
const len = actions.length
for (let i = 0; i < len; i += 1) {
const action = actions[i]
setActionButton(i+1, textForAction(action), action)
}
for (let i = len; i < 3; i += 1) {
hideActionButton(i+1)
}
}
function textForAction(action) {
switch (action) {
/// The player can request cards to be dealt
case "deal":
return "Austeilen"
/// The player doubles on the initial four cards
case "double":
return "Legen"
/// The player does not double on the initial four cards
case "skip":
return "Nicht legen"
/// The player offers a wedding (one trump card)
case "wedding":
return "Hochzeit anbieten"
/// The player can choose to accept the wedding
case "accept":
return "Hochzeit akzeptieren"
/// The player matches or increases the game during auction
case "bid":
return "Spielen"
/// The player does not want to play
case "out":
return "Weg"
/// The player claims to win and doubles the game cost ("schießen")
case "raise":
return "Schießen"
}
return action
}
function setActionButton(position, text, action) {
const button = document.getElementById("action-button" + position.toString())
button.style.display = "inherit"
button.innerHTML = text
button.onclick = function() {
performAction(action)
};
}
function hideActionButton(position) {
hide("action-button" + position.toString())
}
function performAction(action) {
const token = getSessionToken()
if (token == null) {
showBlankLogin()
return
}
performPlayerActionRequest(token, action)
// TODO: Handle errors and success
}

View File

@ -1,7 +1,8 @@
// The web socket to connect to the server
var socket = null;
var tableId = "";
var tableId = null;
var activePlayer = null;
function closeSocketIfNeeded() {
if (socket) {
@ -11,7 +12,7 @@ function closeSocketIfNeeded() {
}
function didLeaveTable() {
tableId = ""
tableId = null
}
function didCloseSocket() {
@ -22,7 +23,15 @@ function setTableId(table) {
tableId = table
}
function showBlankLoginScreen(text) {
function showLoginWithError(error) {
showLoginWithText(error.message)
}
function showBlankLogin() {
showLoginWithText("")
}
function showLoginWithText(text) {
closeSocketIfNeeded()
didLeaveTable()
clearLoginPassword()
@ -32,125 +41,93 @@ function showBlankLoginScreen(text) {
setLoginError(text)
}
function showGame(tableId) {
setTableId(tableId)
const token = getSessionToken()
if (token) {
showGameElements()
openSocket(token)
// TODO: Show interface
console.log("Show table " + tableId)
} else {
showBlankLoginScreen("")
function showTableOrList(table) {
if (table == null) {
didLeaveTable()
showTableListElements()
closeSocketIfNeeded()
refreshTables()
// TODO: Show table list, refresh
return
}
const token = getSessionToken()
if (token == null) {
showBlankLogin()
return
}
clearTableName()
setTableId(table.id)
showGameElements()
updateTableInfo(table)
openSocket(token)
}
function registerUser() {
createSession(performRegisterPlayerRequest)
}
function loginUser() {
createSession(performLoginPlayerRequest)
}
function createSession(inputFunction) {
const username = getLoginName()
const password = getLoginPassword()
if (username == "") {
setLoginError("Please enter your desired user name")
showLoginWithText("Please enter your user name")
return
}
if (password == "") {
setLoginError("Please enter a password")
showLoginWithText("Please enter a password")
return
}
performRegisterPlayerRequest(username, password)
inputFunction(username, password)
.then(function(token) {
setSessionToken(token)
setPlayerName(username)
showTableListElements()
loadCurrentTable(token)
}).catch(function(error) {
setLoginError(error.message)
})
}).catch(showLoginWithError)
}
function logoutUser() {
const token = getSessionToken()
if (token == null) {
showBlankLogin()
return
}
performLogoutRequest(token)
.then(function() {
showBlankLogin()
}).catch(showLoginWithError)
}
function deletePlayerAccount() {
const name = getPlayerName()
const password = getLoginPassword()
performDeletePlayerRequest(name, password, function(error) {
if (error == "") {
showBlankLoginScreen("")
console.log("Player deleted")
} else {
closeSocketIfNeeded()
didLeaveTable()
deleteSessionToken()
alert(error)
console.log(error)
}
})
}
function loginUser() {
const username = getLoginName()
const password = getLoginPassword()
if (username == "") {
setLoginError("Please enter your user name")
return
}
if (password == "") {
setLoginError("Please enter your password")
return
}
performLoginPlayerRequest(username, password)
.then(function(token) {
setSessionToken(token)
setPlayerName(username)
showTableListElements()
loadCurrentTable(token)
}).catch(function(error) {
setLoginError(error.message)
})
}
function logoutUser() {
const token = getSessionToken()
if (token) {
performLogoutRequest(token)
.then(function() {
showBlankLoginScreen("")
}).catch(function(error) {
showBlankLoginScreen(error.message)
console.log(error)
})
} else {
showBlankLoginScreen("")
}
performDeletePlayerRequest(name, password)
.then(showBlankLogin)
.catch(showLoginWithError)
}
function loadExistingSession() {
const token = getSessionToken()
if (token) {
resumeSessionRequest(token)
.then(function(name) {
setPlayerName(name)
showTableListElements()
loadCurrentTable(token)
}).catch(function(error) {
showBlankLoginScreen(error.message)
})
} else {
showBlankLoginScreen("")
if (token == null) {
showBlankLogin()
return
}
resumeSessionRequest(token)
.then(function(name) {
setPlayerName(name)
loadCurrentTable(token)
}).catch(showLoginWithError)
}
function loadCurrentTable(token) {
performGetCurrentTableRequest(token)
.then(function(tableId) {
if (tableId == "") {
didLeaveTable()
refreshTables()
return
}
console.log("Loaded table " + tableId)
showGame(tableId)
}).catch(function(error) {
showBlankLoginScreen(error.message)
})
.then(showTableOrList)
.catch(showLoginWithError)
}
function createTable() {
@ -159,70 +136,56 @@ function createTable() {
return
}
const token = getSessionToken()
if (token) {
const isVisible = getTableVisibility()
performCreateTableRequest(token, tableName, isVisible)
.then(function(tableId) {
clearTableName()
showGame(tableId)
}).catch(function(error) {
showBlankLoginScreen(error.message)
})
} else {
showBlankLoginScreen("")
}
if (token == null) {
showBlankLogin()
return
}
const isVisible = getTableVisibility()
performCreateTableRequest(token, tableName, isVisible)
.then(showTableOrList)
.catch(showLoginWithError)
}
function joinTable(tableId) {
const token = getSessionToken()
if (token) {
performJoinTableRequest(tableId, token)
.then(function() {
showGame(tableId)
})
.catch(function(error) {
showBlankLoginScreen(error.message)
})
} else {
showBlankLoginScreen("")
if (token == null) {
showBlankLogin()
return
}
performJoinTableRequest(tableId, token)
.then(showTableOrList)
.catch(showLoginWithError)
}
function leaveTable() {
const token = getSessionToken()
if (token) {
performLeaveTableRequest(token)
.then(function() {
showTableListElements()
closeSocketIfNeeded()
didLeaveTable()
refreshTables()
})
.catch(function(error) {
showBlankLoginScreen(error.message)
})
} else {
showBlankLoginScreen("")
if (token == null) {
showBlankLogin()
return
}
performLeaveTableRequest(token)
.then(function() {
showTableOrList(null)
})
.catch(showLoginWithError)
}
function openSocket(token) {
socket = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + "/session/start")
socket.onopen = function(e) {
socket.send(token);
showConnectedState()
};
socket.onmessage = function(event) {
// TODO: Handle server data
//event.data
handleServerUpdates(event.data)
const table = convertJsonResponse(event.data)
updateTableInfo(table)
};
socket.onclose = function(event) {
if (event.wasClean) {
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
@ -238,52 +201,15 @@ function openSocket(token) {
};
}
function handleServerUpdates(data) {
const info = JSON.parse(data.substring(1))
if (data.startsWith("t")) {
handleTableInfoUpdate(info)
} else if (data.startsWith("c")) {
handleCardInfoUpdate(info)
} else {
console.log("Unhandled update: " + data)
}
}
function handleTableInfoUpdate(info) {
for (let i = 0, len = info.players.length; i < len; i += 1) {
const player = info.players[i]
// TODO: Mark active player
setTablePlayerInfo(i + 1, player.name, player.connected, false)
}
if (info.tableIsFull) {
showDealButton()
} else {
hideDealButton()
}
}
function handleCardInfoUpdate(info) {
for (let i = 0, len = info.cards.length; i < len; i += 1) {
setHandCard(i+1, info.cards[i].card, info.cards[i].playable)
}
for (let i = 0, len = info.tableCards.length; i < len; i += 1) {
setTableCard(i+1, info.tableCards[i])
}
}
function refreshTables() {
const token = getSessionToken()
if (token) {
performGetPublicTablesRequest(token)
.then(function(json) {
const html = processTableList(json)
setTableListContent(html)
}).catch(function(error) {
showBlankLoginScreen(error.message)
})
} else {
showBlankLoginScreen()
if (token == null) {
showBlankLogin()
return
}
performGetPublicTablesRequest(token)
.then(processTableList)
.catch(showLoginWithError)
}
function processTableList(tables) {
@ -300,22 +226,20 @@ function processTableList(tables) {
if (tableInfo.players.length == 0) {
html += "<div class=\"table-subtitle\">No players</div>"
} else {
const names = tableInfo.players.map(function(player) { return player.name }).join(", ")
html += "<div class=\"table-subtitle\">Players: " + names + "</div>"
const names = tableInfo.players.join(", ")
html += "<div class=\"table-subtitle\">" + names + "</div>"
}
html += "</div>" // table-row
}
return html
setTableListContent(html)
}
function dealCards() {
const token = getSessionToken()
if (token) {
performDealCardsRequest(token)
.catch(function(error) {
showBlankLoginScreen(error.message)
})
} else {
showBlankLoginScreen()
if (token == null) {
showBlankLogin()
return
}
performDealCardsRequest(token)
.catch(showLoginWithError)
}

View File

@ -33,28 +33,37 @@
<div id="table-list">
</div>
<div id="table-players">
<button id="deal-button" class="standard-button" onclick="dealCards()">Deal cards</button>
<button id="bid-button" class="standard-button" onclick="increaseBid()">Bid</button>
<button id="fold-button" class="standard-button" onclick="fold()">Fold</button>
<div id="table-player-card1" class="table-card"></div>
<div id="table-player-card2" class="table-card"></div>
<div id="table-player-card3" class="table-card"></div>
<div id="table-player-card4" class="table-card"></div>
<div id="table-player-info1">
<div id="table-player-name1">Player 1</div>
<div id="table-player-state1" class="player-connection-state">Offline</div>
<div id="action-buttons">
<button id="action-button-spacer"></button>
<div class="action-button-container">
<button id="action-button3" class="standard-button action-button"></button>
</div>
<div class="action-button-container">
<button id="action-button2" class="standard-button action-button"></button>
</div>
<div class="action-button-container">
<button id="action-button1" class="standard-button action-button"></button>
</div>
</div>
<div id="table-player-info2">
<div id="table-player-name2">Player 2</div>
<div id="table-player-state2" class="player-connection-state">Offline</div>
<div id="table-player-card-top" class="table-card"></div>
<div id="table-player-card-right" class="table-card"></div>
<div id="table-player-card-bottom" class="table-card"></div>
<div id="table-player-card-left" class="table-card"></div>
<div id="table-player-info-top">
<div id="table-player-name-top">Player 1</div>
<div id="table-player-state-top" class="player-connection-state">Offline</div>
</div>
<div id="table-player-info3">
<div id="table-player-name3">Player 3</div>
<div id="table-player-state3" class="player-connection-state">Offline</div>
<div id="table-player-info-right">
<div id="table-player-name-right">Player 2</div>
<div id="table-player-state-right" class="player-connection-state">Offline</div>
</div>
<div id="table-player-info4">
<div id="table-player-name4">Player 4</div>
<div id="table-player-state4" class="player-connection-state">Offline</div>
<div id="table-player-info-bottom">
<div id="table-player-name-bottom">Player 3</div>
<div id="table-player-state-bottom" class="player-connection-state">Offline</div>
</div>
<div id="table-player-info-left">
<div id="table-player-name-left">Player 4</div>
<div id="table-player-state-left" class="player-connection-state">Offline</div>
</div>
</div>
<div id="player-cards">

View File

@ -275,31 +275,40 @@ body {
margin-top: 20px;
margin-left: auto;
margin-right: auto;
width: 549px;
width: 649px;
height: 437px;
grid-template-columns: 150px 71px 36px 35px 36px 71px 150px;
grid-template-columns: 200px 71px 36px 35px 36px 71px 200px;
grid-template-rows: 111px 76px 35px 76px 111px;
column-gap: 0px;
row-gap: 0px;
align-items: center;
}
#deal-button {
display: none;
#action-buttons {
grid-column: 7;
grid-row: 5;
grid-row: 4 / span 2;
width: 200px;
height: 187px;
}
#fold-button {
.action-button {
height: 100%;
width: 100%;
display: none;
grid-column: 1;
grid-row: 5;
}
#bid-button {
display: none;
grid-column: 7;
grid-row: 5;
.action-button-container {
height: 40px;
width: 160px;
margin-top: 10px;
margin-left: 40px;
}
#action-button-spacer {
height: 37px;
width: 100%;
background-color: var(--standard-background);
border: none;
}
.table-card {
@ -308,31 +317,31 @@ body {
background-color: var(--element-background);
}
#table-player-card1 { /* bottom */
#table-player-card-bottom {
grid-column: 3 / span 3;
grid-row: 4 / span 2;
z-index: 2;
}
#table-player-card2 { /* left */
#table-player-card-left {
grid-column: 2 / span 2;
grid-row: 2 / span 3;
z-index: 1;
}
#table-player-card3 { /* top */
#table-player-card-top {
grid-column: 3 / span 3;
grid-row: 1 / span 2;
z-index: 4;
}
#table-player-card4 { /* right */
#table-player-card-right {
grid-column: 5 / span 2;
grid-row: 2 / span 3;
z-index: 3;
}
#table-player-info1 { /* bottom */
#table-player-info-bottom {
grid-column: 1 / span 2;
grid-row: 5;
font-size: large;
@ -341,7 +350,7 @@ body {
margin-top: 50px;
}
#table-player-info2 { /* left */
#table-player-info-left {
grid-column: 1;
grid-row: 3;
font-size: large;
@ -349,7 +358,7 @@ body {
margin-right: 15px;
}
#table-player-info3 { /* top */
#table-player-info-top {
grid-column: 1 / span 2;
grid-row: 1;
font-size: large;
@ -358,7 +367,7 @@ body {
margin-bottom: 50px;
}
#table-player-info4 { /* right */
#table-player-info-right {
grid-column: 7;
grid-row: 3;
font-size: large;
@ -370,14 +379,6 @@ body {
color: var(--alert-color);
}
#table-player-state1 {
display: none;
}
#table-player-state2 {
display: none;
}
#player-cards {
display: none;
margin-left: auto;