From 3da4809e277c2c378506766af5d381bfdd305f09 Mon Sep 17 00:00:00 2001 From: adbenitez Date: Mon, 13 Jun 2022 05:48:38 -0400 Subject: [PATCH] first commit --- .gitignore | 11 ++++ LICENSE | 21 +++++++ README.md | 27 +++++++++ index.html | 62 ++++++++++++++++++++ jszip.config.json | 18 ++++++ manifest.toml | 2 + package.json | 13 +++++ webxdc-scores.css | 30 ++++++++++ webxdc-scores.d.ts | 59 +++++++++++++++++++ webxdc-scores.js | 139 +++++++++++++++++++++++++++++++++++++++++++++ webxdc.js | 114 +++++++++++++++++++++++++++++++++++++ 11 files changed, 496 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 index.html create mode 100644 jszip.config.json create mode 100644 manifest.toml create mode 100644 package.json create mode 100644 webxdc-scores.css create mode 100644 webxdc-scores.d.ts create mode 100644 webxdc-scores.js create mode 100644 webxdc.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d9dea97 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +pnpm-debug.log* +pnpm-lock.yaml + +node_modules +dist + +# Editor directories and files +.vscode/* +.idea +.DS_Store +*~ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4d20996 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e4d9e7c --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# webxdc-scores + +An utility library to facilitate the process of creating score-based webxdc games. + +## Usage + +Copy the `webxdc-scores.js` file to your project's floder, then include it (together with `webxdc.js`) in your `index.html`: + +```html + + + + + + + + + ... + + +``` + +Then you will have an scores API via `window.webxdc_scores` object, check `webxdc-scores.d.ts` file for documentation of the available API. + +> **⚠️ NOTE:** If you use `window.webxdc_scores.getScoreboard()` you need to include `webxdc-scores.css` in your `index.html`, edit it to adapt the scoreboard style to your app. + +For a full example check the `index.html` file included in this repository. diff --git a/index.html b/index.html new file mode 100644 index 0000000..e58c1fb --- /dev/null +++ b/index.html @@ -0,0 +1,62 @@ + + + + + + + + + + + +

Score: 0

+

+ CLICK ME! +

+
+ + + diff --git a/jszip.config.json b/jszip.config.json new file mode 100644 index 0000000..e430835 --- /dev/null +++ b/jszip.config.json @@ -0,0 +1,18 @@ +{ + "compressionLevel": 9, + "dereferenceLinks": true, + "entries": [ + "dist/assets", + "dist/index.html", + "webxdc-scores.js", + "manifest.toml" + ], + "force": true, + "ignoreEntries": [ + "*.map" + ], + "mode": "add", + "outputEntry": "dist/app.xdc", + "quiet": false, + "verbose": false +} diff --git a/manifest.toml b/manifest.toml new file mode 100644 index 0000000..2fb21d5 --- /dev/null +++ b/manifest.toml @@ -0,0 +1,2 @@ +name = "Test Game" +source_code_url = "https://github.com/webxdc/webxdc-scores" \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..64d215f --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "private": true, + "packageManager": "pnpm@6.32.3", + "scripts": { + "dev": "vite --host --open", + "build": "vite build && jszip-cli -c jszip.config.json", + "preview": "vite preview" + }, + "devDependencies": { + "@ffflorian/jszip-cli": "^3.1.6", + "vite": "^2.9.9" + } +} diff --git a/webxdc-scores.css b/webxdc-scores.css new file mode 100644 index 0000000..a856daf --- /dev/null +++ b/webxdc-scores.css @@ -0,0 +1,30 @@ +.score-row { + font-size: 120%; + color: #000; + text-align: left; + padding: 1% 4%; + margin: 1% 6%; + border-radius: 0.3em; +} + +.score-row.you { + background: #eee; +} + +.row-pos { + float: left; + color: #4D4D4D; +} + +.row-score { + float: right; + display: inline-block; +} + +.row-name { + text-overflow: ellipsis; + display: inline-block; + width: 65%; + overflow: hidden; + white-space: nowrap; +} diff --git a/webxdc-scores.d.ts b/webxdc-scores.d.ts new file mode 100644 index 0000000..bf58697 --- /dev/null +++ b/webxdc-scores.d.ts @@ -0,0 +1,59 @@ +//@ts-check + +type Player = { + /** the player's name */ + name: string; + /** the player's position in the scoreboard */ + pos: string; + /** the player's high score */ + score: number; + /** true if this player is the current/self player, false otherwise. */ + current: boolean; +}; + +interface WebxdcScores { + /** + * Initialize the scores API. + * @param appName the app's name that will be shown in info-messages. + * @returns promise that resolves when the API is ready to be used. + */ + init(appName: string): Promise; + /** + * Use this method to get the high score of the current player. + * @returns the current player's high score. + */ + getScore(): number; + /** + * Use this method to set the high score of the current player. + * The new score is ignored if it is not greater than the player's high score and + * "force" is False. + * If the new score is not ignored, an info-message will be sent in the form: + * "PlayerName scored newScore in appName" + * @param score the new high score. + * @param force if the new score should override the old score even if it is smaller. + */ + setScore(score: number, force: boolean): void; + /** + * Use this method to get data for high score tables. + * This method will return scores for the current player, plus their closest + * neighbors on each side. Will also return the top three players if the current + * player and their neighbors are not among them. + * @returns an array of Player objects. + */ + getHighScores(): Player[]; + /** + * Use this method to get the HTML markup of the scoreboard. + * @returns an string containing the HTML markup of the scoreboard. + */ + getScoreboard(): string; +} + +////////// ANCHOR: global +declare global { + interface Window { + webxdc_scores: WebxdcScores; + } +} +////////// ANCHOR_END: global + +export { WebxdcScores }; diff --git a/webxdc-scores.js b/webxdc-scores.js new file mode 100644 index 0000000..a4be87a --- /dev/null +++ b/webxdc-scores.js @@ -0,0 +1,139 @@ +window.webxdc_scores = (() => { + let players = [], + _appName = ""; + + function h(tag, attributes, ...children) { + const element = document.createElement(tag); + if (attributes) { + Object.entries(attributes).forEach(entry => { + element.setAttribute(entry[0], entry[1]); + }); + } + element.append(...children); + return element; + } + + function getScore(addr) { + return players[addr] ? players[addr].score : 0; + } + + function getHighScores() { + const selfAddr = window.webxdc.selfAddr; + const scoreboard = Object.keys(players).map((addr) => { + return { + current: addr === selfAddr, + ...players[addr], + }; + }).sort((a, b) => b.score - a.score); + + const top = []; + const neighbors = []; + let selfIndex = -1; + for (let i = 0; i < scoreboard.length; i++) { + if (scoreboard[i].current) { + selfIndex = i; + break; + } + } + if (selfIndex === -1 || selfIndex < 4) { + for (let i = 0; i < scoreboard.length; i++) { + if (i > 4) { + break; + } + const player = scoreboard[i]; + player.pos = i + 1; + top[i] = player; + } + } else { + let i = 0; + let player; + if (selfIndex - 1 >= 0) { + player = scoreboard[selfIndex - 1]; + player.pos = selfIndex; + neighbors[i++] = player; + } + + player = scoreboard[selfIndex]; + player.pos = selfIndex + 1; + neighbors[i++] = player; + + if (selfIndex + 1 < scoreboard.length) { + player = scoreboard[selfIndex + 1]; + player.pos = selfIndex + 2; + neighbors[i] = player; + } + + for (let i = 0; i < neighbors[0].pos - 1; i++) { + if (i > 2) { + break; + } + const player = scoreboard[i]; + player.pos = i + 1; + top[i] = player; + } + } + + return top.concat(neighbors); + } + + return { + init: (appName) => { + _appName = appName; + return window.webxdc.setUpdateListener((update) => { + const player = update.payload; + if (player.score > getScore(player.addr)) { + players[player.addr] = {name: player.name, score: player.score}; + } + }, 0); + }, + + getScore: () => { + return getScore(window.webxdc.selfAddr); + }, + + setScore: (score, force) => { + const addr = window.webxdc.selfAddr; + const old_score = getScore(addr); + if (score > old_score) { + const name = window.webxdc.selfName; + let info = name + " scored " + score; + if (_appName) { + info += " in " + _appName; + } + window.webxdc.sendUpdate( + { + payload: { + addr: addr, + name: name, + score: score, + }, + info: info, + }, + info + ); + } else { + console.log("[webxdc-score] Ignoring score: " + score + " < " + old_score); + } + }, + + getHighScores: getHighScores, + + getScoreboard: () => { + let table = getHighScores(); + let div = h("div"); + for (let i = 0; i < table.length; i++) { + const player = table[i]; + const pos = h("span", {class: "row-pos"}, player.pos); + pos.innerHTML += ".  "; + div.appendChild( + h("div", {class: "score-row" + (player.current ? " you" : "")}, + pos, + h("span", {class: "row-name"}, player.name), + h("span", {class: "row-score"}, player.score), + ) + ); + } + return div.innerHTML; + }, + }; +})(); diff --git a/webxdc.js b/webxdc.js new file mode 100644 index 0000000..f5f76f9 --- /dev/null +++ b/webxdc.js @@ -0,0 +1,114 @@ +// debug friend: document.writeln(JSON.stringify(value)); +//@ts-check +/** @type {import('./webxdc').Webxdc} */ +window.webxdc = (() => { + var updateListener = (_) => {}; + var updatesKey = "__xdcUpdatesKey__"; + window.addEventListener('storage', (event) => { + if (event.key == null) { + window.location.reload(); + } else if (event.key === updatesKey) { + var updates = JSON.parse(event.newValue); + var update = updates[updates.length-1]; + update.max_serial = updates.length; + console.log("[Webxdc] " + JSON.stringify(update)); + updateListener(update); + } + }); + + function getUpdates() { + var updatesJSON = window.localStorage.getItem(updatesKey); + return updatesJSON ? JSON.parse(updatesJSON) : []; + } + + var params = new URLSearchParams(window.location.hash.substr(1)); + return { + selfAddr: params.get("addr") || "device0@local.host", + selfName: params.get("name") || "device0", + setUpdateListener: (cb, serial = 0) => { + var updates = getUpdates(); + var maxSerial = updates.length; + updates.forEach((update) => { + if (update.serial > serial) { + update.max_serial = maxSerial; + cb(update); + } + }); + updateListener = cb; + return Promise.resolve() + }, + getAllUpdates: () => { + console.log('[Webxdc] WARNING: getAllUpdates() is deprecated.'); + return Promise.resolve([]); + }, + sendUpdate: (update, description) => { + var updates = getUpdates(); + var serial = updates.length + 1; + var _update = {payload: update.payload, summary: update.summary, info: update.info, serial: serial}; + updates.push(_update); + window.localStorage.setItem(updatesKey, JSON.stringify(updates)); + _update.max_serial = serial; + console.log('[Webxdc] description="' + description + '", ' + JSON.stringify(_update)); + updateListener(_update); + }, + }; +})(); + +window.addXdcPeer = () => { + var loc = window.location; + // get next peer ID + var params = new URLSearchParams(loc.hash.substr(1)); + var peerId = Number(params.get("next_peer")) || 1; + + // open a new window + var peerName = "device" + peerId; + var url = loc.protocol + "//" + loc.host + loc.pathname + "#name=" + peerName + "&addr=" + peerName + "@local.host"; + window.open(url); + + // update next peer ID + params.set("next_peer", String(peerId + 1)); + window.location.hash = "#" + params.toString(); +} + +window.clearXdcStorage = () => { + window.localStorage.clear(); + window.location.reload(); +} + +window.alterXdcApp = () => { + var styleControlPanel = 'position: fixed; bottom:1em; left:1em; background-color: #000; opacity:0.8; padding:.5em; font-size:16px; font-family: sans-serif; color:#fff; z-index: 9999'; + var styleMenuLink = 'color:#fff; text-decoration: none; vertical-align: middle'; + var styleAppIcon = 'height: 1.5em; width: 1.5em; margin-right: 0.5em; border-radius:10%; vertical-align: middle'; + var title = document.getElementsByTagName('title')[0]; + if (typeof title == 'undefined') { + title = document.createElement('title'); + document.getElementsByTagName('head')[0].append(title); + } + title.innerText = window.webxdc.selfAddr; + + if (window.webxdc.selfName === "device0") { + var div = document.createElement('div'); + div.innerHTML = + '
' + + 'Add Peer' + + ' | ' + + 'Clear Storage' + + '
'; + var controlPanel = div.firstChild; + + function loadIcon(name) { + var tester = new Image(); + tester.onload = () => { + div.innerHTML = ''; + controlPanel.insertBefore(div.firstChild, controlPanel.firstChild); + }; + tester.src = name; + } + loadIcon("icon.png"); + loadIcon("icon.jpg"); + + document.getElementsByTagName('body')[0].append(controlPanel); + } +} + +window.addEventListener("load", window.alterXdcApp);