lots of changes to switch to vue

This commit is contained in:
Zutatensuppe 2021-05-13 22:45:55 +02:00
parent 5adb8806dc
commit a0118b0bdf
22 changed files with 582 additions and 920 deletions

View file

@ -17,10 +17,10 @@ function send(message) {
let clientSeq
let events
function connect(gameId, clientId) {
function connect(address, gameId, clientId) {
clientSeq = 0
events = {}
conn = new WsClient(WS_ADDRESS, clientId + '|' + gameId)
conn = new WsClient(address, clientId + '|' + gameId)
return new Promise(resolve => {
conn.connect()
conn.onSocket('message', async ({ data }) => {
@ -46,10 +46,10 @@ function connect(gameId, clientId) {
})
}
function connectReplay(gameId, clientId) {
function connectReplay(address, gameId, clientId) {
clientSeq = 0
events = {}
conn = new WsClient(WS_ADDRESS, clientId + '|' + gameId)
conn = new WsClient(address, clientId + '|' + gameId)
return new Promise(resolve => {
conn.connect()
conn.onSocket('message', async ({ data }) => {
@ -67,6 +67,14 @@ function connectReplay(gameId, clientId) {
})
}
function disconnect() {
if (conn) {
conn.disconnect()
}
clientSeq = 0
events = {}
}
function sendClientEvent(evt) {
// when sending event, increase number of sent events
// and add the event locally
@ -78,6 +86,7 @@ function sendClientEvent(evt) {
export default {
connect,
connectReplay,
disconnect,
onServerChange,
sendClientEvent,
}

View file

@ -2,6 +2,8 @@
import Time from '../common/Time.js'
const CODE_CUSTOM_DISCONNECT = 4000
/**
* Wrapper around ws that
* - buffers 'send' until a connection is available
@ -57,8 +59,16 @@ export default class WsWrapper {
}
ws.onclose = (e) => {
this.handle = null
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1 * Time.SEC)
if (e.code !== CODE_CUSTOM_DISCONNECT) {
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1 * Time.SEC)
}
this.onclose(e)
}
}
disconnect() {
if (this.handle) {
this.handle.close(CODE_CUSTOM_DISCONNECT)
}
}
}

View file

@ -2,23 +2,23 @@
import Time from './../../common/Time.js'
const GameTeaser = {
export default {
name: 'game-teaser',
props: {
game: Object,
},
template: `
<div class="game-teaser" :style="style">
<a class="game-info" :href="'/g/' + game.id">
<router-link class="game-info" :to="{ name: 'game', params: { id: game.id } }">
<span class="game-info-text">
🧩 {{game.tilesFinished}}/{{game.tilesTotal}}<br />
👥 {{game.players}}<br />
{{time(game.started, game.finished)}}<br />
</span>
</a>
<a v-if="false && game.hasReplay" class="game-replay" :href="'/replay/' + game.id">
</router-link>
<router-link v-if="false && game.hasReplay" class="game-replay" :to="{ name: 'replay', params: { id: game.id } }">
Watch replay
</a>
</router-link>
</div>`,
computed: {
style() {
@ -38,5 +38,3 @@ const GameTeaser = {
},
},
}
export default GameTeaser

View file

@ -0,0 +1,26 @@
"use strict"
// ingame component
// shows the help (key bindings)
export default {
name: 'help-overlay',
template: `<div class="overlay transparent" @click="$emit('bgclick')">
<table class="help" @click.stop="">
<tr><td> Move up:</td><td><div><kbd>W</kbd>/<kbd></kbd>/🖱</div></td></tr>
<tr><td> Move down:</td><td><div><kbd>S</kbd>/<kbd></kbd>/🖱</div></td></tr>
<tr><td> Move left:</td><td><div><kbd>A</kbd>/<kbd></kbd>/🖱</div></td></tr>
<tr><td> Move right:</td><td><div><kbd>D</kbd>/<kbd></kbd>/🖱</div></td></tr>
<tr><td></td><td><div>Move faster by holding <kbd>Shift</kbd></div></td></tr>
<tr><td>🔍+ Zoom in:</td><td><div><kbd>E</kbd>/🖱-Wheel</div></td></tr>
<tr><td>🔍- Zoom out:</td><td><div><kbd>Q</kbd>/🖱-Wheel</div></td></tr>
<tr><td>🖼 Toggle preview:</td><td><div><kbd>Space</kbd></div></td></tr>
<tr><td>🧩 Toggle fixed pieces:</td><td><div><kbd>F</kbd></div></td></tr>
<tr><td>🧩 Toggle loose pieces:</td><td><div><kbd>G</kbd></div></td></tr>
</table>
</div>`,
emits: {
bgclick: null,
},
}

View file

@ -1,6 +1,6 @@
"use strict"
const ImageTeaser = {
export default {
name: 'image-teaser',
props: {
image: Object
@ -20,5 +20,3 @@ const ImageTeaser = {
},
},
}
export default ImageTeaser

View file

@ -0,0 +1,27 @@
"use strict"
// ingame component
// shows the preview image
export default {
name: 'preview-overlay',
template: `
<div class="overlay" @click="$emit('bgclick')">
<div class="preview">
<div class="img" :style="previewStyle"></div>
</div>
</div>`,
props: {
img: String,
},
emits: {
bgclick: null,
},
computed: {
previewStyle () {
return {
backgroundImage: `url('${this.img}')`,
}
},
},
}

View file

@ -0,0 +1,36 @@
"use strict"
import Time from './../../common/Time.js'
// ingame component
// shows timer, tiles left, etc..
// maybe split it up later
export default {
name: 'puzzle-status',
template: `
<div class="timer">
<div>
🧩 {{piecesDone}}/{{piecesTotal}}
</div>
<div>
{{icon}} {{durationStr}}
</div>
<slot />
</div>
`,
props: {
finished: Boolean,
duration: Number,
piecesDone: Number,
piecesTotal: Number,
},
computed: {
icon () {
return this.finished ? '🏁' : '⏳'
},
durationStr () {
return Time.durationStr(this.duration)
},
}
}

View file

@ -0,0 +1,41 @@
"use strict"
// ingame component
// shows player scores
export default {
name: "scores",
template: `
<div class="scores">
<div>Scores</div>
<table>
<tr v-for="(p, idx) in actives" :key="idx" :style="{color: p.color}">
<td></td>
<td>{{p.name}}</td>
<td>{{p.points}}</td>
</tr>
<tr v-for="(p, idx) in idles" :key="idx" :style="{color: p.color}">
<td>💤</td>
<td>{{p.name}}</td>
<td>{{p.points}}</td>
</tr>
</table>
</div>
`,
computed: {
actives () {
// TODO: dont sort in place
this.activePlayers.sort((a, b) => b.points - a.points)
return this.activePlayers
},
idles () {
// TODO: dont sort in place
this.idlePlayers.sort((a, b) => b.points - a.points)
return this.idlePlayers
},
},
props: {
activePlayers: Array,
idlePlayers: Array,
},
}

View file

@ -0,0 +1,38 @@
"use strict"
// ingame component
// allows to change (player) settings
export default {
name: 'settings-overlay',
template: `
<div class="overlay transparent" @click="$emit('bgclick')">
<table class="settings" @click.stop="">
<tr>
<td><label>Background: </label></td>
<td><input type="color" v-model="modelValue.background" /></td>
</tr>
<tr>
<td><label>Color: </label></td>
<td><input type="color" v-model="modelValue.color" /></td>
</tr>
<tr>
<td><label>Name: </label></td>
<td><input type="text" maxLength="16" v-model="modelValue.name" /></td>
</tr>
</table>
</div>
`,
emits: {
bgclick: null,
'update:modelValue': null,
},
props: {
modelValue: Object,
},
created () {
this.$watch('modelValue', val => {
this.$emit('update:modelValue', val)
}, { deep: true })
},
}

View file

@ -1,6 +1,6 @@
"use strict"
const Upload = {
export default {
name: 'upload',
props: {
accept: String,
@ -27,5 +27,3 @@ const Upload = {
},
}
}
export default Upload

View file

@ -12,8 +12,8 @@ import fireworksController from './Fireworks.js'
import Protocol from '../common/Protocol.js'
import Time from '../common/Time.js'
const MODE_PLAY = 'play'
const MODE_REPLAY = 'replay'
export const MODE_PLAY = 'play'
export const MODE_REPLAY = 'replay'
let PIECE_VIEW_FIXED = true
let PIECE_VIEW_LOOSE = true
@ -39,190 +39,6 @@ function addCanvasToDom(TARGET_EL, canvas) {
return canvas
}
function addMenuToDom(TARGET_EL, previewImageUrl, setHotkeys) {
const ELEMENTS = {}
const h = (type, props, children) => {
if (typeof props === 'string' || typeof props === 'number') {
children = [props]
props = {}
}
if (props instanceof Array) {
children = props
props = {}
}
if (children && !(children instanceof Array)) {
children = [children]
}
if (!ELEMENTS[type]) {
ELEMENTS[type] = document.createElement(type)
}
const el = ELEMENTS[type].cloneNode(true)
if (children) {
for (const child of children) {
if (typeof child === 'string' || typeof child === 'number') {
el.appendChild(document.createTextNode(child))
} else {
el.appendChild(child)
}
}
}
if (props) {
for (const k in props) {
if (k === 'click') {
el.addEventListener('click', props[k])
} else if (k === 'cls') {
if (typeof props[k] === 'string') {
el.classList.add(props[k])
} else {
for (const cls of props[k]) {
el.classList.add(cls)
}
}
} else if (k === 'style') {
for (const s in props[k]) {
el.style[s] = props[k][s]
}
} else {
el[k] = props[k]
}
}
}
return el
}
const row = (props, children) => {
if (props instanceof Array) {
children = props
props = {}
}
return h('tr', props, children.map(el => h('td', {}, el)))
}
const bgColorPickerEl = h('input', { type: 'color' })
const playerColorPickerEl = h('input', { type: 'color' })
const nameChangeEl = h('input', { type: 'text', maxLength: 16 })
const stopProp = (e) => e.stopPropagation()
const mkToggler = (el, hotkeys = true) => () => toggle(el, hotkeys)
const mkSelfToggler = (hotkeys = true) => (ev) => toggle(ev.target, hotkeys)
const toggle = (el, hotkeys = true) => {
el.classList.toggle('closed')
if (hotkeys) {
setHotkeys(el.classList.contains('closed'))
}
}
const helpOverlay = h(
'div',
{ cls: ['overlay', 'transparent', 'closed'], click: mkSelfToggler() },
[
h('table', { cls: 'help', click: stopProp }, [
row(['⬆️ Move up:', h('div', [h('kbd', 'W'), '/', h('kbd', '↑'), '/🖱️'])]),
row(['⬇️ Move down:', h('div', [h('kbd', 'S'), '/', h('kbd', '↓'), '/🖱️'])]),
row(['⬅️ Move left:', h('div', [h('kbd', 'A'), '/', h('kbd', '←'), '/🖱️'])]),
row(['➡️ Move right:', h('div', [h('kbd', 'D'), '/', h('kbd', '→'), '/🖱️'])]),
row(['', h('div', ['Move faster by holding ', h('kbd', 'Shift')])]),
row(['🔍+ Zoom in:', h('div', [h('kbd', 'E'), '/🖱️-Wheel'])]),
row(['🔍- Zoom out:', h('div', [h('kbd', 'Q'), '/🖱️-Wheel'])]),
row(['🖼️ Toggle preview:', h('div', [h('kbd', 'Space')])]),
row(['🧩✔️ Toggle fixed pieces:', h('div', [h('kbd', 'F')])]),
row(['🧩❓ Toggle loose pieces:', h('div', [h('kbd', 'G')])]),
]),
]
)
const settingsOverlay = h(
'div',
{ cls: ['overlay', 'transparent', 'closed'], click: mkSelfToggler() },
[
h('table', { cls: 'settings', click: stopProp }, [
row([h('label', 'Background: '), bgColorPickerEl]),
row([h('label', 'Color: '), playerColorPickerEl]),
row([h('label', 'Name: '), nameChangeEl]),
]),
]
)
const previewOverlay = h(
'div',
{ cls: ['overlay', 'closed'], click: mkSelfToggler() },
[
h('div', { cls: 'preview' }, [
h('div', { cls: 'img', style: { backgroundImage: `url('${previewImageUrl}')` } })
])
]
)
const scoresListEl = h('table')
const updateScoreBoard = (players, ts) => {
const minTs = ts - 30 * Time.SEC
const actives = players.filter(player => player.ts >= minTs)
const nonActives = players.filter(player => player.ts < minTs)
actives.sort((a, b) => b.points - a.points)
nonActives.sort((a, b) => b.points - a.points)
const _row = (icon, player) => row(
{ style: { color: player.color} },
[icon, player.name, player.points]
)
scoresListEl.innerHTML = ''
actives.forEach(player => scoresListEl.appendChild(_row('⚡', player)))
nonActives.forEach(player => scoresListEl.appendChild(_row('💤', player)))
}
const timerCountdownEl = h('div')
const updateTimer = (from, ended, ts) => {
const icon = ended ? '🏁' : '⏳'
const timeDiffStr = Time.timeDiffStr(from, ended || ts)
timerCountdownEl.innerText = `${icon} ${timeDiffStr}`
}
const tilesDoneEl = h('div')
const udateTilesDone = (finished, total) => {
tilesDoneEl.innerText = `🧩 ${finished}/${total}`
}
const timerEl = h('div', { cls: 'timer' }, [tilesDoneEl, timerCountdownEl])
let replayControl = null
if (MODE === MODE_REPLAY) {
const speedUp = h('button', { cls: 'btn' }, ['⏫'])
const speedDown = h('button', { cls: 'btn' }, ['⏬'])
const pause = h('button', { cls: 'btn' }, ['⏸️'])
const speed = h('div')
timerEl.appendChild(h('div', [ speed, speedUp, speedDown, pause ]))
replayControl = { speedUp, speedDown, pause, speed }
}
TARGET_EL.appendChild(settingsOverlay)
TARGET_EL.appendChild(previewOverlay)
TARGET_EL.appendChild(helpOverlay)
TARGET_EL.appendChild(timerEl)
TARGET_EL.appendChild(h('div', { cls: 'menu' }, [
h('div', { cls: 'tabs' }, [
h('a', { cls: 'opener', target: '_blank', href: '/' }, '🧩 Puzzles'),
h('div', { cls: 'opener', click: mkToggler(previewOverlay, false) }, '🖼️ Preview'),
h('div', { cls: 'opener', click: mkToggler(settingsOverlay) }, '🛠️ Settings'),
h('div', { cls: 'opener', click: mkToggler(helpOverlay) }, ' Help'),
])
]))
TARGET_EL.appendChild(h('div', { cls: 'scores' }, [
h('div', 'Scores'),
scoresListEl,
]))
return {
bgColorPickerEl,
playerColorPickerEl,
nameChangeEl,
updateScoreBoard,
updateTimer,
udateTilesDone,
togglePreview: () => toggle(previewOverlay, false),
replayControl,
}
}
function initme() {
let ID = localStorage.getItem('ID')
if (!ID) {
@ -359,14 +175,13 @@ function EventAdapter (canvas, window, viewport) {
}
}
async function main(TARGET_EL) {
if (typeof GAME_ID === 'undefined') throw '[ GAME_ID not set ]'
if (typeof WS_ADDRESS === 'undefined') throw '[ WS_ADDRESS not set ]'
export async function main(gameId, wsAddress, MODE, TARGET_EL, HUD) {
if (typeof gameId === 'undefined') throw '[ gameId not set ]'
if (typeof wsAddress === 'undefined') throw '[ wsAddress not set ]'
if (typeof MODE === 'undefined') throw '[ MODE not set ]'
if (typeof DEBUG === 'undefined') window.DEBUG = false
const gameId = GAME_ID
const CLIENT_ID = initme()
const shouldDrawPlayerText = (player) => {
return MODE === MODE_REPLAY || player.id !== CLIENT_ID
@ -412,12 +227,12 @@ async function main(TARGET_EL) {
let TIME
if (MODE === MODE_PLAY) {
const game = await Communication.connect(gameId, CLIENT_ID)
const game = await Communication.connect(wsAddress, gameId, CLIENT_ID)
const gameObject = Util.decodeGame(game)
Game.setGame(gameObject.id, gameObject)
TIME = () => Time.timestamp()
} else if (MODE === MODE_REPLAY) {
const {game, log} = await Communication.connectReplay(gameId, CLIENT_ID)
const {game, log} = await Communication.connectReplay(wsAddress, gameId, CLIENT_ID)
const gameObject = Util.decodeGame(game)
Game.setGame(gameObject.id, gameObject)
REPLAY.log = log
@ -468,25 +283,33 @@ async function main(TARGET_EL) {
const evts = new EventAdapter(canvas, window, viewport)
const {
bgColorPickerEl,
playerColorPickerEl,
nameChangeEl,
updateScoreBoard,
updateTimer,
udateTilesDone,
togglePreview,
replayControl,
} = addMenuToDom(TARGET_EL, Game.getImageUrl(gameId), evts.setHotkeys)
const previewImageUrl = Game.getImageUrl(gameId)
const activePlayers = (gameId, ts) => {
const minTs = ts - 30 * Time.SEC
const players = Game.getRelevantPlayers(gameId, ts)
return players.filter(player => player.ts >= minTs)
}
const idlePlayers = (gameId, ts) => {
const minTs = ts - 30 * Time.SEC
const players = Game.getRelevantPlayers(gameId, ts)
return players.filter(player => player.ts < minTs)
}
const updateTimerElements = () => {
updateTimer(Game.getStartTs(gameId), Game.getFinishTs(gameId), TIME())
const startTs = Game.getStartTs(gameId)
const finishTs = Game.getFinishTs(gameId)
const ts = TIME()
HUD.setFinished(!!(finishTs))
HUD.setDuration((finishTs || ts) - startTs)
}
updateTimerElements()
udateTilesDone(Game.getFinishedTileCount(gameId), Game.getTileCount(gameId))
HUD.setPiecesDone(Game.getFinishedTileCount(gameId))
HUD.setPiecesTotal(Game.getTileCount(gameId))
const ts = TIME()
updateScoreBoard(Game.getRelevantPlayers(gameId, ts), ts)
HUD.setActivePlayers(activePlayers(gameId, ts))
HUD.setIdlePlayers(idlePlayers(gameId, ts))
const longFinished = !! Game.getFinishTs(gameId)
let finished = longFinished
@ -508,49 +331,45 @@ async function main(TARGET_EL) {
|| 'anon')
}
const onBgChange = (value) => {
localStorage.setItem('bg_color', value)
evts.addEvent([Protocol.INPUT_EV_BG_COLOR, value])
}
const onColorChange = (value) => {
localStorage.setItem('player_color', value)
evts.addEvent([Protocol.INPUT_EV_PLAYER_COLOR, value])
}
const onNameChange = (value) => {
localStorage.setItem('player_name', value)
evts.addEvent([Protocol.INPUT_EV_PLAYER_NAME, value])
}
const doSetSpeedStatus = () => {
HUD.setReplaySpeed(REPLAY.speeds[REPLAY.speedIdx])
HUD.setReplayPaused(REPLAY.paused)
}
const replayOnSpeedUp = () => {
if (REPLAY.speedIdx + 1 < REPLAY.speeds.length) {
REPLAY.speedIdx++
doSetSpeedStatus()
}
}
const replayOnSpeedDown = () => {
if (REPLAY.speedIdx >= 1) {
REPLAY.speedIdx--
doSetSpeedStatus()
}
}
const replayOnPauseToggle = () => {
REPLAY.paused = !REPLAY.paused
doSetSpeedStatus()
}
if (MODE === MODE_PLAY) {
bgColorPickerEl.value = playerBgColor()
evts.addEvent([Protocol.INPUT_EV_BG_COLOR, bgColorPickerEl.value])
bgColorPickerEl.addEventListener('change', () => {
localStorage.setItem('bg_color', bgColorPickerEl.value)
evts.addEvent([Protocol.INPUT_EV_BG_COLOR, bgColorPickerEl.value])
})
playerColorPickerEl.value = playerColor()
evts.addEvent([Protocol.INPUT_EV_PLAYER_COLOR, playerColorPickerEl.value])
playerColorPickerEl.addEventListener('change', () => {
localStorage.setItem('player_color', playerColorPickerEl.value)
evts.addEvent([Protocol.INPUT_EV_PLAYER_COLOR, playerColorPickerEl.value])
})
nameChangeEl.value = playerName()
evts.addEvent([Protocol.INPUT_EV_PLAYER_NAME, nameChangeEl.value])
nameChangeEl.addEventListener('change', () => {
localStorage.setItem('player_name', nameChangeEl.value)
evts.addEvent([Protocol.INPUT_EV_PLAYER_NAME, nameChangeEl.value])
})
setInterval(updateTimerElements, 1000)
} else if (MODE === MODE_REPLAY) {
const setSpeedStatus = () => {
replayControl.speed.innerText = 'Replay-Speed: ' +
(REPLAY.speeds[REPLAY.speedIdx] + 'x') +
(REPLAY.paused ? ' Paused' : '')
}
setSpeedStatus()
replayControl.speedUp.addEventListener('click', () => {
if (REPLAY.speedIdx + 1 < REPLAY.speeds.length) {
REPLAY.speedIdx++
setSpeedStatus()
}
})
replayControl.speedDown.addEventListener('click', () => {
if (REPLAY.speedIdx >= 1) {
REPLAY.speedIdx--
setSpeedStatus()
}
})
replayControl.pause.addEventListener('click', () => {
REPLAY.paused = !REPLAY.paused
setSpeedStatus()
})
doSetSpeedStatus()
}
if (MODE === MODE_PLAY) {
@ -678,7 +497,7 @@ async function main(TARGET_EL) {
Game.changePlayer(gameId, CLIENT_ID, pos)
}
} else if (type === Protocol.INPUT_EV_TOGGLE_PREVIEW) {
togglePreview()
HUD.togglePreview()
}
// LOCAL + SERVER CHANGES
@ -726,7 +545,7 @@ async function main(TARGET_EL) {
RERENDER = true
}
} else if (type === Protocol.INPUT_EV_TOGGLE_PREVIEW) {
togglePreview()
HUD.togglePreview()
}
}
}
@ -818,11 +637,12 @@ async function main(TARGET_EL) {
if (DEBUG) Debug.checkpoint('players done')
// DRAW PLAYERS
// propagate HUD changes
// ---------------------------------------------------------------
updateScoreBoard(Game.getRelevantPlayers(gameId, ts), ts)
udateTilesDone(Game.getFinishedTileCount(gameId), Game.getTileCount(gameId))
if (DEBUG) Debug.checkpoint('scores done')
HUD.setActivePlayers(activePlayers(gameId, ts))
HUD.setIdlePlayers(idlePlayers(gameId, ts))
HUD.setPiecesDone(Game.getFinishedTileCount(gameId))
if (DEBUG) Debug.checkpoint('HUD done')
// ---------------------------------------------------------------
if (justFinished()) {
@ -836,6 +656,23 @@ async function main(TARGET_EL) {
update: onUpdate,
render: onRender,
})
}
export default main
return {
setHotkeys: (state) => {
evts.setHotkeys(state)
},
onBgChange,
onColorChange,
onNameChange,
replayOnSpeedUp,
replayOnSpeedDown,
replayOnPauseToggle,
previewImageUrl,
player: {
background: playerBgColor(),
color: playerColor(),
name: playerName(),
},
disconnect: Communication.disconnect,
}
}

View file

@ -14,19 +14,32 @@
import Game from "/views/Game.vue.js"
import Replay from "/views/Replay.vue.js"
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{ name: 'index', path: '/', component: Index },
{ name: 'new-game', path: '/new-game', component: NewGame },
{ name: 'game', path: '/g/:id', component: Game },
{ name: 'replay', path: '/replay/:id', component: Replay },
],
})
(async () => {
const res = await fetch(`/api/conf`)
const conf = await res.json()
const app = Vue.createApp(App)
app.use(router)
app.mount('#app')
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{ name: 'index', path: '/', component: Index },
{ name: 'new-game', path: '/new-game', component: NewGame },
{ name: 'game', path: '/g/:id', component: Game },
{ name: 'replay', path: '/replay/:id', component: Replay },
],
})
router.beforeEach((to, from) => {
if (from.name !== undefined) {
document.documentElement.classList.remove(`view-${from.name}`)
}
document.documentElement.classList.add(`view-${to.name}`)
})
const app = Vue.createApp(App)
app.config.globalProperties.$config = conf
app.use(router)
app.mount('#app')
})()
</script>
</body>
</html>

View file

@ -278,3 +278,10 @@ kbd {
top: 0;
right: 0;
}
html.view-game { overflow: hidden; }
html.view-game body { overflow: hidden; }
html.view-replay { overflow: hidden; }
html.view-replay body { overflow: hidden; }
html.view-replay canvas { cursor: grab; }

View file

@ -1,33 +1,118 @@
"use strict"
import main from './../game.js'
import Scores from './../components/Scores.vue.js'
import PuzzleStatus from './../components/PuzzleStatus.vue.js'
import SettingsOverlay from './../components/SettingsOverlay.vue.js'
import PreviewOverlay from './../components/PreviewOverlay.vue.js'
import HelpOverlay from './../components/HelpOverlay.vue.js'
import { main, MODE_PLAY } from './../game.js'
export default {
name: 'game',
template: `<div>{{gameData}}</div>`,
components: {
PuzzleStatus,
Scores,
SettingsOverlay,
PreviewOverlay,
HelpOverlay,
},
template: `<div id="game">
<settings-overlay v-show="overlay === 'settings'" @bgclick="toggle('settings', true)" v-model="g.player" />
<preview-overlay v-show="overlay === 'preview'" @bgclick="toggle('preview', false)" :img="g.previewImageUrl" />
<help-overlay v-show="overlay === 'help'" @bgclick="toggle('help', true)" />
<puzzle-status
:finished="finished"
:duration="duration"
:piecesDone="piecesDone"
:piecesTotal="piecesTotal"
/>
<div class="menu">
<div class="tabs">
<router-link class="opener" :to="{name: 'index'}" target="_blank">🧩 Puzzles</router-link>
<div class="opener" @click="toggle('preview', false)">🖼 Preview</div>
<div class="opener" @click="toggle('settings', true)">🛠 Settings</div>
<div class="opener" @click="toggle('help', true)"> Help</div>
</div>
</div>
<scores :activePlayers="activePlayers" :idlePlayers="idlePlayers" />
</div>`,
data() {
return {
gameData: null,
activePlayers: [],
idlePlayers: [],
finished: false,
duration: 0,
piecesDone: 0,
piecesTotal: 0,
overlay: null,
g: {
player: {
background: '',
color: '',
name: '',
},
previewImageUrl: '',
setHotkeys: () => {},
onBgChange: () => {},
onColorChange: () => {},
onNameChange: () => {},
disconnect: () => {},
},
}
},
created() {
this.$watch(
() => this.$route.params,
() => { this.fetchData() },
{ immediate: true }
async mounted() {
if (!this.$route.params.id) {
return
}
this.$watch(() => this.g.player.background, (value) => {
this.g.onBgChange(value)
})
this.$watch(() => this.g.player.color, (value) => {
this.g.onColorChange(value)
})
this.$watch(() => this.g.player.name, (value) => {
this.g.onNameChange(value)
})
this.g = await main(
this.$route.params.id,
this.$config.WS_ADDRESS,
MODE_PLAY,
this.$el,
{
setActivePlayers: (v) => { this.activePlayers = v },
setIdlePlayers: (v) => { this.idlePlayers = v },
setFinished: (v) => { this.finished = v },
setDuration: (v) => { this.duration = v },
setPiecesDone: (v) => { this.piecesDone = v },
setPiecesTotal: (v) => { this.piecesTotal = v },
togglePreview: () => { this.toggle('preview', false) },
}
)
},
unmounted () {
this.g.disconnect()
},
methods: {
async fetchData() {
this.gameData = null
const res = await fetch(`/api/game-data/${this.$route.params.id}`)
const json = await res.json()
this.gameData = json
window.GAME_ID = this.gameData.GAME_ID
window.WS_ADDRESS = this.gameData.WS_ADDRESS
window.MODE = 'play'
main(this.$el)
toggle(overlay, affectsHotkeys) {
if (this.overlay === null) {
this.overlay = overlay
if (affectsHotkeys) {
this.g.setHotkeys(false)
}
} else {
// could check if overlay was the provided one
this.overlay = null
if (affectsHotkeys) {
this.g.setHotkeys(true)
}
}
},
},
}

View file

@ -1,33 +1,142 @@
"use strict"
import main from './../game.js'
import Scores from './../components/Scores.vue.js'
import PuzzleStatus from './../components/PuzzleStatus.vue.js'
import SettingsOverlay from './../components/SettingsOverlay.vue.js'
import PreviewOverlay from './../components/PreviewOverlay.vue.js'
import HelpOverlay from './../components/HelpOverlay.vue.js'
import { main, MODE_REPLAY } from './../game.js'
export default {
name: 'replay',
template: `<div>{{replayData}}</div>`,
components: {
PuzzleStatus,
Scores,
SettingsOverlay,
PreviewOverlay,
HelpOverlay,
},
template: `<div id="replay">
<settings-overlay v-show="overlay === 'settings'" @bgclick="toggle('settings', true)" v-model="g.player" />
<preview-overlay v-show="overlay === 'preview'" @bgclick="toggle('preview', false)" :img="g.previewImageUrl" />
<help-overlay v-show="overlay === 'help'" @bgclick="toggle('help', true)" />
<puzzle-status
:finished="finished"
:duration="duration"
:piecesDone="piecesDone"
:piecesTotal="piecesTotal"
>
<div>
<div>{{replayText}}</div>
<button class="btn" @click="g.replayOnSpeedUp()"></button>
<button class="btn" @click="g.replayOnSpeedDown()"></button>
<button class="btn" @click="g.replayOnPauseToggle()"></button>
</div>
</puzzle-status>
<div class="menu">
<div class="tabs">
<router-link class="opener" :to="{name: 'index'}" target="_blank">🧩 Puzzles</router-link>
<div class="opener" @click="toggle('preview', false)">🖼 Preview</div>
<div class="opener" @click="toggle('settings', true)">🛠 Settings</div>
<div class="opener" @click="toggle('help', true)"> Help</div>
</div>
</div>
<scores :activePlayers="activePlayers" :idlePlayers="idlePlayers" />
</div>`,
data() {
return {
replayData: null,
activePlayers: [],
idlePlayers: [],
finished: false,
duration: 0,
piecesDone: 0,
piecesTotal: 0,
overlay: null,
g: {
player: {
background: '',
color: '',
name: '',
},
previewImageUrl: '',
setHotkeys: () => {},
onBgChange: () => {},
onColorChange: () => {},
onNameChange: () => {},
replayOnSpeedUp: () => {},
replayOnSpeedDown: () => {},
replayOnPauseToggle: () => {},
disconnect: () => {},
},
replay: {
speed: 1,
paused: false,
},
}
},
created() {
this.$watch(
() => this.$route.params,
() => { this.fetchData() },
{ immediate: true }
async mounted() {
if (!this.$route.params.id) {
return
}
this.$watch(() => this.g.player.background, (value) => {
this.g.onBgChange(value)
})
this.$watch(() => this.g.player.color, (value) => {
this.g.onColorChange(value)
})
this.$watch(() => this.g.player.name, (value) => {
this.g.onNameChange(value)
})
this.g = await main(
this.$route.params.id,
this.$config.WS_ADDRESS,
MODE_REPLAY,
this.$el,
{
setActivePlayers: (v) => { this.activePlayers = v },
setIdlePlayers: (v) => { this.idlePlayers = v },
setFinished: (v) => { this.finished = v },
setDuration: (v) => { this.duration = v },
setPiecesDone: (v) => { this.piecesDone = v },
setPiecesTotal: (v) => { this.piecesTotal = v },
togglePreview: () => { this.toggle('preview', false) },
setReplaySpeed: (v) => { this.replay.speed = v },
setReplayPaused: (v) => { this.replay.paused = v },
}
)
},
unmounted () {
this.g.disconnect()
},
computed: {
replayText () {
return 'Replay-Speed: ' +
(this.replay.speed + 'x') +
(this.replay.paused ? ' Paused' : '')
},
},
methods: {
async fetchData() {
this.replayData = null
const res = await fetch(`/api/replay-data/${this.$route.params.id}`)
const json = await res.json()
this.replayData = json
window.GAME_ID = this.gameData.GAME_ID
window.WS_ADDRESS = this.gameData.WS_ADDRESS
window.MODE = 'replay'
main(this.$el)
toggle(overlay, affectsHotkeys) {
if (this.overlay === null) {
this.overlay = overlay
if (affectsHotkeys) {
this.g.setHotkeys(false)
}
} else {
// could check if overlay was the provided one
this.overlay = null
if (affectsHotkeys) {
this.g.setHotkeys(true)
}
}
},
},
}