add Time, reducing some duplication

This commit is contained in:
Zutatensuppe 2021-04-14 19:30:45 +02:00
parent e737015d7e
commit b6999e4f1f
7 changed files with 70 additions and 85 deletions

View file

@ -1,5 +1,6 @@
import Geometry from './Geometry.js'
import Protocol from './Protocol.js'
import Time from './Time.js'
import Util from './Util.js'
// Map<gameId, GameObject>
@ -89,14 +90,14 @@ function playerExists(gameId, playerId) {
}
function getRelevantPlayers(gameId, ts) {
const minTs = ts - 30000
const minTs = ts - 30 * Time.SEC
return getAllPlayers(gameId).filter(player => {
return player.ts >= minTs || player.points > 0
})
}
function getActivePlayers(gameId, ts) {
const minTs = ts - 30000
const minTs = ts - 30 * Time.SEC
return getAllPlayers(gameId).filter(player => {
return player.ts >= minTs
})

45
common/Time.js Normal file
View file

@ -0,0 +1,45 @@
const MS = 1
const SEC = MS * 1000
const MIN = SEC * 60
const HOUR = MIN * 60
const DAY = HOUR * 24
export const timestamp = () => {
const d = new Date();
return Date.UTC(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds(),
d.getUTCMilliseconds(),
)
}
export const timeDiffStr = (from, to) => {
let diff = to - from
const d = Math.floor(diff / DAY)
diff = diff % DAY
const h = Math.floor(diff / HOUR)
diff = diff % HOUR
const m = Math.floor(diff / MIN)
diff = diff % MIN
const s = Math.floor(diff / SEC)
return `${d}d ${h}h ${m}m ${s}s`
}
export default {
MS,
SEC,
MIN,
HOUR,
DAY,
timestamp,
timeDiffStr,
}

View file

@ -69,19 +69,6 @@ export const shuffle = (
return arr
}
export const timestamp = () => {
const d = new Date();
return Date.UTC(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds(),
d.getUTCMilliseconds(),
)
}
function encodeShape(data) {
if (typeof data === 'number') {
return data
@ -224,7 +211,6 @@ export default {
choice,
throttle,
shuffle,
timestamp,
encodeShape,
decodeShape,

View file

@ -1,3 +1,5 @@
import Time from '../common/Time.js'
/**
* Wrapper around ws that
* - buffers 'send' until a connection is available
@ -48,12 +50,12 @@ export default class WsWrapper {
}
ws.onerror = (e) => {
this.handle = null
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1000)
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1 * Time.SEC)
this.onclose(e)
}
ws.onclose = (e) => {
this.handle = null
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1000)
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1 * Time.SEC)
this.onclose(e)
}
}

View file

@ -9,6 +9,7 @@ import PuzzleGraphics from './PuzzleGraphics.js'
import Game from './Game.js'
import fireworksController from './Fireworks.js'
import Protocol from '../common/Protocol.js'
import Time from '../common/Time.js'
if (typeof GAME_ID === 'undefined') throw '[ GAME_ID not set ]'
if (typeof WS_ADDRESS === 'undefined') throw '[ WS_ADDRESS not set ]'
@ -18,7 +19,7 @@ if (typeof DEBUG === 'undefined') window.DEBUG = false
let RERENDER = true
let TIME = () => Util.timestamp()
let TIME = () => Time.timestamp()
function addCanvasToDom(canvas) {
canvas.width = window.innerWidth
@ -154,7 +155,7 @@ function addMenuToDom(gameId) {
const scoresListEl = document.createElement('table')
const updateScores = () => {
const ts = TIME()
const minTs = ts - 30000
const minTs = ts - 30 * Time.SEC
const players = Game.getRelevantPlayers(gameId, ts)
const actives = players.filter(player => player.ts >= minTs)
@ -187,31 +188,11 @@ function addMenuToDom(gameId) {
const timerStr = () => {
const started = Game.getStartTs(gameId)
const ended = Game.getFinishTs(gameId)
const icon = ended ? '🏁' : '⏳'
const from = started;
const to = ended || TIME()
const MS = 1
const SEC = MS * 1000
const MIN = SEC * 60
const HOUR = MIN * 60
const DAY = HOUR * 24
let diff = to - from
const d = Math.floor(diff / DAY)
diff = diff % DAY
const h = Math.floor(diff / HOUR)
diff = diff % HOUR
const m = Math.floor(diff / MIN)
diff = diff % MIN
const s = Math.floor(diff / SEC)
return `${icon} ${d}d ${h}h ${m}m ${s}s`
const timeDiffStr = Time.timeDiffStr(from, to)
return `${icon} ${timeDiffStr}`
}
const timerCountdownEl = document.createElement('div')
@ -372,7 +353,7 @@ async function main() {
const {game, log} = await Communication.connectReplay(gameId, CLIENT_ID)
Game.newGame(Util.decodeGame(game))
GAME_LOG = log
lastRealTime = Util.timestamp()
lastRealTime = Time.timestamp()
GAME_START_TS = GAME_LOG[0][GAME_LOG[0].length - 1]
lastGameTime = GAME_START_TS
TIME = () => lastGameTime
@ -440,7 +421,7 @@ async function main() {
evts.addEvent([Protocol.INPUT_EV_PLAYER_NAME, nameChangeEl.value])
})
} else if (MODE === 'replay') {
let setSpeedStatus = () => {
const setSpeedStatus = () => {
replayControl.speed.innerText = 'Replay-Speed: ' + (REPLAY_SPEEDS[REPLAY_SPEED_IDX] + 'x') + (REPLAY_PAUSED ? ' Paused' : '')
}
setSpeedStatus()
@ -494,7 +475,7 @@ async function main() {
// no external communication for replay mode,
// only the GAME_LOG is relevant
let inter = setInterval(() => {
let realTime = Util.timestamp()
let realTime = Time.timestamp()
if (REPLAY_PAUSED) {
lastRealTime = realTime
return

View file

@ -1,3 +1,5 @@
import Time from '../common/Time.js'
const Upload = {
name: 'upload',
props: {
@ -26,20 +28,6 @@ const Upload = {
}
}
export const timestamp = () => {
const d = new Date();
return Date.UTC(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds(),
d.getUTCMilliseconds(),
)
}
export default {
components: {
Upload,
@ -104,29 +92,10 @@ export default {
methods: {
time(start, end) {
const icon = end ? '🏁' : '⏳'
const from = start;
const to = end || timestamp()
const MS = 1
const SEC = MS * 1000
const MIN = SEC * 60
const HOUR = MIN * 60
const DAY = HOUR * 24
let diff = to - from
const d = Math.floor(diff / DAY)
diff = diff % DAY
const h = Math.floor(diff / HOUR)
diff = diff % HOUR
const m = Math.floor(diff / MIN)
diff = diff % MIN
const s = Math.floor(diff / SEC)
return `${icon} ${d}d ${h}h ${m}m ${s}s`
const to = end || Time.timestamp()
const timeDiffStr = Time.timeDiffStr(from, to)
return `${icon} ${timeDiffStr}`
},
mediaImgUploaded(j) {
this.image = j.image

View file

@ -12,6 +12,7 @@ import bodyParser from 'body-parser'
import v8 from 'v8'
import GameLog from './GameLog.js'
import GameSockets from './GameSockets.js'
import Time from '../common/Time.js'
const log = logger('index.js')
@ -80,7 +81,7 @@ app.post('/newgame', bodyParser.json(), async (req, res) => {
log.log(req.body.tiles, req.body.image)
const gameId = Util.uniqId()
if (!Game.exists(gameId)) {
const ts = Util.timestamp()
const ts = Time.timestamp()
await Game.createGame(gameId, req.body.tiles, req.body.image, ts)
}
res.send({ url: `/g/${gameId}` })
@ -90,7 +91,7 @@ app.use('/common/', express.static('./../common/'))
app.use('/uploads/', express.static('./../data/uploads/'))
app.use('/', async (req, res, next) => {
if (req.path === '/') {
const ts = Util.timestamp()
const ts = Time.timestamp()
const games = [
...Game.getAllGames().map(game => ({
id: game.id,
@ -162,7 +163,7 @@ wss.on('message', async ({socket, data}) => {
if (!Game.exists(gameId)) {
throw `[game ${gameId} does not exist... ]`
}
const ts = Util.timestamp()
const ts = Time.timestamp()
Game.addPlayer(gameId, clientId, ts)
GameSockets.addSocket(gameId, socket)
const game = Game.get(gameId)
@ -178,7 +179,7 @@ wss.on('message', async ({socket, data}) => {
}
const clientSeq = msg[1]
const clientEvtData = msg[2]
const ts = Util.timestamp()
const ts = Time.timestamp()
let sendGame = false
if (!Game.playerExists(gameId, clientId)) {