diff --git a/static/script.js b/static/script.js index d010dbc..d24caac 100644 --- a/static/script.js +++ b/static/script.js @@ -251,12 +251,13 @@ window.addEventListener("DOMContentLoaded", function() { } class Game { - constructor({ canvasId = 'canvas', chatInputId = 'msg', sendBtnId = "send" }) { + constructor({ canvasId = 'canvas', chatInputId = 'msg', sendBtnId = "send", leaveBtnId = "leave" }) { this.canvas = document.getElementById(canvasId); this.ctx = this.canvas.getContext('2d'); this.chatInput = document.getElementById(chatInputId); this.sendBtn = document.getElementById(sendBtnId); + this.leaveBtn = document.getElementById(leaveBtnId); this.time = 0; this.players = {}; @@ -275,6 +276,7 @@ window.addEventListener("DOMContentLoaded", function() { document.addEventListener("keydown", this._onKeyDown); document.addEventListener("keyup", this._onKeyUp); if (this.sendBtn) this.sendBtn.addEventListener("click", this._onSendClick); + if (this.leaveBtn) this.leaveBtn.addEventListener("click", this._leaveGame); this._ensurePlayer(this.pageData.username); this._initWebSocket(); @@ -333,7 +335,6 @@ window.addEventListener("DOMContentLoaded", function() { const metaTag = document.querySelector('meta[name="pagedata"]'); const json = JSON.parse(metaTag.getAttribute("content")); return json; - } _isTypingInChat() { @@ -389,6 +390,12 @@ window.addEventListener("DOMContentLoaded", function() { me.keys[e.key] = false; this._sendAction(e.key, 'keyUp') } + + if (this._isTypingInChat()) { + if (e.key === 'Enter') { + this._onSendClick() + } + } } _ensurePlayer(id) { @@ -454,6 +461,10 @@ window.addEventListener("DOMContentLoaded", function() { this.ws.onerror = (err) => { console.log("ws error:", err); }; + + this.ws.onclose = () => { + console.log("leaving game...") + } } _sendAction(action, actionType = "", message = "") { @@ -470,6 +481,9 @@ window.addEventListener("DOMContentLoaded", function() { this.ws.send(JSON.stringify(obj)); } } + _leavegame() { + this.ws.close(); + } } @@ -477,6 +491,7 @@ window.addEventListener("DOMContentLoaded", function() { canvasId: 'canvas', chatInputId: 'msg', sendBtnId: 'send', + leaveBtnId: 'leave', }); game.start(); }); diff --git a/templates/index.html b/templates/index.html index d68181a..e7d0172 100644 --- a/templates/index.html +++ b/templates/index.html @@ -76,6 +76,7 @@ Logged In as {{ .Username}} {{ end }} +