commit 823b09e9444a4e79163d92128b8f597de7f84b19 Author: jwinterm Date: Sun Apr 27 09:03:16 2025 -0400 Initial AI commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..81bbc2b --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# Node.js dependencies +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Logs +logs/ +*.log +*.tlog +*.out +*.pid +*.gz + +# Environment variables +.env + +# Build files +dist/ +build/ + +# Temporary files +tmp/ +temp/ +*.tmp + +# IDE files +.vscode/ +.idea/ +*.swp +*.swo + +# OS generated files +.DS_Store +Thumbs.db diff --git a/dbcalls.js b/dbcalls.js new file mode 100644 index 0000000..07f4fe5 --- /dev/null +++ b/dbcalls.js @@ -0,0 +1,67 @@ +const { Client } = require('pg'); + +const client = new Client({ + user: 'postgres', + host: 'localhost', + database: 'bitdungeon', + password: 'postgres', + port: 5432, +}); +client.connect(); + +// Add this function to create the necessary table if it doesn't exist +function initializeDatabase() { + const createTableQuery = ` + CREATE TABLE IF NOT EXISTS visitors ( + id SERIAL PRIMARY KEY, + socketid VARCHAR(255) NOT NULL, + ip VARCHAR(100) NOT NULL, + time BIGINT NOT NULL + ) + `; + + client.query(createTableQuery) + .then(() => console.log("Database initialized")) + .catch(err => console.error("Database initialization error:", err)); +} + +// Call this function when starting up +initializeDatabase(); + +// String for inserting new visitor +const insertVisitorText = 'INSERT INTO visitors(socketid, ip, time) VALUES($1, $2, $3)'; +// Function for inserting new visitor and returning ID# +function insertVisitor(socketid, ip, cookie) { + values = [socketid, ip, Math.floor(new Date() / 1000)]; + + // First check if table exists to prevent errors + client.query("SELECT to_regclass('visitors')", (err, res) => { + if (err) { + console.error("Database check error:", err); + return; + } + + // If table doesn't exist yet, try to initialize again + if (res.rows[0].to_regclass === null) { + console.log("Table 'visitors' doesn't exist yet, creating it now..."); + initializeDatabase(); + return; + } + + // Insert the visitor + client.query(insertVisitorText, values, (err, res) => { + if (err) { + console.log(err.stack); + } else if (res.rows && res.rows[0]) { + console.log("Visitor inserted:", res.rows[0]); + } else { + console.log("Visitor inserted"); + } + }); + }); +} + + +module.exports = { + insertVisitor: insertVisitor +} diff --git a/game.js b/game.js new file mode 100644 index 0000000..c4c8432 --- /dev/null +++ b/game.js @@ -0,0 +1,186 @@ +const ROT = require('./rot.js'); + +// Define the missing generateDungeon function +function generateDungeon(width, height) { + // Create dungeon using ROT.js Map.Digger + const digger = new ROT.Map.Digger(width, height, { + roomWidth: [3, 9], + roomHeight: [3, 7], + corridorLength: [2, 6], + dugPercentage: 0.2 + }); + + // Initialize the empty map with walls (1) + const map = Array(height).fill().map(() => Array(width).fill(1)); + + // Fill in floors (0) using digger's callback + digger.create((x, y, value) => { + // value: 0 = floor, 1 = wall + map[y][x] = value; + }); + + // Get rooms that were created + const rooms = digger.getRooms(); + + // Place entrance in the first room + const entranceRoom = rooms[0]; + const entranceCenter = entranceRoom.getCenter(); + const entrance = [entranceCenter[0], entranceCenter[1]]; + + // Place exit in the last room + const exitRoom = rooms[rooms.length - 1]; + const exitCenter = exitRoom.getCenter(); + const exit = [exitCenter[0], exitCenter[1]]; + + // Place treasure in a middle room (not first or last) + let treasureRoom; + if (rooms.length > 2) { + treasureRoom = rooms[Math.floor(rooms.length / 2)]; + } else { + // Fallback if we have fewer than 3 rooms + treasureRoom = rooms[0]; + } + const treasureCenter = treasureRoom.getCenter(); + // Place treasure slightly off center to make it more interesting + const treasure = [ + treasureCenter[0] + Math.floor(Math.random() * 3) - 1, + treasureCenter[1] + Math.floor(Math.random() * 3) - 1 + ]; + + // Ensure the treasure is on a floor tile + if (map[treasure[1]][treasure[0]] !== 0) { + treasure[0] = treasureCenter[0]; + treasure[1] = treasureCenter[1]; + } + + return { + map: map, + rooms: rooms, + entrance: entrance, + exit: exit, + treasure: treasure + }; +} + +class Game { + constructor(socketId, mapWidth, mapHeight) { + this.socketId = socketId; + this.width = mapWidth || 50; + this.height = mapHeight || 30; + this.gameState = 'waiting'; // waiting, active, won, lost + this.startBlock = null; + this.dungeon = null; + this.player = { x: 0, y: 0, hasKey: false, hasTreasure: false }; + this.monster = { x: 0, y: 0 }; + this.fee = 0; // Amount player paid + this.generateDungeon(); + } + + generateDungeon() { + const dungeon = generateDungeon(this.width, this.height); + this.dungeon = dungeon; + + if (dungeon.entrance) { + this.player.x = dungeon.entrance[0]; + this.player.y = dungeon.entrance[1]; + } + + // Place monster far from entrance + if (dungeon.rooms && dungeon.rooms.length > 2) { + const monsterRoom = dungeon.rooms[Math.floor(dungeon.rooms.length * 0.7)]; + const center = monsterRoom.getCenter(); + this.monster.x = center[0]; + this.monster.y = center[1]; + } + } + + movePlayer(dx, dy) { + const newX = this.player.x + dx; + const newY = this.player.y + dy; + + // Check if the move is valid (not into a wall) + if (this.dungeon.map[newY][newX] === 0) { + this.player.x = newX; + this.player.y = newY; + + // Check if player found treasure + if (this.dungeon.treasure && + newX === this.dungeon.treasure[0] && + newY === this.dungeon.treasure[1]) { + this.player.hasTreasure = true; + } + + // Check if player reached exit + if (this.dungeon.exit && + newX === this.dungeon.exit[0] && + newY === this.dungeon.exit[1]) { + this.gameState = 'won'; + return { status: 'won', hasTreasure: this.player.hasTreasure }; + } + + // Move monster after player moves + this.moveMonster(); + + // Check if monster caught player + if (this.monster.x === this.player.x && this.monster.y === this.player.y) { + this.gameState = 'lost'; + return { status: 'lost', reason: 'caught' }; + } + + return { status: 'moved' }; + } + + return { status: 'invalid' }; + } + + moveMonster() { + // Simple monster AI to move toward player + const dx = Math.sign(this.player.x - this.monster.x); + const dy = Math.sign(this.player.y - this.monster.y); + + // Try horizontal move + if (dx !== 0) { + if (this.dungeon.map[this.monster.y][this.monster.x + dx] === 0) { + this.monster.x += dx; + return; + } + } + + // Try vertical move + if (dy !== 0) { + if (this.dungeon.map[this.monster.y + dy][this.monster.x] === 0) { + this.monster.y += dy; + return; + } + } + + // Try random direction if direct path is blocked + const dirs = [[0,1],[1,0],[0,-1],[-1,0]]; + const shuffledDirs = ROT.RNG.shuffle(dirs.slice()); + + for (const [dx, dy] of shuffledDirs) { + const nx = this.monster.x + dx; + const ny = this.monster.y + dy; + if (this.dungeon.map[ny] && this.dungeon.map[ny][nx] === 0) { + this.monster.x = nx; + this.monster.y = ny; + break; + } + } + } + + getState() { + return { + gameState: this.gameState, + player: this.player, + monster: this.monster, + map: this.dungeon.map, + entrance: this.dungeon.entrance, + exit: this.dungeon.exit, + treasure: this.dungeon.treasure, + hasTreasure: this.player.hasTreasure + }; + } +} + +module.exports = Game; \ No newline at end of file diff --git a/html/favicon.ico b/html/favicon.ico new file mode 100644 index 0000000..8585e95 Binary files /dev/null and b/html/favicon.ico differ diff --git a/html/index.html b/html/index.html new file mode 100644 index 0000000..cad0755 --- /dev/null +++ b/html/index.html @@ -0,0 +1,207 @@ + + + + Wowgue + + + + +
+
+

+
+ +
+ Block height: 0 +
+ +
+
+
    +
  • Welcome to Wowgue!
  • +
  • Type 'hello' to begin
  • +
+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + diff --git a/html/js/game.js b/html/js/game.js new file mode 100644 index 0000000..6e19788 --- /dev/null +++ b/html/js/game.js @@ -0,0 +1,227 @@ +var Game = { + // Change dimensions to match the display options (25 × 19 tiles) + _screenWidth: 25, // Used for drawing coordinates (columns) + _screenHeight: 19, // Used for drawing coordinates (rows) + _mapWidth: 25, // Logical map width (should match display) + _mapHeight: 19, // Logical map height (should match display) + _display: null, + _map: null, + _player: null, + _monster: null, + _exit: null, + _entrance: null, + _treasure: null, + _gameActive: false, + _message: "", // To display messages like 'waiting' + + init: function() { + // Assuming 'options' is defined globally or passed correctly + console.log("Creating ROT.Display with options:", options); + try { + this._display = new ROT.Display(options); + console.log("ROT.Display created."); + // Do not append here; we use external logic to append container + } catch (e) { + console.error("Error creating ROT.Display:", e); + alert("Failed to initialize display. Check console for errors."); + return; + } + + // Initialize empty map representation based on _mapWidth and _mapHeight + this._map = []; + for (var i = 0; i < this._mapWidth; i++) { + this._map[i] = []; + for (var j = 0; j < this._mapHeight; j++) { + // Default to wall visually; adjust as needed + this._map[i][j] = 1; + } + } + + var game = this; + // Set up keyboard input + window.addEventListener("keydown", function(e) { + var code = e.keyCode; + + // If game isn't active, ignore all keys except Enter + if (!game._gameActive && code !== 13) { + return; + } + + // Enter key to start game + if (code === 13 && !game._gameActive) { + console.log("Enter pressed, sending 'enter' message to server."); + socket.emit('chat message', 'enter'); + game._message = "Connecting..."; + game._drawWelcomeScreen(); + e.preventDefault(); + return; + } + + // Movement controls + var direction = ""; + switch (code) { + case 38: case 75: case 87: // up, k, w + direction = "up"; + break; + case 40: case 74: case 83: // down, j, s + direction = "down"; + break; + case 37: case 72: case 65: // left, h, a + direction = "left"; + break; + case 39: case 76: case 68: // right, l, d + direction = "right"; + break; + default: + return; + } + + if (direction && game._gameActive) { + socket.emit('move', direction); + e.preventDefault(); + } + }); + + // Draw welcome screen + this._message = "Press Enter or type 'enter' to Play!"; + this._drawWelcomeScreen(); + }, + + // Initialize game with data from server + startGame: function(data) { + console.log("Starting game with data:", data); + + this._map = data.map; + this._player = data.player; + this._monster = data.monster; + this._entrance = data.entrance; + this._exit = data.exit; + this._treasure = data.treasure; + this._gameActive = true; + + this._drawGameScreen(); + }, + + clearDisplay: function() { + // Clear the entire display area + this._display.clear(); + }, + + _drawGameScreen: function() { + this.clearDisplay(); + + // Draw map + for (var x = 0; x < this._mapWidth; x++) { + for (var y = 0; y < this._mapHeight; y++) { + var tile = this._map[y] && this._map[y][x] ? this._map[y][x] : 1; + + if (tile === 0) { + this._display.draw(x, y, "'", "#fff"); // Floor + } else { + this._display.draw(x, y, "#", "#777"); // Wall + } + } + } + + // Draw special features + if (this._entrance) { + this._display.draw(this._entrance[0], this._entrance[1], "<", "#0f0"); + } + + if (this._exit) { + this._display.draw(this._exit[0], this._exit[1], ">", "#0f0"); + } + + if (this._treasure && (!this._player || !this._player.hasTreasure)) { + this._display.draw(this._treasure[0], this._treasure[1], "$", "#ff0"); + } + + // Draw player + if (this._player) { + this._display.draw(this._player.x, this._player.y, "@", "#fff"); + } + + // Draw monster + if (this._monster) { + this._display.draw(this._monster.x, this._monster.y, "~", "#f00"); + } + + // Draw status line + var statusY = this._mapHeight; // Position below map + this._display.drawText(0, statusY, "--------------------------------------------------------------------------------"); // Separator + statusY++; + + var statusLine = `Use Arrows/WASD/HJKL. Find ($) and reach exit (>). Avoid (~).`; + if (this._player && this._player.hasTreasure) { + statusLine = "You have the treasure ($)! Reach the exit (>)!"; + } + this._display.drawText(1, statusY, statusLine); + }, + + _drawWelcomeScreen: function() { + this.clearDisplay(); + var y = 5; + this._display.drawText(this._screenWidth / 2 - 5, y++, "%c{yellow}WOWGUE"); + y++; + y+=2; + this._display.drawText(this._screenWidth / 2 - 10, y++, "@ - This is you"); + this._display.drawText(this._screenWidth / 2 - 10, y++, "> - Escape the dungeon"); + this._display.drawText(this._screenWidth / 2 - 10, y++, "~ - Avoid the monster"); + this._display.drawText(this._screenWidth / 2 - 10, y++, "$ - Find the treasure"); + y+=2; + // Display dynamic message (like waiting or error) + if (this._message) { + this._display.drawText(this._screenWidth / 2 - this._message.length / 2, y++, `%c{yellow}${this._message}`); + } + }, + + _drawWinScreen: function(hasTreasure) { + this.clearDisplay(); + var y = 5; + this._display.drawText(this._screenWidth / 2 - 5, y++, "%c{green}YOU WIN!"); + y++; + + if (hasTreasure) { + this._display.drawText(this._screenWidth / 2 - 15, y++, "You found the treasure and escaped!"); + } else { + this._display.drawText(this._screenWidth / 2 - 10, y++, "You escaped the dungeon!"); + } + + y++; + this._gameActive = false; + this._message = "Press Enter to Play Again!"; + this._display.drawText(this._screenWidth / 2 - (this._message.length / 2), y++, `%c{yellow}${this._message}`); + }, + + _drawLoseScreen: function(reason) { + this.clearDisplay(); + var y = 5; + this._display.drawText(this._screenWidth / 2 - 5, y++, "%c{red}GAME OVER!"); + y++; + + if (reason === 'timeout') { + this._display.drawText(this._screenWidth / 2 - 20, y++, "You didn't escape before the next block!"); + } else if (reason === 'caught') { + this._display.drawText(this._screenWidth / 2 - 15, y++, "The monster caught you!"); + } else { + this._display.drawText(this._screenWidth / 2 - 10, y++, `Reason: ${reason}`); + } + + y++; + this._gameActive = false; + this._message = "Press Enter to Play Again!"; + this._display.drawText(this._screenWidth / 2 - (this._message.length / 2), y++, `%c{yellow}${this._message}`); + }, + + getDisplay: function() { + return this._display; + }, + + getScreenWidth: function() { + return this._screenWidth; + }, + + getScreenHeight: function() { + return this._screenHeight; + } +}; \ No newline at end of file diff --git a/html/js/jquery-3.4.1.min.js b/html/js/jquery-3.4.1.min.js new file mode 100644 index 0000000..a1c07fd --- /dev/null +++ b/html/js/jquery-3.4.1.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0": [32, 0], // Exit + "@": [64, 0], // Player + "~": [96, 0], // Monster + "<": [0, 32], // Entrance + "=": [32, 32], // Monster Entrance + "#": [64, 32], // Wall + "$": [96, 32], // Treasure + // ... include all other necessary character mappings ... + "a": [128, 0], + "b": [160, 0], + "c": [192, 0], + "d": [224, 0], + "e": [256, 0], + "f": [288, 0], + "g": [320, 0], + "h": [352, 0], + "i": [384, 0], + "j": [416, 0], + "k": [448, 0], + "l": [480, 0], + "m": [512, 0], // Duplicate M? Ensure one is correct + "n": [544, 0], + "o": [576, 0], + "p": [608, 0], + "q": [640, 0], + "r": [672, 0], + "s": [704, 0], + "t": [736, 0], + "u": [768, 0], + "v": [800, 0], + "w": [832, 0], + "x": [864, 0], + "y": [896, 0], + "z": [928, 0], + "A": [128, 32], + "B": [160, 32], + "C": [192, 32], + "D": [224, 32], + "E": [256, 32], + "F": [288, 32], + "G": [320, 32], + "H": [352, 32], + "I": [384, 32], + "J": [416, 32], + "K": [448, 32], + "L": [480, 32], + "M": [512, 32], // Already mapped M + "N": [544, 32], + "O": [576, 32], + "P": [608, 32], + "Q": [640, 32], + "R": [672, 32], + "S": [704, 32], + "T": [736, 32], + "U": [768, 32], + "V": [800, 32], + "W": [832, 32], + "X": [864, 32], + "Y": [896, 32], + "Z": [928, 32], + "&": [0, 64], + "-": [32, 64], + "+": [64, 64], + "`": [96, 64], + "0": [128, 64], + "1": [160, 64], + "2": [192, 64], + "3": [224, 64], + "4": [256, 64], + "5": [288, 64], + "6": [320, 64], + "7": [352, 64], + "8": [384, 64], + "9": [416, 64], + ".": [448, 64], + ":": [480, 64], + ",": [512, 64], + ";": [544, 64], + "(": [576, 64], + "*": [608, 64], + "!": [640, 64], + "?": [672, 64], + "}": [704, 64], + "^": [736, 64], + ")": [768, 64], + "[": [800, 64], + "]": [832, 64], + "{": [864, 64], + "%": [896, 64], + "^": [928, 64], // Duplicate ^ + " ": [992, 64] + } +}; diff --git a/html/js/rot.js b/html/js/rot.js new file mode 100644 index 0000000..03f3919 --- /dev/null +++ b/html/js/rot.js @@ -0,0 +1,7228 @@ +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.ROT = {}); +})(this, function (exports) { + 'use strict'; + /** + * This code is an implementation of Alea algorithm; (C) 2010 Johannes Baagøe. + * Alea is licensed according to the http://en.wikipedia.org/wiki/MIT_License. + */ + + var FRAC = 2.3283064365386963e-10; + /* 2^-32 */ + + var RNG = + /*#__PURE__*/ + function () { + function RNG() { + this._seed = 0; + this._s0 = 0; + this._s1 = 0; + this._s2 = 0; + this._c = 0; + } + + var _proto = RNG.prototype; + + _proto.getSeed = function getSeed() { + return this._seed; + }; + /** + * Seed the number generator + */ + + + _proto.setSeed = function setSeed(seed) { + seed = seed < 1 ? 1 / seed : seed; + this._seed = seed; + this._s0 = (seed >>> 0) * FRAC; + seed = seed * 69069 + 1 >>> 0; + this._s1 = seed * FRAC; + seed = seed * 69069 + 1 >>> 0; + this._s2 = seed * FRAC; + this._c = 1; + return this; + }; + /** + * @returns Pseudorandom value [0,1), uniformly distributed + */ + + + _proto.getUniform = function getUniform() { + var t = 2091639 * this._s0 + this._c * FRAC; + this._s0 = this._s1; + this._s1 = this._s2; + this._c = t | 0; + this._s2 = t - this._c; + return this._s2; + }; + /** + * @param lowerBound The lower end of the range to return a value from, inclusive + * @param upperBound The upper end of the range to return a value from, inclusive + * @returns Pseudorandom value [lowerBound, upperBound], using ROT.RNG.getUniform() to distribute the value + */ + + + _proto.getUniformInt = function getUniformInt(lowerBound, upperBound) { + var max = Math.max(lowerBound, upperBound); + var min = Math.min(lowerBound, upperBound); + return Math.floor(this.getUniform() * (max - min + 1)) + min; + }; + /** + * @param mean Mean value + * @param stddev Standard deviation. ~95% of the absolute values will be lower than 2*stddev. + * @returns A normally distributed pseudorandom value + */ + + + _proto.getNormal = function getNormal(mean, stddev) { + if (mean === void 0) { + mean = 0; + } + + if (stddev === void 0) { + stddev = 1; + } + + var u, v, r; + + do { + u = 2 * this.getUniform() - 1; + v = 2 * this.getUniform() - 1; + r = u * u + v * v; + } while (r > 1 || r == 0); + + var gauss = u * Math.sqrt(-2 * Math.log(r) / r); + return mean + gauss * stddev; + }; + /** + * @returns Pseudorandom value [1,100] inclusive, uniformly distributed + */ + + + _proto.getPercentage = function getPercentage() { + return 1 + Math.floor(this.getUniform() * 100); + }; + /** + * @returns Randomly picked item, null when length=0 + */ + + + _proto.getItem = function getItem(array) { + if (!array.length) { + return null; + } + + return array[Math.floor(this.getUniform() * array.length)]; + }; + /** + * @returns New array with randomized items + */ + + + _proto.shuffle = function shuffle(array) { + var result = []; + var clone = array.slice(); + + while (clone.length) { + var _index = clone.indexOf(this.getItem(clone)); + + result.push(clone.splice(_index, 1)[0]); + } + + return result; + }; + /** + * @param data key=whatever, value=weight (relative probability) + * @returns whatever + */ + + + _proto.getWeightedValue = function getWeightedValue(data) { + var total = 0; + + for (var _id in data) { + total += data[_id]; + } + + var random = this.getUniform() * total; + var id, + part = 0; + + for (id in data) { + part += data[id]; + + if (random < part) { + return id; + } + } // If by some floating-point annoyance we have + // random >= total, just return the last id. + + + return id; + }; + /** + * Get RNG state. Useful for storing the state and re-setting it via setState. + * @returns Internal state + */ + + + _proto.getState = function getState() { + return [this._s0, this._s1, this._s2, this._c]; + }; + /** + * Set a previously retrieved state. + */ + + + _proto.setState = function setState(state) { + this._s0 = state[0]; + this._s1 = state[1]; + this._s2 = state[2]; + this._c = state[3]; + return this; + }; + /** + * Returns a cloned RNG + */ + + + _proto.clone = function clone() { + var clone = new RNG(); + return clone.setState(this.getState()); + }; + + return RNG; + }(); + + var RNG$1 = new RNG().setSeed(Date.now()); + /** + * @class Abstract display backend module + * @private + */ + + var Backend = + /*#__PURE__*/ + function () { + function Backend() {} + + var _proto2 = Backend.prototype; + + _proto2.getContainer = function getContainer() { + return null; + }; + + _proto2.setOptions = function setOptions(options) { + this._options = options; + }; + + return Backend; + }(); + + var Canvas = + /*#__PURE__*/ + function (_Backend) { + _inheritsLoose(Canvas, _Backend); + + function Canvas() { + var _this; + + _this = _Backend.call(this) || this; + _this._ctx = document.createElement("canvas").getContext("2d"); + return _this; + } + + var _proto3 = Canvas.prototype; + + _proto3.schedule = function schedule(cb) { + requestAnimationFrame(cb); + }; + + _proto3.getContainer = function getContainer() { + return this._ctx.canvas; + }; + + _proto3.setOptions = function setOptions(opts) { + _Backend.prototype.setOptions.call(this, opts); + + var style = opts.fontStyle ? opts.fontStyle + " " : ""; + var font = style + " " + opts.fontSize + "px " + opts.fontFamily; + this._ctx.font = font; + + this._updateSize(); + + this._ctx.font = font; + this._ctx.textAlign = "center"; + this._ctx.textBaseline = "middle"; + }; + + _proto3.clear = function clear() { + this._ctx.fillStyle = this._options.bg; + + this._ctx.fillRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height); + }; + + _proto3.eventToPosition = function eventToPosition(x, y) { + var canvas = this._ctx.canvas; + var rect = canvas.getBoundingClientRect(); + x -= rect.left; + y -= rect.top; + x *= canvas.width / rect.width; + y *= canvas.height / rect.height; + + if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) { + return [-1, -1]; + } + + return this._normalizedEventToPosition(x, y); + }; + + return Canvas; + }(Backend); + /** + * Always positive modulus + * @param x Operand + * @param n Modulus + * @returns x modulo n + */ + + + function mod(x, n) { + return (x % n + n) % n; + } + + function clamp(val, min, max) { + if (min === void 0) { + min = 0; + } + + if (max === void 0) { + max = 1; + } + + if (val < min) return min; + if (val > max) return max; + return val; + } + + function capitalize(string) { + return string.charAt(0).toUpperCase() + string.substring(1); + } + /** + * Format a string in a flexible way. Scans for %s strings and replaces them with arguments. List of patterns is modifiable via String.format.map. + * @param {string} template + * @param {any} [argv] + */ + + + function format(template) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var map = format.map; + + var replacer = function replacer(match, group1, group2, index) { + if (template.charAt(index - 1) == "%") { + return match.substring(1); + } + + if (!args.length) { + return match; + } + + var obj = args[0]; + var group = group1 || group2; + var parts = group.split(","); + var name = parts.shift() || ""; + var method = map[name.toLowerCase()]; + + if (!method) { + return match; + } + + obj = args.shift(); + var replaced = obj[method].apply(obj, parts); + var first = name.charAt(0); + + if (first != first.toLowerCase()) { + replaced = capitalize(replaced); + } + + return replaced; + }; + + return template.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi, replacer); + } + + format.map = { + "s": "toString" + }; + var util = + /*#__PURE__*/ + Object.freeze({ + mod: mod, + clamp: clamp, + capitalize: capitalize, + format: format + }); + /** + * @class Hexagonal backend + * @private + */ + + var Hex = + /*#__PURE__*/ + function (_Canvas) { + _inheritsLoose(Hex, _Canvas); + + function Hex() { + var _this2; + + _this2 = _Canvas.call(this) || this; + _this2._spacingX = 0; + _this2._spacingY = 0; + _this2._hexSize = 0; + return _this2; + } + + var _proto4 = Hex.prototype; + + _proto4.draw = function draw(data, clearBefore) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var px = [(x + 1) * this._spacingX, y * this._spacingY + this._hexSize]; + + if (this._options.transpose) { + px.reverse(); + } + + if (clearBefore) { + this._ctx.fillStyle = bg; + + this._fill(px[0], px[1]); + } + + if (!ch) { + return; + } + + this._ctx.fillStyle = fg; + var chars = [].concat(ch); + + for (var i = 0; i < chars.length; i++) { + this._ctx.fillText(chars[i], px[0], Math.ceil(px[1])); + } + }; + + _proto4.computeSize = function computeSize(availWidth, availHeight) { + if (this._options.transpose) { + availWidth += availHeight; + availHeight = availWidth - availHeight; + availWidth -= availHeight; + } + + var width = Math.floor(availWidth / this._spacingX) - 1; + var height = Math.floor((availHeight - 2 * this._hexSize) / this._spacingY + 1); + return [width, height]; + }; + + _proto4.computeFontSize = function computeFontSize(availWidth, availHeight) { + if (this._options.transpose) { + availWidth += availHeight; + availHeight = availWidth - availHeight; + availWidth -= availHeight; + } + + var hexSizeWidth = 2 * availWidth / ((this._options.width + 1) * Math.sqrt(3)) - 1; + var hexSizeHeight = availHeight / (2 + 1.5 * (this._options.height - 1)); + var hexSize = Math.min(hexSizeWidth, hexSizeHeight); // compute char ratio + + var oldFont = this._ctx.font; + this._ctx.font = "100px " + this._options.fontFamily; + var width = Math.ceil(this._ctx.measureText("W").width); + this._ctx.font = oldFont; + var ratio = width / 100; + hexSize = Math.floor(hexSize) + 1; // closest larger hexSize + // FIXME char size computation does not respect transposed hexes + + var fontSize = 2 * hexSize / (this._options.spacing * (1 + ratio / Math.sqrt(3))); // closest smaller fontSize + + return Math.ceil(fontSize) - 1; + }; + + _proto4._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + var nodeSize; + + if (this._options.transpose) { + x += y; + y = x - y; + x -= y; + nodeSize = this._ctx.canvas.width; + } else { + nodeSize = this._ctx.canvas.height; + } + + var size = nodeSize / this._options.height; + y = Math.floor(y / size); + + if (mod(y, 2)) { + /* odd row */ + x -= this._spacingX; + x = 1 + 2 * Math.floor(x / (2 * this._spacingX)); + } else { + x = 2 * Math.floor(x / (2 * this._spacingX)); + } + + return [x, y]; + }; + /** + * Arguments are pixel values. If "transposed" mode is enabled, then these two are already swapped. + */ + + + _proto4._fill = function _fill(cx, cy) { + var a = this._hexSize; + var b = this._options.border; + var ctx = this._ctx; + ctx.beginPath(); + + if (this._options.transpose) { + ctx.moveTo(cx - a + b, cy); + ctx.lineTo(cx - a / 2 + b, cy + this._spacingX - b); + ctx.lineTo(cx + a / 2 - b, cy + this._spacingX - b); + ctx.lineTo(cx + a - b, cy); + ctx.lineTo(cx + a / 2 - b, cy - this._spacingX + b); + ctx.lineTo(cx - a / 2 + b, cy - this._spacingX + b); + ctx.lineTo(cx - a + b, cy); + } else { + ctx.moveTo(cx, cy - a + b); + ctx.lineTo(cx + this._spacingX - b, cy - a / 2 + b); + ctx.lineTo(cx + this._spacingX - b, cy + a / 2 - b); + ctx.lineTo(cx, cy + a - b); + ctx.lineTo(cx - this._spacingX + b, cy + a / 2 - b); + ctx.lineTo(cx - this._spacingX + b, cy - a / 2 + b); + ctx.lineTo(cx, cy - a + b); + } + + ctx.fill(); + }; + + _proto4._updateSize = function _updateSize() { + var opts = this._options; + var charWidth = Math.ceil(this._ctx.measureText("W").width); + this._hexSize = Math.floor(opts.spacing * (opts.fontSize + charWidth / Math.sqrt(3)) / 2); + this._spacingX = this._hexSize * Math.sqrt(3) / 2; + this._spacingY = this._hexSize * 1.5; + var xprop; + var yprop; + + if (opts.transpose) { + xprop = "height"; + yprop = "width"; + } else { + xprop = "width"; + yprop = "height"; + } + + this._ctx.canvas[xprop] = Math.ceil((opts.width + 1) * this._spacingX); + this._ctx.canvas[yprop] = Math.ceil((opts.height - 1) * this._spacingY + 2 * this._hexSize); + }; + + return Hex; + }(Canvas); + /** + * @class Rectangular backend + * @private + */ + + + var Rect = + /*#__PURE__*/ + function (_Canvas2) { + _inheritsLoose(Rect, _Canvas2); + + function Rect() { + var _this3; + + _this3 = _Canvas2.call(this) || this; + _this3._spacingX = 0; + _this3._spacingY = 0; + _this3._canvasCache = {}; + return _this3; + } + + var _proto5 = Rect.prototype; + + _proto5.setOptions = function setOptions(options) { + _Canvas2.prototype.setOptions.call(this, options); + + this._canvasCache = {}; + }; + + _proto5.draw = function draw(data, clearBefore) { + if (Rect.cache) { + this._drawWithCache(data); + } else { + this._drawNoCache(data, clearBefore); + } + }; + + _proto5._drawWithCache = function _drawWithCache(data) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var hash = "" + ch + fg + bg; + var canvas; + + if (hash in this._canvasCache) { + canvas = this._canvasCache[hash]; + } else { + var b = this._options.border; + canvas = document.createElement("canvas"); + var ctx = canvas.getContext("2d"); + canvas.width = this._spacingX; + canvas.height = this._spacingY; + ctx.fillStyle = bg; + ctx.fillRect(b, b, canvas.width - b, canvas.height - b); + + if (ch) { + ctx.fillStyle = fg; + ctx.font = this._ctx.font; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + var chars = [].concat(ch); + + for (var i = 0; i < chars.length; i++) { + ctx.fillText(chars[i], this._spacingX / 2, Math.ceil(this._spacingY / 2)); + } + } + + this._canvasCache[hash] = canvas; + } + + this._ctx.drawImage(canvas, x * this._spacingX, y * this._spacingY); + }; + + _proto5._drawNoCache = function _drawNoCache(data, clearBefore) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + + if (clearBefore) { + var b = this._options.border; + this._ctx.fillStyle = bg; + + this._ctx.fillRect(x * this._spacingX + b, y * this._spacingY + b, this._spacingX - b, this._spacingY - b); + } + + if (!ch) { + return; + } + + this._ctx.fillStyle = fg; + var chars = [].concat(ch); + + for (var i = 0; i < chars.length; i++) { + this._ctx.fillText(chars[i], (x + 0.5) * this._spacingX, Math.ceil((y + 0.5) * this._spacingY)); + } + }; + + _proto5.computeSize = function computeSize(availWidth, availHeight) { + var width = Math.floor(availWidth / this._spacingX); + var height = Math.floor(availHeight / this._spacingY); + return [width, height]; + }; + + _proto5.computeFontSize = function computeFontSize(availWidth, availHeight) { + var boxWidth = Math.floor(availWidth / this._options.width); + var boxHeight = Math.floor(availHeight / this._options.height); + /* compute char ratio */ + + var oldFont = this._ctx.font; + this._ctx.font = "100px " + this._options.fontFamily; + var width = Math.ceil(this._ctx.measureText("W").width); + this._ctx.font = oldFont; + var ratio = width / 100; + var widthFraction = ratio * boxHeight / boxWidth; + + if (widthFraction > 1) { + /* too wide with current aspect ratio */ + boxHeight = Math.floor(boxHeight / widthFraction); + } + + return Math.floor(boxHeight / this._options.spacing); + }; + + _proto5._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + return [Math.floor(x / this._spacingX), Math.floor(y / this._spacingY)]; + }; + + _proto5._updateSize = function _updateSize() { + var opts = this._options; + var charWidth = Math.ceil(this._ctx.measureText("W").width); + this._spacingX = Math.ceil(opts.spacing * charWidth); + this._spacingY = Math.ceil(opts.spacing * opts.fontSize); + + if (opts.forceSquareRatio) { + this._spacingX = this._spacingY = Math.max(this._spacingX, this._spacingY); + } + + this._ctx.canvas.width = opts.width * this._spacingX; + this._ctx.canvas.height = opts.height * this._spacingY; + }; + + return Rect; + }(Canvas); + + Rect.cache = false; + /** + * @class Tile backend + * @private + */ + + var Tile = + /*#__PURE__*/ + function (_Canvas3) { + _inheritsLoose(Tile, _Canvas3); + + function Tile() { + var _this4; + + _this4 = _Canvas3.call(this) || this; + _this4._colorCanvas = document.createElement("canvas"); + return _this4; + } + + var _proto6 = Tile.prototype; + + _proto6.draw = function draw(data, clearBefore) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var tileWidth = this._options.tileWidth; + var tileHeight = this._options.tileHeight; + + if (clearBefore) { + if (this._options.tileColorize) { + this._ctx.clearRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } else { + this._ctx.fillStyle = bg; + + this._ctx.fillRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } + } + + if (!ch) { + return; + } + + var chars = [].concat(ch); + var fgs = [].concat(fg); + var bgs = [].concat(bg); + + for (var i = 0; i < chars.length; i++) { + var tile = this._options.tileMap[chars[i]]; + + if (!tile) { + throw new Error("Char \"" + chars[i] + "\" not found in tileMap"); + } + + if (this._options.tileColorize) { + // apply colorization + var canvas = this._colorCanvas; + var context = canvas.getContext("2d"); + context.globalCompositeOperation = "source-over"; + context.clearRect(0, 0, tileWidth, tileHeight); + var _fg = fgs[i]; + var _bg = bgs[i]; + context.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, 0, 0, tileWidth, tileHeight); + + if (_fg != "transparent") { + context.fillStyle = _fg; + context.globalCompositeOperation = "source-atop"; + context.fillRect(0, 0, tileWidth, tileHeight); + } + + if (_bg != "transparent") { + context.fillStyle = _bg; + context.globalCompositeOperation = "destination-over"; + context.fillRect(0, 0, tileWidth, tileHeight); + } + + this._ctx.drawImage(canvas, x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } else { + // no colorizing, easy + this._ctx.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } + } + }; + + _proto6.computeSize = function computeSize(availWidth, availHeight) { + var width = Math.floor(availWidth / this._options.tileWidth); + var height = Math.floor(availHeight / this._options.tileHeight); + return [width, height]; + }; + + _proto6.computeFontSize = function computeFontSize() { + throw new Error("Tile backend does not understand font size"); + }; + + _proto6._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + return [Math.floor(x / this._options.tileWidth), Math.floor(y / this._options.tileHeight)]; + }; + + _proto6._updateSize = function _updateSize() { + var opts = this._options; + this._ctx.canvas.width = opts.width * opts.tileWidth; + this._ctx.canvas.height = opts.height * opts.tileHeight; + this._colorCanvas.width = opts.tileWidth; + this._colorCanvas.height = opts.tileHeight; + }; + + return Tile; + }(Canvas); + + function fromString(str) { + var cached, r; + + if (str in CACHE) { + cached = CACHE[str]; + } else { + if (str.charAt(0) == "#") { + // hex rgb + var matched = str.match(/[0-9a-f]/gi) || []; + var values = matched.map(function (x) { + return parseInt(x, 16); + }); + + if (values.length == 3) { + cached = values.map(function (x) { + return x * 17; + }); + } else { + for (var i = 0; i < 3; i++) { + values[i + 1] += 16 * values[i]; + values.splice(i, 1); + } + + cached = values; + } + } else if (r = str.match(/rgb\(([0-9, ]+)\)/i)) { + // decimal rgb + cached = r[1].split(/\s*,\s*/).map(function (x) { + return parseInt(x); + }); + } else { + // html name + cached = [0, 0, 0]; + } + + CACHE[str] = cached; + } + + return cached.slice(); + } + /** + * Add two or more colors + */ + + + function add(color1) { + var result = color1.slice(); + + for (var _len2 = arguments.length, colors = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + colors[_key2 - 1] = arguments[_key2]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + result[i] += colors[j][i]; + } + } + + return result; + } + /** + * Add two or more colors, MODIFIES FIRST ARGUMENT + */ + + + function add_(color1) { + for (var _len3 = arguments.length, colors = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + colors[_key3 - 1] = arguments[_key3]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + color1[i] += colors[j][i]; + } + } + + return color1; + } + /** + * Multiply (mix) two or more colors + */ + + + function multiply(color1) { + var result = color1.slice(); + + for (var _len4 = arguments.length, colors = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + colors[_key4 - 1] = arguments[_key4]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + result[i] *= colors[j][i] / 255; + } + + result[i] = Math.round(result[i]); + } + + return result; + } + /** + * Multiply (mix) two or more colors, MODIFIES FIRST ARGUMENT + */ + + + function multiply_(color1) { + for (var _len5 = arguments.length, colors = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + colors[_key5 - 1] = arguments[_key5]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + color1[i] *= colors[j][i] / 255; + } + + color1[i] = Math.round(color1[i]); + } + + return color1; + } + /** + * Interpolate (blend) two colors with a given factor + */ + + + function interpolate(color1, color2, factor) { + if (factor === void 0) { + factor = 0.5; + } + + var result = color1.slice(); + + for (var i = 0; i < 3; i++) { + result[i] = Math.round(result[i] + factor * (color2[i] - color1[i])); + } + + return result; + } + + var lerp = interpolate; + /** + * Interpolate (blend) two colors with a given factor in HSL mode + */ + + function interpolateHSL(color1, color2, factor) { + if (factor === void 0) { + factor = 0.5; + } + + var hsl1 = rgb2hsl(color1); + var hsl2 = rgb2hsl(color2); + + for (var i = 0; i < 3; i++) { + hsl1[i] += factor * (hsl2[i] - hsl1[i]); + } + + return hsl2rgb(hsl1); + } + + var lerpHSL = interpolateHSL; + /** + * Create a new random color based on this one + * @param color + * @param diff Set of standard deviations + */ + + function randomize(color, diff) { + if (!(diff instanceof Array)) { + diff = Math.round(RNG$1.getNormal(0, diff)); + } + + var result = color.slice(); + + for (var i = 0; i < 3; i++) { + result[i] += diff instanceof Array ? Math.round(RNG$1.getNormal(0, diff[i])) : diff; + } + + return result; + } + /** + * Converts an RGB color value to HSL. Expects 0..255 inputs, produces 0..1 outputs. + */ + + + function rgb2hsl(color) { + var r = color[0] / 255; + var g = color[1] / 255; + var b = color[2] / 255; + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h = 0, + s, + l = (max + min) / 2; + + if (max == min) { + s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + + case g: + h = (b - r) / d + 2; + break; + + case b: + h = (r - g) / d + 4; + break; + } + + h /= 6; + } + + return [h, s, l]; + } + + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + /** + * Converts an HSL color value to RGB. Expects 0..1 inputs, produces 0..255 outputs. + */ + + + function hsl2rgb(color) { + var l = color[2]; + + if (color[1] == 0) { + l = Math.round(l * 255); + return [l, l, l]; + } else { + var s = color[1]; + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + var r = hue2rgb(p, q, color[0] + 1 / 3); + var g = hue2rgb(p, q, color[0]); + var b = hue2rgb(p, q, color[0] - 1 / 3); + return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; + } + } + + function toRGB(color) { + var clamped = color.map(function (x) { + return clamp(x, 0, 255); + }); + return "rgb(" + clamped.join(",") + ")"; + } + + function toHex(color) { + var clamped = color.map(function (x) { + return clamp(x, 0, 255).toString(16).padStart(2, "0"); + }); + return "#" + clamped.join(""); + } + + var CACHE = { + "black": [0, 0, 0], + "navy": [0, 0, 128], + "darkblue": [0, 0, 139], + "mediumblue": [0, 0, 205], + "blue": [0, 0, 255], + "darkgreen": [0, 100, 0], + "green": [0, 128, 0], + "teal": [0, 128, 128], + "darkcyan": [0, 139, 139], + "deepskyblue": [0, 191, 255], + "darkturquoise": [0, 206, 209], + "mediumspringgreen": [0, 250, 154], + "lime": [0, 255, 0], + "springgreen": [0, 255, 127], + "aqua": [0, 255, 255], + "cyan": [0, 255, 255], + "midnightblue": [25, 25, 112], + "dodgerblue": [30, 144, 255], + "forestgreen": [34, 139, 34], + "seagreen": [46, 139, 87], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "limegreen": [50, 205, 50], + "mediumseagreen": [60, 179, 113], + "turquoise": [64, 224, 208], + "royalblue": [65, 105, 225], + "steelblue": [70, 130, 180], + "darkslateblue": [72, 61, 139], + "mediumturquoise": [72, 209, 204], + "indigo": [75, 0, 130], + "darkolivegreen": [85, 107, 47], + "cadetblue": [95, 158, 160], + "cornflowerblue": [100, 149, 237], + "mediumaquamarine": [102, 205, 170], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "slateblue": [106, 90, 205], + "olivedrab": [107, 142, 35], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "mediumslateblue": [123, 104, 238], + "lawngreen": [124, 252, 0], + "chartreuse": [127, 255, 0], + "aquamarine": [127, 255, 212], + "maroon": [128, 0, 0], + "purple": [128, 0, 128], + "olive": [128, 128, 0], + "gray": [128, 128, 128], + "grey": [128, 128, 128], + "skyblue": [135, 206, 235], + "lightskyblue": [135, 206, 250], + "blueviolet": [138, 43, 226], + "darkred": [139, 0, 0], + "darkmagenta": [139, 0, 139], + "saddlebrown": [139, 69, 19], + "darkseagreen": [143, 188, 143], + "lightgreen": [144, 238, 144], + "mediumpurple": [147, 112, 216], + "darkviolet": [148, 0, 211], + "palegreen": [152, 251, 152], + "darkorchid": [153, 50, 204], + "yellowgreen": [154, 205, 50], + "sienna": [160, 82, 45], + "brown": [165, 42, 42], + "darkgray": [169, 169, 169], + "darkgrey": [169, 169, 169], + "lightblue": [173, 216, 230], + "greenyellow": [173, 255, 47], + "paleturquoise": [175, 238, 238], + "lightsteelblue": [176, 196, 222], + "powderblue": [176, 224, 230], + "firebrick": [178, 34, 34], + "darkgoldenrod": [184, 134, 11], + "mediumorchid": [186, 85, 211], + "rosybrown": [188, 143, 143], + "darkkhaki": [189, 183, 107], + "silver": [192, 192, 192], + "mediumvioletred": [199, 21, 133], + "indianred": [205, 92, 92], + "peru": [205, 133, 63], + "chocolate": [210, 105, 30], + "tan": [210, 180, 140], + "lightgray": [211, 211, 211], + "lightgrey": [211, 211, 211], + "palevioletred": [216, 112, 147], + "thistle": [216, 191, 216], + "orchid": [218, 112, 214], + "goldenrod": [218, 165, 32], + "crimson": [220, 20, 60], + "gainsboro": [220, 220, 220], + "plum": [221, 160, 221], + "burlywood": [222, 184, 135], + "lightcyan": [224, 255, 255], + "lavender": [230, 230, 250], + "darksalmon": [233, 150, 122], + "violet": [238, 130, 238], + "palegoldenrod": [238, 232, 170], + "lightcoral": [240, 128, 128], + "khaki": [240, 230, 140], + "aliceblue": [240, 248, 255], + "honeydew": [240, 255, 240], + "azure": [240, 255, 255], + "sandybrown": [244, 164, 96], + "wheat": [245, 222, 179], + "beige": [245, 245, 220], + "whitesmoke": [245, 245, 245], + "mintcream": [245, 255, 250], + "ghostwhite": [248, 248, 255], + "salmon": [250, 128, 114], + "antiquewhite": [250, 235, 215], + "linen": [250, 240, 230], + "lightgoldenrodyellow": [250, 250, 210], + "oldlace": [253, 245, 230], + "red": [255, 0, 0], + "fuchsia": [255, 0, 255], + "magenta": [255, 0, 255], + "deeppink": [255, 20, 147], + "orangered": [255, 69, 0], + "tomato": [255, 99, 71], + "hotpink": [255, 105, 180], + "coral": [255, 127, 80], + "darkorange": [255, 140, 0], + "lightsalmon": [255, 160, 122], + "orange": [255, 165, 0], + "lightpink": [255, 182, 193], + "pink": [255, 192, 203], + "gold": [255, 215, 0], + "peachpuff": [255, 218, 185], + "navajowhite": [255, 222, 173], + "moccasin": [255, 228, 181], + "bisque": [255, 228, 196], + "mistyrose": [255, 228, 225], + "blanchedalmond": [255, 235, 205], + "papayawhip": [255, 239, 213], + "lavenderblush": [255, 240, 245], + "seashell": [255, 245, 238], + "cornsilk": [255, 248, 220], + "lemonchiffon": [255, 250, 205], + "floralwhite": [255, 250, 240], + "snow": [255, 250, 250], + "yellow": [255, 255, 0], + "lightyellow": [255, 255, 224], + "ivory": [255, 255, 240], + "white": [255, 255, 255] + }; + var color = + /*#__PURE__*/ + Object.freeze({ + fromString: fromString, + add: add, + add_: add_, + multiply: multiply, + multiply_: multiply_, + interpolate: interpolate, + lerp: lerp, + interpolateHSL: interpolateHSL, + lerpHSL: lerpHSL, + randomize: randomize, + rgb2hsl: rgb2hsl, + hsl2rgb: hsl2rgb, + toRGB: toRGB, + toHex: toHex + }); + /** + * @class Tile backend + * @private + */ + + var TileGL = + /*#__PURE__*/ + function (_Backend2) { + _inheritsLoose(TileGL, _Backend2); + + TileGL.isSupported = function isSupported() { + return !!document.createElement("canvas").getContext("webgl2", { + preserveDrawingBuffer: true + }); + }; + + function TileGL() { + var _this5; + + _this5 = _Backend2.call(this) || this; + _this5._uniforms = {}; + + try { + _this5._gl = _this5._initWebGL(); + } catch (e) { + alert(e.message); + } + + return _this5; + } + + var _proto7 = TileGL.prototype; + + _proto7.schedule = function schedule(cb) { + requestAnimationFrame(cb); + }; + + _proto7.getContainer = function getContainer() { + return this._gl.canvas; + }; + + _proto7.setOptions = function setOptions(opts) { + var _this6 = this; + + _Backend2.prototype.setOptions.call(this, opts); + + this._updateSize(); + + var tileSet = this._options.tileSet; + + if (tileSet && "complete" in tileSet && !tileSet.complete) { + tileSet.addEventListener("load", function () { + return _this6._updateTexture(tileSet); + }); + } else { + this._updateTexture(tileSet); + } + }; + + _proto7.draw = function draw(data, clearBefore) { + var gl = this._gl; + var opts = this._options; + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var scissorY = gl.canvas.height - (y + 1) * opts.tileHeight; + gl.scissor(x * opts.tileWidth, scissorY, opts.tileWidth, opts.tileHeight); + + if (clearBefore) { + if (opts.tileColorize) { + gl.clearColor(0, 0, 0, 0); + } else { + gl.clearColor.apply(gl, parseColor(bg)); + } + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + if (!ch) { + return; + } + + var chars = [].concat(ch); + var bgs = [].concat(bg); + var fgs = [].concat(fg); + gl.uniform2fv(this._uniforms["targetPosRel"], [x, y]); + + for (var i = 0; i < chars.length; i++) { + var tile = this._options.tileMap[chars[i]]; + + if (!tile) { + throw new Error("Char \"" + chars[i] + "\" not found in tileMap"); + } + + gl.uniform1f(this._uniforms["colorize"], opts.tileColorize ? 1 : 0); + gl.uniform2fv(this._uniforms["tilesetPosAbs"], tile); + + if (opts.tileColorize) { + gl.uniform4fv(this._uniforms["tint"], parseColor(fgs[i])); + gl.uniform4fv(this._uniforms["bg"], parseColor(bgs[i])); + } + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + } + /* + + + for (let i=0;i= canvas.width || y >= canvas.height) { + return [-1, -1]; + } + + return this._normalizedEventToPosition(x, y); + }; + + _proto7._initWebGL = function _initWebGL() { + var _this7 = this; + + var gl = document.createElement("canvas").getContext("webgl2", { + preserveDrawingBuffer: true + }); + window.gl = gl; + var program = createProgram(gl, VS, FS); + gl.useProgram(program); + createQuad(gl); + UNIFORMS.forEach(function (name) { + return _this7._uniforms[name] = gl.getUniformLocation(program, name); + }); + this._program = program; + gl.enable(gl.BLEND); + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + gl.enable(gl.SCISSOR_TEST); + return gl; + }; + + _proto7._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + return [Math.floor(x / this._options.tileWidth), Math.floor(y / this._options.tileHeight)]; + }; + + _proto7._updateSize = function _updateSize() { + var gl = this._gl; + var opts = this._options; + var canvasSize = [opts.width * opts.tileWidth, opts.height * opts.tileHeight]; + gl.canvas.width = canvasSize[0]; + gl.canvas.height = canvasSize[1]; + gl.viewport(0, 0, canvasSize[0], canvasSize[1]); + gl.uniform2fv(this._uniforms["tileSize"], [opts.tileWidth, opts.tileHeight]); + gl.uniform2fv(this._uniforms["targetSize"], canvasSize); + }; + + _proto7._updateTexture = function _updateTexture(tileSet) { + createTexture(this._gl, tileSet); + }; + + return TileGL; + }(Backend); + + var UNIFORMS = ["targetPosRel", "tilesetPosAbs", "tileSize", "targetSize", "colorize", "bg", "tint"]; + var VS = "\n#version 300 es\n\nin vec2 tilePosRel;\nout vec2 tilesetPosPx;\n\nuniform vec2 tilesetPosAbs;\nuniform vec2 tileSize;\nuniform vec2 targetSize;\nuniform vec2 targetPosRel;\n\nvoid main() {\n\tvec2 targetPosPx = (targetPosRel + tilePosRel) * tileSize;\n\tvec2 targetPosNdc = ((targetPosPx / targetSize)-0.5)*2.0;\n\ttargetPosNdc.y *= -1.0;\n\n\tgl_Position = vec4(targetPosNdc, 0.0, 1.0);\n\ttilesetPosPx = tilesetPosAbs + tilePosRel * tileSize;\n}".trim(); + var FS = "\n#version 300 es\nprecision highp float;\n\nin vec2 tilesetPosPx;\nout vec4 fragColor;\nuniform sampler2D image;\nuniform bool colorize;\nuniform vec4 bg;\nuniform vec4 tint;\n\nvoid main() {\n\tfragColor = vec4(0, 0, 0, 1);\n\n\tvec4 texel = texelFetch(image, ivec2(tilesetPosPx), 0);\n\n\tif (colorize) {\n\t\ttexel.rgb = tint.a * tint.rgb + (1.0-tint.a) * texel.rgb;\n\t\tfragColor.rgb = texel.a*texel.rgb + (1.0-texel.a)*bg.rgb;\n\t\tfragColor.a = texel.a + (1.0-texel.a)*bg.a;\n\t} else {\n\t\tfragColor = texel;\n\t}\n}".trim(); + + function createProgram(gl, vss, fss) { + var vs = gl.createShader(gl.VERTEX_SHADER); + gl.shaderSource(vs, vss); + gl.compileShader(vs); + + if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) { + throw new Error(gl.getShaderInfoLog(vs) || ""); + } + + var fs = gl.createShader(gl.FRAGMENT_SHADER); + gl.shaderSource(fs, fss); + gl.compileShader(fs); + + if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) { + throw new Error(gl.getShaderInfoLog(fs) || ""); + } + + var p = gl.createProgram(); + gl.attachShader(p, vs); + gl.attachShader(p, fs); + gl.linkProgram(p); + + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { + throw new Error(gl.getProgramInfoLog(p) || ""); + } + + return p; + } + + function createQuad(gl) { + var pos = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]); + var buf = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, buf); + gl.bufferData(gl.ARRAY_BUFFER, pos, gl.STATIC_DRAW); + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + } + + function createTexture(gl, data) { + var t = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, t); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, data); + return t; + } + + var colorCache = {}; + + function parseColor(color) { + if (!(color in colorCache)) { + var parsed; + + if (color == "transparent") { + parsed = [0, 0, 0, 0]; + } else if (color.indexOf("rgba") > -1) { + parsed = (color.match(/[\d.]+/g) || []).map(Number); + + for (var i = 0; i < 3; i++) { + parsed[i] = parsed[i] / 255; + } + } else { + parsed = fromString(color).map(function ($) { + return $ / 255; + }); + parsed.push(1); + } + + colorCache[color] = parsed; + } + + return colorCache[color]; + } + + function clearToAnsi(bg) { + return "\x1B[0;48;5;" + termcolor(bg) + "m\x1B[2J"; + } + + function colorToAnsi(fg, bg) { + return "\x1B[0;38;5;" + termcolor(fg) + ";48;5;" + termcolor(bg) + "m"; + } + + function positionToAnsi(x, y) { + return "\x1B[" + (y + 1) + ";" + (x + 1) + "H"; + } + + function termcolor(color) { + var SRC_COLORS = 256.0; + var DST_COLORS = 6.0; + var COLOR_RATIO = DST_COLORS / SRC_COLORS; + var rgb = fromString(color); + var r = Math.floor(rgb[0] * COLOR_RATIO); + var g = Math.floor(rgb[1] * COLOR_RATIO); + var b = Math.floor(rgb[2] * COLOR_RATIO); + return r * 36 + g * 6 + b * 1 + 16; + } + + var Term = + /*#__PURE__*/ + function (_Backend3) { + _inheritsLoose(Term, _Backend3); + + function Term() { + var _this8; + + _this8 = _Backend3.call(this) || this; + _this8._offset = [0, 0]; + _this8._cursor = [-1, -1]; + _this8._lastColor = ""; + return _this8; + } + + var _proto8 = Term.prototype; + + _proto8.schedule = function schedule(cb) { + setTimeout(cb, 1000 / 60); + }; + + _proto8.setOptions = function setOptions(options) { + _Backend3.prototype.setOptions.call(this, options); + + var size = [options.width, options.height]; + var avail = this.computeSize(); + this._offset = avail.map(function (val, index) { + return Math.floor((val - size[index]) / 2); + }); + }; + + _proto8.clear = function clear() { + process.stdout.write(clearToAnsi(this._options.bg)); + }; + + _proto8.draw = function draw(data, clearBefore) { + // determine where to draw what with what colors + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; // determine if we need to move the terminal cursor + + var dx = this._offset[0] + x; + var dy = this._offset[1] + y; + var size = this.computeSize(); + + if (dx < 0 || dx >= size[0]) { + return; + } + + if (dy < 0 || dy >= size[1]) { + return; + } + + if (dx !== this._cursor[0] || dy !== this._cursor[1]) { + process.stdout.write(positionToAnsi(dx, dy)); + this._cursor[0] = dx; + this._cursor[1] = dy; + } // terminals automatically clear, but if we're clearing when we're + // not otherwise provided with a character, just use a space instead + + + if (clearBefore) { + if (!ch) { + ch = " "; + } + } // if we're not clearing and not provided with a character, do nothing + + + if (!ch) { + return; + } // determine if we need to change colors + + + var newColor = colorToAnsi(fg, bg); + + if (newColor !== this._lastColor) { + process.stdout.write(newColor); + this._lastColor = newColor; + } // write the provided symbol to the display + + + var chars = [].concat(ch); + process.stdout.write(chars[0]); // update our position, given that we wrote a character + + this._cursor[0]++; + + if (this._cursor[0] >= size[0]) { + this._cursor[0] = 0; + this._cursor[1]++; + } + }; + + _proto8.computeFontSize = function computeFontSize() { + throw new Error("Terminal backend has no notion of font size"); + }; + + _proto8.eventToPosition = function eventToPosition(x, y) { + return [x, y]; + }; + + _proto8.computeSize = function computeSize() { + return [process.stdout.columns, process.stdout.rows]; + }; + + return Term; + }(Backend); + /** + * @namespace + * Contains text tokenization and breaking routines + */ + + + var RE_COLORS = /%([bc]){([^}]*)}/g; // token types + + var TYPE_TEXT = 0; + var TYPE_NEWLINE = 1; + var TYPE_FG = 2; + var TYPE_BG = 3; + /** + * Measure size of a resulting text block + */ + + function measure(str, maxWidth) { + var result = { + width: 0, + height: 1 + }; + var tokens = tokenize(str, maxWidth); + var lineWidth = 0; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + switch (token.type) { + case TYPE_TEXT: + lineWidth += token.value.length; + break; + + case TYPE_NEWLINE: + result.height++; + result.width = Math.max(result.width, lineWidth); + lineWidth = 0; + break; + } + } + + result.width = Math.max(result.width, lineWidth); + return result; + } + /** + * Convert string to a series of a formatting commands + */ + + + function tokenize(str, maxWidth) { + var result = []; + /* first tokenization pass - split texts and color formatting commands */ + + var offset = 0; + str.replace(RE_COLORS, function (match, type, name, index) { + /* string before */ + var part = str.substring(offset, index); + + if (part.length) { + result.push({ + type: TYPE_TEXT, + value: part + }); + } + /* color command */ + + + result.push({ + type: type == "c" ? TYPE_FG : TYPE_BG, + value: name.trim() + }); + offset = index + match.length; + return ""; + }); + /* last remaining part */ + + var part = str.substring(offset); + + if (part.length) { + result.push({ + type: TYPE_TEXT, + value: part + }); + } + + return breakLines(result, maxWidth); + } + /* insert line breaks into first-pass tokenized data */ + + + function breakLines(tokens, maxWidth) { + if (!maxWidth) { + maxWidth = Infinity; + } + + var i = 0; + var lineLength = 0; + var lastTokenWithSpace = -1; + + while (i < tokens.length) { + /* take all text tokens, remove space, apply linebreaks */ + var token = tokens[i]; + + if (token.type == TYPE_NEWLINE) { + /* reset */ + lineLength = 0; + lastTokenWithSpace = -1; + } + + if (token.type != TYPE_TEXT) { + /* skip non-text tokens */ + i++; + continue; + } + /* remove spaces at the beginning of line */ + + + while (lineLength == 0 && token.value.charAt(0) == " ") { + token.value = token.value.substring(1); + } + /* forced newline? insert two new tokens after this one */ + + + var _index2 = token.value.indexOf("\n"); + + if (_index2 != -1) { + token.value = breakInsideToken(tokens, i, _index2, true); + /* if there are spaces at the end, we must remove them (we do not want the line too long) */ + + var arr = token.value.split(""); + + while (arr.length && arr[arr.length - 1] == " ") { + arr.pop(); + } + + token.value = arr.join(""); + } + /* token degenerated? */ + + + if (!token.value.length) { + tokens.splice(i, 1); + continue; + } + + if (lineLength + token.value.length > maxWidth) { + /* line too long, find a suitable breaking spot */ + + /* is it possible to break within this token? */ + var _index3 = -1; + + while (1) { + var nextIndex = token.value.indexOf(" ", _index3 + 1); + + if (nextIndex == -1) { + break; + } + + if (lineLength + nextIndex > maxWidth) { + break; + } + + _index3 = nextIndex; + } + + if (_index3 != -1) { + /* break at space within this one */ + token.value = breakInsideToken(tokens, i, _index3, true); + } else if (lastTokenWithSpace != -1) { + /* is there a previous token where a break can occur? */ + var _token = tokens[lastTokenWithSpace]; + + var breakIndex = _token.value.lastIndexOf(" "); + + _token.value = breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true); + i = lastTokenWithSpace; + } else { + /* force break in this token */ + token.value = breakInsideToken(tokens, i, maxWidth - lineLength, false); + } + } else { + /* line not long, continue */ + lineLength += token.value.length; + + if (token.value.indexOf(" ") != -1) { + lastTokenWithSpace = i; + } + } + + i++; + /* advance to next token */ + } + + tokens.push({ + type: TYPE_NEWLINE + }); + /* insert fake newline to fix the last text line */ + + /* remove trailing space from text tokens before newlines */ + + var lastTextToken = null; + + for (var _i = 0; _i < tokens.length; _i++) { + var _token2 = tokens[_i]; + + switch (_token2.type) { + case TYPE_TEXT: + lastTextToken = _token2; + break; + + case TYPE_NEWLINE: + if (lastTextToken) { + /* remove trailing space */ + var _arr = lastTextToken.value.split(""); + + while (_arr.length && _arr[_arr.length - 1] == " ") { + _arr.pop(); + } + + lastTextToken.value = _arr.join(""); + } + + lastTextToken = null; + break; + } + } + + tokens.pop(); + /* remove fake token */ + + return tokens; + } + /** + * Create new tokens and insert them into the stream + * @param {object[]} tokens + * @param {int} tokenIndex Token being processed + * @param {int} breakIndex Index within current token's value + * @param {bool} removeBreakChar Do we want to remove the breaking character? + * @returns {string} remaining unbroken token value + */ + + + function breakInsideToken(tokens, tokenIndex, breakIndex, removeBreakChar) { + var newBreakToken = { + type: TYPE_NEWLINE + }; + var newTextToken = { + type: TYPE_TEXT, + value: tokens[tokenIndex].value.substring(breakIndex + (removeBreakChar ? 1 : 0)) + }; + tokens.splice(tokenIndex + 1, 0, newBreakToken, newTextToken); + return tokens[tokenIndex].value.substring(0, breakIndex); + } + + var text = + /*#__PURE__*/ + Object.freeze({ + TYPE_TEXT: TYPE_TEXT, + TYPE_NEWLINE: TYPE_NEWLINE, + TYPE_FG: TYPE_FG, + TYPE_BG: TYPE_BG, + measure: measure, + tokenize: tokenize + }); + /** Default with for display and map generators */ + + var DEFAULT_WIDTH = 80; + /** Default height for display and map generators */ + + var DEFAULT_HEIGHT = 25; + var DIRS = { + 4: [[0, -1], [1, 0], [0, 1], [-1, 0]], + 8: [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1]], + 6: [[-1, -1], [1, -1], [2, 0], [1, 1], [-1, 1], [-2, 0]] + }; + var KEYS = { + /** Cancel key. */ + VK_CANCEL: 3, + + /** Help key. */ + VK_HELP: 6, + + /** Backspace key. */ + VK_BACK_SPACE: 8, + + /** Tab key. */ + VK_TAB: 9, + + /** 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. */ + VK_CLEAR: 12, + + /** Return/enter key on the main keyboard. */ + VK_RETURN: 13, + + /** Reserved, but not used. */ + VK_ENTER: 14, + + /** Shift key. */ + VK_SHIFT: 16, + + /** Control key. */ + VK_CONTROL: 17, + + /** Alt (Option on Mac) key. */ + VK_ALT: 18, + + /** Pause key. */ + VK_PAUSE: 19, + + /** Caps lock. */ + VK_CAPS_LOCK: 20, + + /** Escape key. */ + VK_ESCAPE: 27, + + /** Space bar. */ + VK_SPACE: 32, + + /** Page Up key. */ + VK_PAGE_UP: 33, + + /** Page Down key. */ + VK_PAGE_DOWN: 34, + + /** End key. */ + VK_END: 35, + + /** Home key. */ + VK_HOME: 36, + + /** Left arrow. */ + VK_LEFT: 37, + + /** Up arrow. */ + VK_UP: 38, + + /** Right arrow. */ + VK_RIGHT: 39, + + /** Down arrow. */ + VK_DOWN: 40, + + /** Print Screen key. */ + VK_PRINTSCREEN: 44, + + /** Ins(ert) key. */ + VK_INSERT: 45, + + /** Del(ete) key. */ + VK_DELETE: 46, + + /***/ + VK_0: 48, + + /***/ + VK_1: 49, + + /***/ + VK_2: 50, + + /***/ + VK_3: 51, + + /***/ + VK_4: 52, + + /***/ + VK_5: 53, + + /***/ + VK_6: 54, + + /***/ + VK_7: 55, + + /***/ + VK_8: 56, + + /***/ + VK_9: 57, + + /** Colon (:) key. Requires Gecko 15.0 */ + VK_COLON: 58, + + /** Semicolon (;) key. */ + VK_SEMICOLON: 59, + + /** Less-than (<) key. Requires Gecko 15.0 */ + VK_LESS_THAN: 60, + + /** Equals (=) key. */ + VK_EQUALS: 61, + + /** Greater-than (>) key. Requires Gecko 15.0 */ + VK_GREATER_THAN: 62, + + /** Question mark (?) key. Requires Gecko 15.0 */ + VK_QUESTION_MARK: 63, + + /** Atmark (@) key. Requires Gecko 15.0 */ + VK_AT: 64, + + /***/ + VK_A: 65, + + /***/ + VK_B: 66, + + /***/ + VK_C: 67, + + /***/ + VK_D: 68, + + /***/ + VK_E: 69, + + /***/ + VK_F: 70, + + /***/ + VK_G: 71, + + /***/ + VK_H: 72, + + /***/ + VK_I: 73, + + /***/ + VK_J: 74, + + /***/ + VK_K: 75, + + /***/ + VK_L: 76, + + /***/ + VK_M: 77, + + /***/ + VK_N: 78, + + /***/ + VK_O: 79, + + /***/ + VK_P: 80, + + /***/ + VK_Q: 81, + + /***/ + VK_R: 82, + + /***/ + VK_S: 83, + + /***/ + VK_T: 84, + + /***/ + VK_U: 85, + + /***/ + VK_V: 86, + + /***/ + VK_W: 87, + + /***/ + VK_X: 88, + + /***/ + VK_Y: 89, + + /***/ + VK_Z: 90, + + /***/ + VK_CONTEXT_MENU: 93, + + /** 0 on the numeric keypad. */ + VK_NUMPAD0: 96, + + /** 1 on the numeric keypad. */ + VK_NUMPAD1: 97, + + /** 2 on the numeric keypad. */ + VK_NUMPAD2: 98, + + /** 3 on the numeric keypad. */ + VK_NUMPAD3: 99, + + /** 4 on the numeric keypad. */ + VK_NUMPAD4: 100, + + /** 5 on the numeric keypad. */ + VK_NUMPAD5: 101, + + /** 6 on the numeric keypad. */ + VK_NUMPAD6: 102, + + /** 7 on the numeric keypad. */ + VK_NUMPAD7: 103, + + /** 8 on the numeric keypad. */ + VK_NUMPAD8: 104, + + /** 9 on the numeric keypad. */ + VK_NUMPAD9: 105, + + /** * on the numeric keypad. */ + VK_MULTIPLY: 106, + + /** + on the numeric keypad. */ + VK_ADD: 107, + + /***/ + VK_SEPARATOR: 108, + + /** - on the numeric keypad. */ + VK_SUBTRACT: 109, + + /** Decimal point on the numeric keypad. */ + VK_DECIMAL: 110, + + /** / on the numeric keypad. */ + VK_DIVIDE: 111, + + /** F1 key. */ + VK_F1: 112, + + /** F2 key. */ + VK_F2: 113, + + /** F3 key. */ + VK_F3: 114, + + /** F4 key. */ + VK_F4: 115, + + /** F5 key. */ + VK_F5: 116, + + /** F6 key. */ + VK_F6: 117, + + /** F7 key. */ + VK_F7: 118, + + /** F8 key. */ + VK_F8: 119, + + /** F9 key. */ + VK_F9: 120, + + /** F10 key. */ + VK_F10: 121, + + /** F11 key. */ + VK_F11: 122, + + /** F12 key. */ + VK_F12: 123, + + /** F13 key. */ + VK_F13: 124, + + /** F14 key. */ + VK_F14: 125, + + /** F15 key. */ + VK_F15: 126, + + /** F16 key. */ + VK_F16: 127, + + /** F17 key. */ + VK_F17: 128, + + /** F18 key. */ + VK_F18: 129, + + /** F19 key. */ + VK_F19: 130, + + /** F20 key. */ + VK_F20: 131, + + /** F21 key. */ + VK_F21: 132, + + /** F22 key. */ + VK_F22: 133, + + /** F23 key. */ + VK_F23: 134, + + /** F24 key. */ + VK_F24: 135, + + /** Num Lock key. */ + VK_NUM_LOCK: 144, + + /** Scroll Lock key. */ + VK_SCROLL_LOCK: 145, + + /** Circumflex (^) key. Requires Gecko 15.0 */ + VK_CIRCUMFLEX: 160, + + /** Exclamation (!) key. Requires Gecko 15.0 */ + VK_EXCLAMATION: 161, + + /** Double quote () key. Requires Gecko 15.0 */ + VK_DOUBLE_QUOTE: 162, + + /** Hash (#) key. Requires Gecko 15.0 */ + VK_HASH: 163, + + /** Dollar sign ($) key. Requires Gecko 15.0 */ + VK_DOLLAR: 164, + + /** Percent (%) key. Requires Gecko 15.0 */ + VK_PERCENT: 165, + + /** Ampersand (&) key. Requires Gecko 15.0 */ + VK_AMPERSAND: 166, + + /** Underscore (_) key. Requires Gecko 15.0 */ + VK_UNDERSCORE: 167, + + /** Open parenthesis (() key. Requires Gecko 15.0 */ + VK_OPEN_PAREN: 168, + + /** Close parenthesis ()) key. Requires Gecko 15.0 */ + VK_CLOSE_PAREN: 169, + + /* Asterisk (*) key. Requires Gecko 15.0 */ + VK_ASTERISK: 170, + + /** Plus (+) key. Requires Gecko 15.0 */ + VK_PLUS: 171, + + /** Pipe (|) key. Requires Gecko 15.0 */ + VK_PIPE: 172, + + /** Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 */ + VK_HYPHEN_MINUS: 173, + + /** Open curly bracket ({) key. Requires Gecko 15.0 */ + VK_OPEN_CURLY_BRACKET: 174, + + /** Close curly bracket (}) key. Requires Gecko 15.0 */ + VK_CLOSE_CURLY_BRACKET: 175, + + /** Tilde (~) key. Requires Gecko 15.0 */ + VK_TILDE: 176, + + /** Comma (,) key. */ + VK_COMMA: 188, + + /** Period (.) key. */ + VK_PERIOD: 190, + + /** Slash (/) key. */ + VK_SLASH: 191, + + /** Back tick (`) key. */ + VK_BACK_QUOTE: 192, + + /** Open square bracket ([) key. */ + VK_OPEN_BRACKET: 219, + + /** Back slash (\) key. */ + VK_BACK_SLASH: 220, + + /** Close square bracket (]) key. */ + VK_CLOSE_BRACKET: 221, + + /** Quote (''') key. */ + VK_QUOTE: 222, + + /** Meta key on Linux, Command key on Mac. */ + VK_META: 224, + + /** AltGr key on Linux. Requires Gecko 15.0 */ + VK_ALTGR: 225, + + /** Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 */ + VK_WIN: 91, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANA: 21, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANGUL: 21, + + /** 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 */ + VK_EISU: 22, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_JUNJA: 23, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_FINAL: 24, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANJA: 25, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANJI: 25, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_CONVERT: 28, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_NONCONVERT: 29, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_ACCEPT: 30, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_MODECHANGE: 31, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SELECT: 41, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_PRINT: 42, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_EXECUTE: 43, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SLEEP: 95 + }; + var BACKENDS = { + "hex": Hex, + "rect": Rect, + "tile": Tile, + "tile-gl": TileGL, + "term": Term + }; + var DEFAULT_OPTIONS = { + width: DEFAULT_WIDTH, + height: DEFAULT_HEIGHT, + transpose: false, + layout: "rect", + fontSize: 15, + spacing: 1, + border: 0, + forceSquareRatio: false, + fontFamily: "monospace", + fontStyle: "", + fg: "#ccc", + bg: "#000", + tileWidth: 32, + tileHeight: 32, + tileMap: {}, + tileSet: null, + tileColorize: false + }; + /** + * @class Visual map display + */ + + var Display = + /*#__PURE__*/ + function () { + function Display(options) { + if (options === void 0) { + options = {}; + } + + this._data = {}; + this._dirty = false; // false = nothing, true = all, object = dirty cells + + this._options = {}; + options = Object.assign({}, DEFAULT_OPTIONS, options); + this.setOptions(options); + this.DEBUG = this.DEBUG.bind(this); + this._tick = this._tick.bind(this); + + this._backend.schedule(this._tick); + } + /** + * Debug helper, ideal as a map generator callback. Always bound to this. + * @param {int} x + * @param {int} y + * @param {int} what + */ + + + var _proto9 = Display.prototype; + + _proto9.DEBUG = function DEBUG(x, y, what) { + var colors = [this._options.bg, this._options.fg]; + this.draw(x, y, null, null, colors[what % colors.length]); + }; + /** + * Clear the whole display (cover it with background color) + */ + + + _proto9.clear = function clear() { + this._data = {}; + this._dirty = true; + }; + /** + * @see ROT.Display + */ + + + _proto9.setOptions = function setOptions(options) { + Object.assign(this._options, options); + + if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) { + if (options.layout) { + var ctor = BACKENDS[options.layout]; + this._backend = new ctor(); + } + + this._backend.setOptions(this._options); + + this._dirty = true; + } + + return this; + }; + /** + * Returns currently set options + */ + + + _proto9.getOptions = function getOptions() { + return this._options; + }; + /** + * Returns the DOM node of this display + */ + + + _proto9.getContainer = function getContainer() { + return this._backend.getContainer(); + }; + /** + * Compute the maximum width/height to fit into a set of given constraints + * @param {int} availWidth Maximum allowed pixel width + * @param {int} availHeight Maximum allowed pixel height + * @returns {int[2]} cellWidth,cellHeight + */ + + + _proto9.computeSize = function computeSize(availWidth, availHeight) { + return this._backend.computeSize(availWidth, availHeight); + }; + /** + * Compute the maximum font size to fit into a set of given constraints + * @param {int} availWidth Maximum allowed pixel width + * @param {int} availHeight Maximum allowed pixel height + * @returns {int} fontSize + */ + + + _proto9.computeFontSize = function computeFontSize(availWidth, availHeight) { + return this._backend.computeFontSize(availWidth, availHeight); + }; + + _proto9.computeTileSize = function computeTileSize(availWidth, availHeight) { + var width = Math.floor(availWidth / this._options.width); + var height = Math.floor(availHeight / this._options.height); + return [width, height]; + }; + /** + * Convert a DOM event (mouse or touch) to map coordinates. Uses first touch for multi-touch. + * @param {Event} e event + * @returns {int[2]} -1 for values outside of the canvas + */ + + + _proto9.eventToPosition = function eventToPosition(e) { + var x, y; + + if ("touches" in e) { + x = e.touches[0].clientX; + y = e.touches[0].clientY; + } else { + x = e.clientX; + y = e.clientY; + } + + return this._backend.eventToPosition(x, y); + }; + /** + * @param {int} x + * @param {int} y + * @param {string || string[]} ch One or more chars (will be overlapping themselves) + * @param {string} [fg] foreground color + * @param {string} [bg] background color + */ + + + _proto9.draw = function draw(x, y, ch, fg, bg) { + if (!fg) { + fg = this._options.fg; + } + + if (!bg) { + bg = this._options.bg; + } + + var key = x + "," + y; + this._data[key] = [x, y, ch, fg, bg]; + + if (this._dirty === true) { + return; + } // will already redraw everything + + + if (!this._dirty) { + this._dirty = {}; + } // first! + + + this._dirty[key] = true; + }; + /** + * Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout. + * @param {int} x + * @param {int} y + * @param {string} text May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default. + * @param {int} [maxWidth] wrap at what width? + * @returns {int} lines drawn + */ + + + _proto9.drawText = function drawText(x, y, text, maxWidth) { + var fg = null; + var bg = null; + var cx = x; + var cy = y; + var lines = 1; + + if (!maxWidth) { + maxWidth = this._options.width - x; + } + + var tokens = tokenize(text, maxWidth); + + while (tokens.length) { + // interpret tokenized opcode stream + var token = tokens.shift(); + + switch (token.type) { + case TYPE_TEXT: + var isSpace = false, + isPrevSpace = false, + isFullWidth = false, + isPrevFullWidth = false; + + for (var i = 0; i < token.value.length; i++) { + var cc = token.value.charCodeAt(i); + var c = token.value.charAt(i); // Assign to `true` when the current char is full-width. + + isFullWidth = cc > 0xff00 && cc < 0xff61 || cc > 0xffdc && cc < 0xffe8 || cc > 0xffee; // Current char is space, whatever full-width or half-width both are OK. + + isSpace = c.charCodeAt(0) == 0x20 || c.charCodeAt(0) == 0x3000; // The previous char is full-width and + // current char is nether half-width nor a space. + + if (isPrevFullWidth && !isFullWidth && !isSpace) { + cx++; + } // add an extra position + // The current char is full-width and + // the previous char is not a space. + + + if (isFullWidth && !isPrevSpace) { + cx++; + } // add an extra position + + + this.draw(cx++, cy, c, fg, bg); + isPrevSpace = isSpace; + isPrevFullWidth = isFullWidth; + } + + break; + + case TYPE_FG: + fg = token.value || null; + break; + + case TYPE_BG: + bg = token.value || null; + break; + + case TYPE_NEWLINE: + cx = x; + cy++; + lines++; + break; + } + } + + return lines; + }; + /** + * Timer tick: update dirty parts + */ + + + _proto9._tick = function _tick() { + this._backend.schedule(this._tick); + + if (!this._dirty) { + return; + } + + if (this._dirty === true) { + // draw all + this._backend.clear(); + + for (var id in this._data) { + this._draw(id, false); + } // redraw cached data + + } else { + // draw only dirty + for (var key in this._dirty) { + this._draw(key, true); + } + } + + this._dirty = false; + }; + /** + * @param {string} key What to draw + * @param {bool} clearBefore Is it necessary to clean before? + */ + + + _proto9._draw = function _draw(key, clearBefore) { + var data = this._data[key]; + + if (data[4] != this._options.bg) { + clearBefore = true; + } + + this._backend.draw(data, clearBefore); + }; + + return Display; + }(); + + Display.Rect = Rect; + Display.Hex = Hex; + Display.Tile = Tile; + Display.TileGL = TileGL; + Display.Term = Term; + /** + * @class (Markov process)-based string generator. + * Copied from a RogueBasin article. + * Offers configurable order and prior. + */ + + var StringGenerator = + /*#__PURE__*/ + function () { + function StringGenerator(options) { + this._options = { + words: false, + order: 3, + prior: 0.001 + }; + Object.assign(this._options, options); + this._boundary = String.fromCharCode(0); + this._suffix = this._boundary; + this._prefix = []; + + for (var i = 0; i < this._options.order; i++) { + this._prefix.push(this._boundary); + } + + this._priorValues = {}; + this._priorValues[this._boundary] = this._options.prior; + this._data = {}; + } + /** + * Remove all learning data + */ + + + var _proto10 = StringGenerator.prototype; + + _proto10.clear = function clear() { + this._data = {}; + this._priorValues = {}; + }; + /** + * @returns {string} Generated string + */ + + + _proto10.generate = function generate() { + var result = [this._sample(this._prefix)]; + + while (result[result.length - 1] != this._boundary) { + result.push(this._sample(result)); + } + + return this._join(result.slice(0, -1)); + }; + /** + * Observe (learn) a string from a training set + */ + + + _proto10.observe = function observe(string) { + var tokens = this._split(string); + + for (var i = 0; i < tokens.length; i++) { + this._priorValues[tokens[i]] = this._options.prior; + } + + tokens = this._prefix.concat(tokens).concat(this._suffix); + /* add boundary symbols */ + + for (var _i2 = this._options.order; _i2 < tokens.length; _i2++) { + var context = tokens.slice(_i2 - this._options.order, _i2); + var event = tokens[_i2]; + + for (var j = 0; j < context.length; j++) { + var subcontext = context.slice(j); + + this._observeEvent(subcontext, event); + } + } + }; + + _proto10.getStats = function getStats() { + var parts = []; + var priorCount = Object.keys(this._priorValues).length; + priorCount--; // boundary + + parts.push("distinct samples: " + priorCount); + var dataCount = Object.keys(this._data).length; + var eventCount = 0; + + for (var p in this._data) { + eventCount += Object.keys(this._data[p]).length; + } + + parts.push("dictionary size (contexts): " + dataCount); + parts.push("dictionary size (events): " + eventCount); + return parts.join(", "); + }; + /** + * @param {string} + * @returns {string[]} + */ + + + _proto10._split = function _split(str) { + return str.split(this._options.words ? /\s+/ : ""); + }; + /** + * @param {string[]} + * @returns {string} + */ + + + _proto10._join = function _join(arr) { + return arr.join(this._options.words ? " " : ""); + }; + /** + * @param {string[]} context + * @param {string} event + */ + + + _proto10._observeEvent = function _observeEvent(context, event) { + var key = this._join(context); + + if (!(key in this._data)) { + this._data[key] = {}; + } + + var data = this._data[key]; + + if (!(event in data)) { + data[event] = 0; + } + + data[event]++; + }; + /** + * @param {string[]} + * @returns {string} + */ + + + _proto10._sample = function _sample(context) { + context = this._backoff(context); + + var key = this._join(context); + + var data = this._data[key]; + var available = {}; + + if (this._options.prior) { + for (var event in this._priorValues) { + available[event] = this._priorValues[event]; + } + + for (var _event in data) { + available[_event] += data[_event]; + } + } else { + available = data; + } + + return RNG$1.getWeightedValue(available); + }; + /** + * @param {string[]} + * @returns {string[]} + */ + + + _proto10._backoff = function _backoff(context) { + if (context.length > this._options.order) { + context = context.slice(-this._options.order); + } else if (context.length < this._options.order) { + context = this._prefix.slice(0, this._options.order - context.length).concat(context); + } + + while (!(this._join(context) in this._data) && context.length > 0) { + context = context.slice(1); + } + + return context; + }; + + return StringGenerator; + }(); + + var EventQueue = + /*#__PURE__*/ + function () { + /** + * @class Generic event queue: stores events and retrieves them based on their time + */ + function EventQueue() { + this._time = 0; + this._events = []; + this._eventTimes = []; + } + /** + * @returns {number} Elapsed time + */ + + + var _proto11 = EventQueue.prototype; + + _proto11.getTime = function getTime() { + return this._time; + }; + /** + * Clear all scheduled events + */ + + + _proto11.clear = function clear() { + this._events = []; + this._eventTimes = []; + return this; + }; + /** + * @param {?} event + * @param {number} time + */ + + + _proto11.add = function add(event, time) { + var index = this._events.length; + + for (var i = 0; i < this._eventTimes.length; i++) { + if (this._eventTimes[i] > time) { + index = i; + break; + } + } + + this._events.splice(index, 0, event); + + this._eventTimes.splice(index, 0, time); + }; + /** + * Locates the nearest event, advances time if necessary. Returns that event and removes it from the queue. + * @returns {? || null} The event previously added by addEvent, null if no event available + */ + + + _proto11.get = function get() { + if (!this._events.length) { + return null; + } + + var time = this._eventTimes.splice(0, 1)[0]; + + if (time > 0) { + /* advance */ + this._time += time; + + for (var i = 0; i < this._eventTimes.length; i++) { + this._eventTimes[i] -= time; + } + } + + return this._events.splice(0, 1)[0]; + }; + /** + * Get the time associated with the given event + * @param {?} event + * @returns {number} time + */ + + + _proto11.getEventTime = function getEventTime(event) { + var index = this._events.indexOf(event); + + if (index == -1) { + return undefined; + } + + return this._eventTimes[index]; + }; + /** + * Remove an event from the queue + * @param {?} event + * @returns {bool} success? + */ + + + _proto11.remove = function remove(event) { + var index = this._events.indexOf(event); + + if (index == -1) { + return false; + } + + this._remove(index); + + return true; + }; + + /** + * Remove an event from the queue + * @param {int} index + */ + _proto11._remove = function _remove(index) { + this._events.splice(index, 1); + + this._eventTimes.splice(index, 1); + }; + + return EventQueue; + }(); + + var Scheduler = + /*#__PURE__*/ + function () { + /** + * @class Abstract scheduler + */ + function Scheduler() { + this._queue = new EventQueue(); + this._repeat = []; + this._current = null; + } + /** + * @see ROT.EventQueue#getTime + */ + + + var _proto12 = Scheduler.prototype; + + _proto12.getTime = function getTime() { + return this._queue.getTime(); + }; + /** + * @param {?} item + * @param {bool} repeat + */ + + + _proto12.add = function add(item, repeat) { + if (repeat) { + this._repeat.push(item); + } + + return this; + }; + /** + * Get the time the given item is scheduled for + * @param {?} item + * @returns {number} time + */ + + + _proto12.getTimeOf = function getTimeOf(item) { + return this._queue.getEventTime(item); + }; + /** + * Clear all items + */ + + + _proto12.clear = function clear() { + this._queue.clear(); + + this._repeat = []; + this._current = null; + return this; + }; + /** + * Remove a previously added item + * @param {?} item + * @returns {bool} successful? + */ + + + _proto12.remove = function remove(item) { + var result = this._queue.remove(item); + + var index = this._repeat.indexOf(item); + + if (index != -1) { + this._repeat.splice(index, 1); + } + + if (this._current == item) { + this._current = null; + } + + return result; + }; + /** + * Schedule next item + * @returns {?} + */ + + + _proto12.next = function next() { + this._current = this._queue.get(); + return this._current; + }; + + return Scheduler; + }(); + /** + * @class Simple fair scheduler (round-robin style) + */ + + + var Simple = + /*#__PURE__*/ + function (_Scheduler) { + _inheritsLoose(Simple, _Scheduler); + + function Simple() { + return _Scheduler.apply(this, arguments) || this; + } + + var _proto13 = Simple.prototype; + + _proto13.add = function add(item, repeat) { + this._queue.add(item, 0); + + return _Scheduler.prototype.add.call(this, item, repeat); + }; + + _proto13.next = function next() { + if (this._current !== null && this._repeat.indexOf(this._current) != -1) { + this._queue.add(this._current, 0); + } + + return _Scheduler.prototype.next.call(this); + }; + + return Simple; + }(Scheduler); + /** + * @class Speed-based scheduler + */ + + + var Speed = + /*#__PURE__*/ + function (_Scheduler2) { + _inheritsLoose(Speed, _Scheduler2); + + function Speed() { + return _Scheduler2.apply(this, arguments) || this; + } + + var _proto14 = Speed.prototype; + + /** + * @param {object} item anything with "getSpeed" method + * @param {bool} repeat + * @param {number} [time=1/item.getSpeed()] + * @see ROT.Scheduler#add + */ + _proto14.add = function add(item, repeat, time) { + this._queue.add(item, time !== undefined ? time : 1 / item.getSpeed()); + + return _Scheduler2.prototype.add.call(this, item, repeat); + }; + /** + * @see ROT.Scheduler#next + */ + + + _proto14.next = function next() { + if (this._current && this._repeat.indexOf(this._current) != -1) { + this._queue.add(this._current, 1 / this._current.getSpeed()); + } + + return _Scheduler2.prototype.next.call(this); + }; + + return Speed; + }(Scheduler); + /** + * @class Action-based scheduler + * @augments ROT.Scheduler + */ + + + var Action = + /*#__PURE__*/ + function (_Scheduler3) { + _inheritsLoose(Action, _Scheduler3); + + function Action() { + var _this9; + + _this9 = _Scheduler3.call(this) || this; + _this9._defaultDuration = 1; + /* for newly added */ + + _this9._duration = _this9._defaultDuration; + /* for this._current */ + + return _this9; + } + /** + * @param {object} item + * @param {bool} repeat + * @param {number} [time=1] + * @see ROT.Scheduler#add + */ + + + var _proto15 = Action.prototype; + + _proto15.add = function add(item, repeat, time) { + this._queue.add(item, time || this._defaultDuration); + + return _Scheduler3.prototype.add.call(this, item, repeat); + }; + + _proto15.clear = function clear() { + this._duration = this._defaultDuration; + return _Scheduler3.prototype.clear.call(this); + }; + + _proto15.remove = function remove(item) { + if (item == this._current) { + this._duration = this._defaultDuration; + } + + return _Scheduler3.prototype.remove.call(this, item); + }; + /** + * @see ROT.Scheduler#next + */ + + + _proto15.next = function next() { + if (this._current !== null && this._repeat.indexOf(this._current) != -1) { + this._queue.add(this._current, this._duration || this._defaultDuration); + + this._duration = this._defaultDuration; + } + + return _Scheduler3.prototype.next.call(this); + }; + /** + * Set duration for the active item + */ + + + _proto15.setDuration = function setDuration(time) { + if (this._current) { + this._duration = time; + } + + return this; + }; + + return Action; + }(Scheduler); + + var index = { + Simple: Simple, + Speed: Speed, + Action: Action + }; + + var FOV = + /*#__PURE__*/ + function () { + /** + * @class Abstract FOV algorithm + * @param {function} lightPassesCallback Does the light pass through x,y? + * @param {object} [options] + * @param {int} [options.topology=8] 4/6/8 + */ + function FOV(lightPassesCallback, options) { + if (options === void 0) { + options = {}; + } + + this._lightPasses = lightPassesCallback; + this._options = Object.assign({ + topology: 8 + }, options); + } + /** + * Return all neighbors in a concentric ring + * @param {int} cx center-x + * @param {int} cy center-y + * @param {int} r range + */ + + + var _proto16 = FOV.prototype; + + _proto16._getCircle = function _getCircle(cx, cy, r) { + var result = []; + var dirs, countFactor, startOffset; + + switch (this._options.topology) { + case 4: + countFactor = 1; + startOffset = [0, 1]; + dirs = [DIRS[8][7], DIRS[8][1], DIRS[8][3], DIRS[8][5]]; + break; + + case 6: + dirs = DIRS[6]; + countFactor = 1; + startOffset = [-1, 1]; + break; + + case 8: + dirs = DIRS[4]; + countFactor = 2; + startOffset = [-1, 1]; + break; + + default: + throw new Error("Incorrect topology for FOV computation"); + break; + } + /* starting neighbor */ + + + var x = cx + startOffset[0] * r; + var y = cy + startOffset[1] * r; + /* circle */ + + for (var i = 0; i < dirs.length; i++) { + for (var j = 0; j < r * countFactor; j++) { + result.push([x, y]); + x += dirs[i][0]; + y += dirs[i][1]; + } + } + + return result; + }; + + return FOV; + }(); + /** + * @class Discrete shadowcasting algorithm. Obsoleted by Precise shadowcasting. + * @augments ROT.FOV + */ + + + var DiscreteShadowcasting = + /*#__PURE__*/ + function (_FOV) { + _inheritsLoose(DiscreteShadowcasting, _FOV); + + function DiscreteShadowcasting() { + return _FOV.apply(this, arguments) || this; + } + + var _proto17 = DiscreteShadowcasting.prototype; + + _proto17.compute = function compute(x, y, R, callback) { + /* this place is always visible */ + callback(x, y, 0, 1); + /* standing in a dark place. FIXME is this a good idea? */ + + if (!this._lightPasses(x, y)) { + return; + } + /* start and end angles */ + + + var DATA = []; + var A, B, cx, cy, blocks; + /* analyze surrounding cells in concentric rings, starting from the center */ + + for (var r = 1; r <= R; r++) { + var neighbors = this._getCircle(x, y, r); + + var angle = 360 / neighbors.length; + + for (var i = 0; i < neighbors.length; i++) { + cx = neighbors[i][0]; + cy = neighbors[i][1]; + A = angle * (i - 0.5); + B = A + angle; + blocks = !this._lightPasses(cx, cy); + + if (this._visibleCoords(Math.floor(A), Math.ceil(B), blocks, DATA)) { + callback(cx, cy, r, 1); + } + + if (DATA.length == 2 && DATA[0] == 0 && DATA[1] == 360) { + return; + } + /* cutoff? */ + + } + /* for all cells in this ring */ + + } + /* for all rings */ + + }; + /** + * @param {int} A start angle + * @param {int} B end angle + * @param {bool} blocks Does current cell block visibility? + * @param {int[][]} DATA shadowed angle pairs + */ + + + _proto17._visibleCoords = function _visibleCoords(A, B, blocks, DATA) { + if (A < 0) { + var v1 = this._visibleCoords(0, B, blocks, DATA); + + var v2 = this._visibleCoords(360 + A, 360, blocks, DATA); + + return v1 || v2; + } + + var index = 0; + + while (index < DATA.length && DATA[index] < A) { + index++; + } + + if (index == DATA.length) { + /* completely new shadow */ + if (blocks) { + DATA.push(A, B); + } + + return true; + } + + var count = 0; + + if (index % 2) { + /* this shadow starts in an existing shadow, or within its ending boundary */ + while (index < DATA.length && DATA[index] < B) { + index++; + count++; + } + + if (count == 0) { + return false; + } + + if (blocks) { + if (count % 2) { + DATA.splice(index - count, count, B); + } else { + DATA.splice(index - count, count); + } + } + + return true; + } else { + /* this shadow starts outside an existing shadow, or within a starting boundary */ + while (index < DATA.length && DATA[index] < B) { + index++; + count++; + } + /* visible when outside an existing shadow, or when overlapping */ + + + if (A == DATA[index - count] && count == 1) { + return false; + } + + if (blocks) { + if (count % 2) { + DATA.splice(index - count, count, A); + } else { + DATA.splice(index - count, count, A, B); + } + } + + return true; + } + }; + + return DiscreteShadowcasting; + }(FOV); + /** + * @class Precise shadowcasting algorithm + * @augments ROT.FOV + */ + + + var PreciseShadowcasting = + /*#__PURE__*/ + function (_FOV2) { + _inheritsLoose(PreciseShadowcasting, _FOV2); + + function PreciseShadowcasting() { + return _FOV2.apply(this, arguments) || this; + } + + var _proto18 = PreciseShadowcasting.prototype; + + _proto18.compute = function compute(x, y, R, callback) { + /* this place is always visible */ + callback(x, y, 0, 1); + /* standing in a dark place. FIXME is this a good idea? */ + + if (!this._lightPasses(x, y)) { + return; + } + /* list of all shadows */ + + + var SHADOWS = []; + var cx, cy, blocks, A1, A2, visibility; + /* analyze surrounding cells in concentric rings, starting from the center */ + + for (var r = 1; r <= R; r++) { + var neighbors = this._getCircle(x, y, r); + + var neighborCount = neighbors.length; + + for (var i = 0; i < neighborCount; i++) { + cx = neighbors[i][0]; + cy = neighbors[i][1]; + /* shift half-an-angle backwards to maintain consistency of 0-th cells */ + + A1 = [i ? 2 * i - 1 : 2 * neighborCount - 1, 2 * neighborCount]; + A2 = [2 * i + 1, 2 * neighborCount]; + blocks = !this._lightPasses(cx, cy); + visibility = this._checkVisibility(A1, A2, blocks, SHADOWS); + + if (visibility) { + callback(cx, cy, r, visibility); + } + + if (SHADOWS.length == 2 && SHADOWS[0][0] == 0 && SHADOWS[1][0] == SHADOWS[1][1]) { + return; + } + /* cutoff? */ + + } + /* for all cells in this ring */ + + } + /* for all rings */ + + }; + /** + * @param {int[2]} A1 arc start + * @param {int[2]} A2 arc end + * @param {bool} blocks Does current arc block visibility? + * @param {int[][]} SHADOWS list of active shadows + */ + + + _proto18._checkVisibility = function _checkVisibility(A1, A2, blocks, SHADOWS) { + if (A1[0] > A2[0]) { + /* split into two sub-arcs */ + var v1 = this._checkVisibility(A1, [A1[1], A1[1]], blocks, SHADOWS); + + var v2 = this._checkVisibility([0, 1], A2, blocks, SHADOWS); + + return (v1 + v2) / 2; + } + /* index1: first shadow >= A1 */ + + + var index1 = 0, + edge1 = false; + + while (index1 < SHADOWS.length) { + var old = SHADOWS[index1]; + var diff = old[0] * A1[1] - A1[0] * old[1]; + + if (diff >= 0) { + /* old >= A1 */ + if (diff == 0 && !(index1 % 2)) { + edge1 = true; + } + + break; + } + + index1++; + } + /* index2: last shadow <= A2 */ + + + var index2 = SHADOWS.length, + edge2 = false; + + while (index2--) { + var _old = SHADOWS[index2]; + + var _diff = A2[0] * _old[1] - _old[0] * A2[1]; + + if (_diff >= 0) { + /* old <= A2 */ + if (_diff == 0 && index2 % 2) { + edge2 = true; + } + + break; + } + } + + var visible = true; + + if (index1 == index2 && (edge1 || edge2)) { + /* subset of existing shadow, one of the edges match */ + visible = false; + } else if (edge1 && edge2 && index1 + 1 == index2 && index2 % 2) { + /* completely equivalent with existing shadow */ + visible = false; + } else if (index1 > index2 && index1 % 2) { + /* subset of existing shadow, not touching */ + visible = false; + } + + if (!visible) { + return 0; + } + /* fast case: not visible */ + + + var visibleLength; + /* compute the length of visible arc, adjust list of shadows (if blocking) */ + + var remove = index2 - index1 + 1; + + if (remove % 2) { + if (index1 % 2) { + /* first edge within existing shadow, second outside */ + var P = SHADOWS[index1]; + visibleLength = (A2[0] * P[1] - P[0] * A2[1]) / (P[1] * A2[1]); + + if (blocks) { + SHADOWS.splice(index1, remove, A2); + } + } else { + /* second edge within existing shadow, first outside */ + var _P = SHADOWS[index2]; + visibleLength = (_P[0] * A1[1] - A1[0] * _P[1]) / (A1[1] * _P[1]); + + if (blocks) { + SHADOWS.splice(index1, remove, A1); + } + } + } else { + if (index1 % 2) { + /* both edges within existing shadows */ + var P1 = SHADOWS[index1]; + var P2 = SHADOWS[index2]; + visibleLength = (P2[0] * P1[1] - P1[0] * P2[1]) / (P1[1] * P2[1]); + + if (blocks) { + SHADOWS.splice(index1, remove); + } + } else { + /* both edges outside existing shadows */ + if (blocks) { + SHADOWS.splice(index1, remove, A1, A2); + } + + return 1; + /* whole arc visible! */ + } + } + + var arcLength = (A2[0] * A1[1] - A1[0] * A2[1]) / (A1[1] * A2[1]); + return visibleLength / arcLength; + }; + + return PreciseShadowcasting; + }(FOV); + /** Octants used for translating recursive shadowcasting offsets */ + + + var OCTANTS = [[-1, 0, 0, 1], [0, -1, 1, 0], [0, -1, -1, 0], [-1, 0, 0, -1], [1, 0, 0, -1], [0, 1, -1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]; + /** + * @class Recursive shadowcasting algorithm + * Currently only supports 4/8 topologies, not hexagonal. + * Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting + * @augments ROT.FOV + */ + + var RecursiveShadowcasting = + /*#__PURE__*/ + function (_FOV3) { + _inheritsLoose(RecursiveShadowcasting, _FOV3); + + function RecursiveShadowcasting() { + return _FOV3.apply(this, arguments) || this; + } + + var _proto19 = RecursiveShadowcasting.prototype; + + /** + * Compute visibility for a 360-degree circle + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {function} callback + */ + _proto19.compute = function compute(x, y, R, callback) { + //You can always see your own tile + callback(x, y, 0, 1); + + for (var i = 0; i < OCTANTS.length; i++) { + this._renderOctant(x, y, OCTANTS[i], R, callback); + } + }; + /** + * Compute visibility for a 180-degree arc + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {int} dir Direction to look in (expressed in a ROT.DIRS value); + * @param {function} callback + */ + + + _proto19.compute180 = function compute180(x, y, R, dir, callback) { + //You can always see your own tile + callback(x, y, 0, 1); + var previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees + + var nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees + + var nextOctant = (dir + 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees + + this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback); + + this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); + + this._renderOctant(x, y, OCTANTS[dir], R, callback); + + this._renderOctant(x, y, OCTANTS[nextOctant], R, callback); + }; + + /** + * Compute visibility for a 90-degree arc + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {int} dir Direction to look in (expressed in a ROT.DIRS value); + * @param {function} callback + */ + _proto19.compute90 = function compute90(x, y, R, dir, callback) { + //You can always see your own tile + callback(x, y, 0, 1); + var previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees + + this._renderOctant(x, y, OCTANTS[dir], R, callback); + + this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); + }; + /** + * Render one octant (45-degree arc) of the viewshed + * @param {int} x + * @param {int} y + * @param {int} octant Octant to be rendered + * @param {int} R Maximum visibility radius + * @param {function} callback + */ + + + _proto19._renderOctant = function _renderOctant(x, y, octant, R, callback) { + //Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses + this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback); + }; + /** + * Actually calculates the visibility + * @param {int} startX The starting X coordinate + * @param {int} startY The starting Y coordinate + * @param {int} row The row to render + * @param {float} visSlopeStart The slope to start at + * @param {float} visSlopeEnd The slope to end at + * @param {int} radius The radius to reach out to + * @param {int} xx + * @param {int} xy + * @param {int} yx + * @param {int} yy + * @param {function} callback The callback to use when we hit a block that is visible + */ + + + _proto19._castVisibility = function _castVisibility(startX, startY, row, visSlopeStart, visSlopeEnd, radius, xx, xy, yx, yy, callback) { + if (visSlopeStart < visSlopeEnd) { + return; + } + + for (var i = row; i <= radius; i++) { + var dx = -i - 1; + var dy = -i; + var blocked = false; + var newStart = 0; //'Row' could be column, names here assume octant 0 and would be flipped for half the octants + + while (dx <= 0) { + dx += 1; //Translate from relative coordinates to map coordinates + + var mapX = startX + dx * xx + dy * xy; + var mapY = startY + dx * yx + dy * yy; //Range of the row + + var slopeStart = (dx - 0.5) / (dy + 0.5); + var slopeEnd = (dx + 0.5) / (dy - 0.5); //Ignore if not yet at left edge of Octant + + if (slopeEnd > visSlopeStart) { + continue; + } //Done if past right edge + + + if (slopeStart < visSlopeEnd) { + break; + } //If it's in range, it's visible + + + if (dx * dx + dy * dy < radius * radius) { + callback(mapX, mapY, i, 1); + } + + if (!blocked) { + //If tile is a blocking tile, cast around it + if (!this._lightPasses(mapX, mapY) && i < radius) { + blocked = true; + + this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback); + + newStart = slopeEnd; + } + } else { + //Keep narrowing if scanning across a block + if (!this._lightPasses(mapX, mapY)) { + newStart = slopeEnd; + continue; + } //Block has ended + + + blocked = false; + visSlopeStart = newStart; + } + } + + if (blocked) { + break; + } + } + }; + + return RecursiveShadowcasting; + }(FOV); + + var index$1 = { + DiscreteShadowcasting: DiscreteShadowcasting, + PreciseShadowcasting: PreciseShadowcasting, + RecursiveShadowcasting: RecursiveShadowcasting + }; + + var Map = + /*#__PURE__*/ + function () { + /** + * @class Base map generator + * @param {int} [width=ROT.DEFAULT_WIDTH] + * @param {int} [height=ROT.DEFAULT_HEIGHT] + */ + function Map(width, height) { + if (width === void 0) { + width = DEFAULT_WIDTH; + } + + if (height === void 0) { + height = DEFAULT_HEIGHT; + } + + this._width = width; + this._height = height; + } + + var _proto20 = Map.prototype; + + _proto20._fillMap = function _fillMap(value) { + var map = []; + + for (var i = 0; i < this._width; i++) { + map.push([]); + + for (var j = 0; j < this._height; j++) { + map[i].push(value); + } + } + + return map; + }; + + return Map; + }(); + /** + * @class Simple empty rectangular room + * @augments ROT.Map + */ + + + var Arena = + /*#__PURE__*/ + function (_Map) { + _inheritsLoose(Arena, _Map); + + function Arena() { + return _Map.apply(this, arguments) || this; + } + + var _proto21 = Arena.prototype; + + _proto21.create = function create(callback) { + var w = this._width - 1; + var h = this._height - 1; + + for (var i = 0; i <= w; i++) { + for (var j = 0; j <= h; j++) { + var empty = i && j && i < w && j < h; + callback(i, j, empty ? 0 : 1); + } + } + + return this; + }; + + return Arena; + }(Map); + /** + * @class Dungeon map: has rooms and corridors + * @augments ROT.Map + */ + + + var Dungeon = + /*#__PURE__*/ + function (_Map2) { + _inheritsLoose(Dungeon, _Map2); + + function Dungeon(width, height) { + var _this10; + + _this10 = _Map2.call(this, width, height) || this; + _this10._rooms = []; + _this10._corridors = []; + return _this10; + } + /** + * Get all generated rooms + * @returns {ROT.Map.Feature.Room[]} + */ + + + var _proto22 = Dungeon.prototype; + + _proto22.getRooms = function getRooms() { + return this._rooms; + }; + /** + * Get all generated corridors + * @returns {ROT.Map.Feature.Corridor[]} + */ + + + _proto22.getCorridors = function getCorridors() { + return this._corridors; + }; + + return Dungeon; + }(Map); + /** + * @class Dungeon feature; has own .create() method + */ + + + var Feature = function Feature() {}; + /** + * @class Room + * @augments ROT.Map.Feature + * @param {int} x1 + * @param {int} y1 + * @param {int} x2 + * @param {int} y2 + * @param {int} [doorX] + * @param {int} [doorY] + */ + + + var Room = + /*#__PURE__*/ + function (_Feature) { + _inheritsLoose(Room, _Feature); + + function Room(x1, y1, x2, y2, doorX, doorY) { + var _this11; + + _this11 = _Feature.call(this) || this; + _this11._x1 = x1; + _this11._y1 = y1; + _this11._x2 = x2; + _this11._y2 = y2; + _this11._doors = {}; + + if (doorX !== undefined && doorY !== undefined) { + _this11.addDoor(doorX, doorY); + } + + return _this11; + } + + /** + * Room of random size, with a given doors and direction + */ + Room.createRandomAt = function createRandomAt(x, y, dx, dy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = RNG$1.getUniformInt(min, max); + min = options.roomHeight[0]; + max = options.roomHeight[1]; + var height = RNG$1.getUniformInt(min, max); + + if (dx == 1) { + /* to the right */ + var y2 = y - Math.floor(RNG$1.getUniform() * height); + return new this(x + 1, y2, x + width, y2 + height - 1, x, y); + } + + if (dx == -1) { + /* to the left */ + var _y = y - Math.floor(RNG$1.getUniform() * height); + + return new this(x - width, _y, x - 1, _y + height - 1, x, y); + } + + if (dy == 1) { + /* to the bottom */ + var x2 = x - Math.floor(RNG$1.getUniform() * width); + return new this(x2, y + 1, x2 + width - 1, y + height, x, y); + } + + if (dy == -1) { + /* to the top */ + var _x = x - Math.floor(RNG$1.getUniform() * width); + + return new this(_x, y - height, _x + width - 1, y - 1, x, y); + } + + throw new Error("dx or dy must be 1 or -1"); + }; + /** + * Room of random size, positioned around center coords + */ + + + Room.createRandomCenter = function createRandomCenter(cx, cy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = RNG$1.getUniformInt(min, max); + min = options.roomHeight[0]; + max = options.roomHeight[1]; + var height = RNG$1.getUniformInt(min, max); + var x1 = cx - Math.floor(RNG$1.getUniform() * width); + var y1 = cy - Math.floor(RNG$1.getUniform() * height); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + return new this(x1, y1, x2, y2); + }; + /** + * Room of random size within a given dimensions + */ + + + Room.createRandom = function createRandom(availWidth, availHeight, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = RNG$1.getUniformInt(min, max); + min = options.roomHeight[0]; + max = options.roomHeight[1]; + var height = RNG$1.getUniformInt(min, max); + var left = availWidth - width - 1; + var top = availHeight - height - 1; + var x1 = 1 + Math.floor(RNG$1.getUniform() * left); + var y1 = 1 + Math.floor(RNG$1.getUniform() * top); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + return new this(x1, y1, x2, y2); + }; + + var _proto23 = Room.prototype; + + _proto23.addDoor = function addDoor(x, y) { + this._doors[x + "," + y] = 1; + return this; + }; + /** + * @param {function} + */ + + + _proto23.getDoors = function getDoors(cb) { + for (var key in this._doors) { + var parts = key.split(","); + cb(parseInt(parts[0]), parseInt(parts[1])); + } + + return this; + }; + + _proto23.clearDoors = function clearDoors() { + this._doors = {}; + return this; + }; + + _proto23.addDoors = function addDoors(isWallCallback) { + var left = this._x1 - 1; + var right = this._x2 + 1; + var top = this._y1 - 1; + var bottom = this._y2 + 1; + + for (var x = left; x <= right; x++) { + for (var y = top; y <= bottom; y++) { + if (x != left && x != right && y != top && y != bottom) { + continue; + } + + if (isWallCallback(x, y)) { + continue; + } + + this.addDoor(x, y); + } + } + + return this; + }; + + _proto23.debug = function debug() { + console.log("room", this._x1, this._y1, this._x2, this._y2); + }; + + _proto23.isValid = function isValid(isWallCallback, canBeDugCallback) { + var left = this._x1 - 1; + var right = this._x2 + 1; + var top = this._y1 - 1; + var bottom = this._y2 + 1; + + for (var x = left; x <= right; x++) { + for (var y = top; y <= bottom; y++) { + if (x == left || x == right || y == top || y == bottom) { + if (!isWallCallback(x, y)) { + return false; + } + } else { + if (!canBeDugCallback(x, y)) { + return false; + } + } + } + } + + return true; + }; + /** + * @param {function} digCallback Dig callback with a signature (x, y, value). Values: 0 = empty, 1 = wall, 2 = door. Multiple doors are allowed. + */ + + + _proto23.create = function create(digCallback) { + var left = this._x1 - 1; + var right = this._x2 + 1; + var top = this._y1 - 1; + var bottom = this._y2 + 1; + var value = 0; + + for (var x = left; x <= right; x++) { + for (var y = top; y <= bottom; y++) { + if (x + "," + y in this._doors) { + value = 2; + } else if (x == left || x == right || y == top || y == bottom) { + value = 1; + } else { + value = 0; + } + + digCallback(x, y, value); + } + } + }; + + _proto23.getCenter = function getCenter() { + return [Math.round((this._x1 + this._x2) / 2), Math.round((this._y1 + this._y2) / 2)]; + }; + + _proto23.getLeft = function getLeft() { + return this._x1; + }; + + _proto23.getRight = function getRight() { + return this._x2; + }; + + _proto23.getTop = function getTop() { + return this._y1; + }; + + _proto23.getBottom = function getBottom() { + return this._y2; + }; + + return Room; + }(Feature); + /** + * @class Corridor + * @augments ROT.Map.Feature + * @param {int} startX + * @param {int} startY + * @param {int} endX + * @param {int} endY + */ + + + var Corridor = + /*#__PURE__*/ + function (_Feature2) { + _inheritsLoose(Corridor, _Feature2); + + function Corridor(startX, startY, endX, endY) { + var _this12; + + _this12 = _Feature2.call(this) || this; + _this12._startX = startX; + _this12._startY = startY; + _this12._endX = endX; + _this12._endY = endY; + _this12._endsWithAWall = true; + return _this12; + } + + Corridor.createRandomAt = function createRandomAt(x, y, dx, dy, options) { + var min = options.corridorLength[0]; + var max = options.corridorLength[1]; + var length = RNG$1.getUniformInt(min, max); + return new this(x, y, x + dx * length, y + dy * length); + }; + + var _proto24 = Corridor.prototype; + + _proto24.debug = function debug() { + console.log("corridor", this._startX, this._startY, this._endX, this._endY); + }; + + _proto24.isValid = function isValid(isWallCallback, canBeDugCallback) { + var sx = this._startX; + var sy = this._startY; + var dx = this._endX - sx; + var dy = this._endY - sy; + var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); + + if (dx) { + dx = dx / Math.abs(dx); + } + + if (dy) { + dy = dy / Math.abs(dy); + } + + var nx = dy; + var ny = -dx; + var ok = true; + + for (var i = 0; i < length; i++) { + var x = sx + i * dx; + var y = sy + i * dy; + + if (!canBeDugCallback(x, y)) { + ok = false; + } + + if (!isWallCallback(x + nx, y + ny)) { + ok = false; + } + + if (!isWallCallback(x - nx, y - ny)) { + ok = false; + } + + if (!ok) { + length = i; + this._endX = x - dx; + this._endY = y - dy; + break; + } + } + /** + * If the length degenerated, this corridor might be invalid + */ + + /* not supported */ + + + if (length == 0) { + return false; + } + /* length 1 allowed only if the next space is empty */ + + + if (length == 1 && isWallCallback(this._endX + dx, this._endY + dy)) { + return false; + } + /** + * We do not want the corridor to crash into a corner of a room; + * if any of the ending corners is empty, the N+1th cell of this corridor must be empty too. + * + * Situation: + * #######1 + * .......? + * #######2 + * + * The corridor was dug from left to right. + * 1, 2 - problematic corners, ? = N+1th cell (not dug) + */ + + + var firstCornerBad = !isWallCallback(this._endX + dx + nx, this._endY + dy + ny); + var secondCornerBad = !isWallCallback(this._endX + dx - nx, this._endY + dy - ny); + this._endsWithAWall = isWallCallback(this._endX + dx, this._endY + dy); + + if ((firstCornerBad || secondCornerBad) && this._endsWithAWall) { + return false; + } + + return true; + }; + /** + * @param {function} digCallback Dig callback with a signature (x, y, value). Values: 0 = empty. + */ + + + _proto24.create = function create(digCallback) { + var sx = this._startX; + var sy = this._startY; + var dx = this._endX - sx; + var dy = this._endY - sy; + var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); + + if (dx) { + dx = dx / Math.abs(dx); + } + + if (dy) { + dy = dy / Math.abs(dy); + } + + for (var i = 0; i < length; i++) { + var x = sx + i * dx; + var y = sy + i * dy; + digCallback(x, y, 0); + } + + return true; + }; + + _proto24.createPriorityWalls = function createPriorityWalls(priorityWallCallback) { + if (!this._endsWithAWall) { + return; + } + + var sx = this._startX; + var sy = this._startY; + var dx = this._endX - sx; + var dy = this._endY - sy; + + if (dx) { + dx = dx / Math.abs(dx); + } + + if (dy) { + dy = dy / Math.abs(dy); + } + + var nx = dy; + var ny = -dx; + priorityWallCallback(this._endX + dx, this._endY + dy); + priorityWallCallback(this._endX + nx, this._endY + ny); + priorityWallCallback(this._endX - nx, this._endY - ny); + }; + + return Corridor; + }(Feature); + /** + * @class Dungeon generator which tries to fill the space evenly. Generates independent rooms and tries to connect them. + * @augments ROT.Map.Dungeon + */ + + + var Uniform = + /*#__PURE__*/ + function (_Dungeon) { + _inheritsLoose(Uniform, _Dungeon); + + function Uniform(width, height, options) { + var _this13; + + _this13 = _Dungeon.call(this, width, height) || this; + _this13._options = { + roomWidth: [3, 9], + roomHeight: [3, 5], + roomDugPercentage: 0.1, + timeLimit: 1000 + /* we stop after this much time has passed (msec) */ + + }; + Object.assign(_this13._options, options); + _this13._map = []; + _this13._dug = 0; + _this13._roomAttempts = 20; + /* new room is created N-times until is considered as impossible to generate */ + + _this13._corridorAttempts = 20; + /* corridors are tried N-times until the level is considered as impossible to connect */ + + _this13._connected = []; + /* list of already connected rooms */ + + _this13._unconnected = []; + /* list of remaining unconnected rooms */ + + _this13._digCallback = _this13._digCallback.bind(_assertThisInitialized(_assertThisInitialized(_this13))); + _this13._canBeDugCallback = _this13._canBeDugCallback.bind(_assertThisInitialized(_assertThisInitialized(_this13))); + _this13._isWallCallback = _this13._isWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this13))); + return _this13; + } + /** + * Create a map. If the time limit has been hit, returns null. + * @see ROT.Map#create + */ + + + var _proto25 = Uniform.prototype; + + _proto25.create = function create(callback) { + var t1 = Date.now(); + + while (1) { + var t2 = Date.now(); + + if (t2 - t1 > this._options.timeLimit) { + return null; + } + /* time limit! */ + + + this._map = this._fillMap(1); + this._dug = 0; + this._rooms = []; + this._unconnected = []; + + this._generateRooms(); + + if (this._rooms.length < 2) { + continue; + } + + if (this._generateCorridors()) { + break; + } + } + + if (callback) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + callback(i, j, this._map[i][j]); + } + } + } + + return this; + }; + /** + * Generates a suitable amount of rooms + */ + + + _proto25._generateRooms = function _generateRooms() { + var w = this._width - 2; + var h = this._height - 2; + var room; + + do { + room = this._generateRoom(); + + if (this._dug / (w * h) > this._options.roomDugPercentage) { + break; + } + /* achieved requested amount of free space */ + + } while (room); + /* either enough rooms, or not able to generate more of them :) */ + + }; + /** + * Try to generate one room + */ + + + _proto25._generateRoom = function _generateRoom() { + var count = 0; + + while (count < this._roomAttempts) { + count++; + var room = Room.createRandom(this._width, this._height, this._options); + + if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) { + continue; + } + + room.create(this._digCallback); + + this._rooms.push(room); + + return room; + } + /* no room was generated in a given number of attempts */ + + + return null; + }; + /** + * Generates connectors beween rooms + * @returns {bool} success Was this attempt successfull? + */ + + + _proto25._generateCorridors = function _generateCorridors() { + var cnt = 0; + + while (cnt < this._corridorAttempts) { + cnt++; + this._corridors = []; + /* dig rooms into a clear map */ + + this._map = this._fillMap(1); + + for (var i = 0; i < this._rooms.length; i++) { + var room = this._rooms[i]; + room.clearDoors(); + room.create(this._digCallback); + } + + this._unconnected = RNG$1.shuffle(this._rooms.slice()); + this._connected = []; + + if (this._unconnected.length) { + this._connected.push(this._unconnected.pop()); + } + /* first one is always connected */ + + + while (1) { + /* 1. pick random connected room */ + var connected = RNG$1.getItem(this._connected); + + if (!connected) { + break; + } + /* 2. find closest unconnected */ + + + var room1 = this._closestRoom(this._unconnected, connected); + + if (!room1) { + break; + } + /* 3. connect it to closest connected */ + + + var room2 = this._closestRoom(this._connected, room1); + + if (!room2) { + break; + } + + var ok = this._connectRooms(room1, room2); + + if (!ok) { + break; + } + /* stop connecting, re-shuffle */ + + + if (!this._unconnected.length) { + return true; + } + /* done; no rooms remain */ + + } + } + + return false; + }; + + /** + * For a given room, find the closest one from the list + */ + _proto25._closestRoom = function _closestRoom(rooms, room) { + var dist = Infinity; + var center = room.getCenter(); + var result = null; + + for (var i = 0; i < rooms.length; i++) { + var r = rooms[i]; + var c = r.getCenter(); + var dx = c[0] - center[0]; + var dy = c[1] - center[1]; + var d = dx * dx + dy * dy; + + if (d < dist) { + dist = d; + result = r; + } + } + + return result; + }; + + _proto25._connectRooms = function _connectRooms(room1, room2) { + /* + room1.debug(); + room2.debug(); + */ + var center1 = room1.getCenter(); + var center2 = room2.getCenter(); + var diffX = center2[0] - center1[0]; + var diffY = center2[1] - center1[1]; + var start; + var end; + var dirIndex1, dirIndex2, min, max, index; + + if (Math.abs(diffX) < Math.abs(diffY)) { + /* first try connecting north-south walls */ + dirIndex1 = diffY > 0 ? 2 : 0; + dirIndex2 = (dirIndex1 + 2) % 4; + min = room2.getLeft(); + max = room2.getRight(); + index = 0; + } else { + /* first try connecting east-west walls */ + dirIndex1 = diffX > 0 ? 1 : 3; + dirIndex2 = (dirIndex1 + 2) % 4; + min = room2.getTop(); + max = room2.getBottom(); + index = 1; + } + + start = this._placeInWall(room1, dirIndex1); + /* corridor will start here */ + + if (!start) { + return false; + } + + if (start[index] >= min && start[index] <= max) { + /* possible to connect with straight line (I-like) */ + end = start.slice(); + var value = 0; + + switch (dirIndex2) { + case 0: + value = room2.getTop() - 1; + break; + + case 1: + value = room2.getRight() + 1; + break; + + case 2: + value = room2.getBottom() + 1; + break; + + case 3: + value = room2.getLeft() - 1; + break; + } + + end[(index + 1) % 2] = value; + + this._digLine([start, end]); + } else if (start[index] < min - 1 || start[index] > max + 1) { + /* need to switch target wall (L-like) */ + var diff = start[index] - center2[index]; + var rotation = 0; + + switch (dirIndex2) { + case 0: + case 1: + rotation = diff < 0 ? 3 : 1; + break; + + case 2: + case 3: + rotation = diff < 0 ? 1 : 3; + break; + } + + dirIndex2 = (dirIndex2 + rotation) % 4; + end = this._placeInWall(room2, dirIndex2); + + if (!end) { + return false; + } + + var mid = [0, 0]; + mid[index] = start[index]; + var index2 = (index + 1) % 2; + mid[index2] = end[index2]; + + this._digLine([start, mid, end]); + } else { + /* use current wall pair, but adjust the line in the middle (S-like) */ + var _index4 = (index + 1) % 2; + + end = this._placeInWall(room2, dirIndex2); + + if (!end) { + return false; + } + + var _mid = Math.round((end[_index4] + start[_index4]) / 2); + + var mid1 = [0, 0]; + var mid2 = [0, 0]; + mid1[index] = start[index]; + mid1[_index4] = _mid; + mid2[index] = end[index]; + mid2[_index4] = _mid; + + this._digLine([start, mid1, mid2, end]); + } + + room1.addDoor(start[0], start[1]); + room2.addDoor(end[0], end[1]); + index = this._unconnected.indexOf(room1); + + if (index != -1) { + this._unconnected.splice(index, 1); + + this._connected.push(room1); + } + + index = this._unconnected.indexOf(room2); + + if (index != -1) { + this._unconnected.splice(index, 1); + + this._connected.push(room2); + } + + return true; + }; + + _proto25._placeInWall = function _placeInWall(room, dirIndex) { + var start = [0, 0]; + var dir = [0, 0]; + var length = 0; + + switch (dirIndex) { + case 0: + dir = [1, 0]; + start = [room.getLeft(), room.getTop() - 1]; + length = room.getRight() - room.getLeft() + 1; + break; + + case 1: + dir = [0, 1]; + start = [room.getRight() + 1, room.getTop()]; + length = room.getBottom() - room.getTop() + 1; + break; + + case 2: + dir = [1, 0]; + start = [room.getLeft(), room.getBottom() + 1]; + length = room.getRight() - room.getLeft() + 1; + break; + + case 3: + dir = [0, 1]; + start = [room.getLeft() - 1, room.getTop()]; + length = room.getBottom() - room.getTop() + 1; + break; + } + + var avail = []; + var lastBadIndex = -2; + + for (var i = 0; i < length; i++) { + var x = start[0] + i * dir[0]; + var y = start[1] + i * dir[1]; + avail.push(null); + var isWall = this._map[x][y] == 1; + + if (isWall) { + if (lastBadIndex != i - 1) { + avail[i] = [x, y]; + } + } else { + lastBadIndex = i; + + if (i) { + avail[i - 1] = null; + } + } + } + + for (var _i3 = avail.length - 1; _i3 >= 0; _i3--) { + if (!avail[_i3]) { + avail.splice(_i3, 1); + } + } + + return avail.length ? RNG$1.getItem(avail) : null; + }; + /** + * Dig a polyline. + */ + + + _proto25._digLine = function _digLine(points) { + for (var i = 1; i < points.length; i++) { + var start = points[i - 1]; + var end = points[i]; + var corridor = new Corridor(start[0], start[1], end[0], end[1]); + corridor.create(this._digCallback); + + this._corridors.push(corridor); + } + }; + + _proto25._digCallback = function _digCallback(x, y, value) { + this._map[x][y] = value; + + if (value == 0) { + this._dug++; + } + }; + + _proto25._isWallCallback = function _isWallCallback(x, y) { + if (x < 0 || y < 0 || x >= this._width || y >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + _proto25._canBeDugCallback = function _canBeDugCallback(x, y) { + if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + return Uniform; + }(Dungeon); + /** + * @class Cellular automaton map generator + * @augments ROT.Map + * @param {int} [width=ROT.DEFAULT_WIDTH] + * @param {int} [height=ROT.DEFAULT_HEIGHT] + * @param {object} [options] Options + * @param {int[]} [options.born] List of neighbor counts for a new cell to be born in empty space + * @param {int[]} [options.survive] List of neighbor counts for an existing cell to survive + * @param {int} [options.topology] Topology 4 or 6 or 8 + */ + + + var Cellular = + /*#__PURE__*/ + function (_Map3) { + _inheritsLoose(Cellular, _Map3); + + function Cellular(width, height, options) { + var _this14; + + if (options === void 0) { + options = {}; + } + + _this14 = _Map3.call(this, width, height) || this; + _this14._options = { + born: [5, 6, 7, 8], + survive: [4, 5, 6, 7, 8], + topology: 8 + }; + + _this14.setOptions(options); + + _this14._dirs = DIRS[_this14._options.topology]; + _this14._map = _this14._fillMap(0); + return _this14; + } + /** + * Fill the map with random values + * @param {float} probability Probability for a cell to become alive; 0 = all empty, 1 = all full + */ + + + var _proto26 = Cellular.prototype; + + _proto26.randomize = function randomize(probability) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + this._map[i][j] = RNG$1.getUniform() < probability ? 1 : 0; + } + } + + return this; + }; + /** + * Change options. + * @see ROT.Map.Cellular + */ + + + _proto26.setOptions = function setOptions(options) { + Object.assign(this._options, options); + }; + + _proto26.set = function set(x, y, value) { + this._map[x][y] = value; + }; + + _proto26.create = function create(callback) { + var newMap = this._fillMap(0); + + var born = this._options.born; + var survive = this._options.survive; + + for (var j = 0; j < this._height; j++) { + var widthStep = 1; + var widthStart = 0; + + if (this._options.topology == 6) { + widthStep = 2; + widthStart = j % 2; + } + + for (var i = widthStart; i < this._width; i += widthStep) { + var cur = this._map[i][j]; + + var ncount = this._getNeighbors(i, j); + + if (cur && survive.indexOf(ncount) != -1) { + /* survive */ + newMap[i][j] = 1; + } else if (!cur && born.indexOf(ncount) != -1) { + /* born */ + newMap[i][j] = 1; + } + } + } + + this._map = newMap; + callback && this._serviceCallback(callback); + }; + + _proto26._serviceCallback = function _serviceCallback(callback) { + for (var j = 0; j < this._height; j++) { + var widthStep = 1; + var widthStart = 0; + + if (this._options.topology == 6) { + widthStep = 2; + widthStart = j % 2; + } + + for (var i = widthStart; i < this._width; i += widthStep) { + callback(i, j, this._map[i][j]); + } + } + }; + /** + * Get neighbor count at [i,j] in this._map + */ + + + _proto26._getNeighbors = function _getNeighbors(cx, cy) { + var result = 0; + + for (var i = 0; i < this._dirs.length; i++) { + var dir = this._dirs[i]; + var x = cx + dir[0]; + var y = cy + dir[1]; + + if (x < 0 || x >= this._width || y < 0 || y >= this._height) { + continue; + } + + result += this._map[x][y] == 1 ? 1 : 0; + } + + return result; + }; + /** + * Make sure every non-wall space is accessible. + * @param {function} callback to call to display map when do + * @param {int} value to consider empty space - defaults to 0 + * @param {function} callback to call when a new connection is made + */ + + + _proto26.connect = function connect(callback, value, connectionCallback) { + if (!value) value = 0; + var allFreeSpace = []; + var notConnected = {}; // find all free space + + var widthStep = 1; + var widthStarts = [0, 0]; + + if (this._options.topology == 6) { + widthStep = 2; + widthStarts = [0, 1]; + } + + for (var y = 0; y < this._height; y++) { + for (var x = widthStarts[y % 2]; x < this._width; x += widthStep) { + if (this._freeSpace(x, y, value)) { + var p = [x, y]; + notConnected[this._pointKey(p)] = p; + allFreeSpace.push([x, y]); + } + } + } + + var start = allFreeSpace[RNG$1.getUniformInt(0, allFreeSpace.length - 1)]; + + var key = this._pointKey(start); + + var connected = {}; + connected[key] = start; + delete notConnected[key]; // find what's connected to the starting point + + this._findConnected(connected, notConnected, [start], false, value); + + while (Object.keys(notConnected).length > 0) { + // find two points from notConnected to connected + var _p = this._getFromTo(connected, notConnected); + + var from = _p[0]; // notConnected + + var to = _p[1]; // connected + // find everything connected to the starting point + + var local = {}; + local[this._pointKey(from)] = from; + + this._findConnected(local, notConnected, [from], true, value); // connect to a connected cell + + + var tunnelFn = this._options.topology == 6 ? this._tunnelToConnected6 : this._tunnelToConnected; + tunnelFn.call(this, to, from, connected, notConnected, value, connectionCallback); // now all of local is connected + + for (var k in local) { + var pp = local[k]; + this._map[pp[0]][pp[1]] = value; + connected[k] = pp; + delete notConnected[k]; + } + } + + callback && this._serviceCallback(callback); + }; + /** + * Find random points to connect. Search for the closest point in the larger space. + * This is to minimize the length of the passage while maintaining good performance. + */ + + + _proto26._getFromTo = function _getFromTo(connected, notConnected) { + var from = [0, 0], + to = [0, 0], + d; + var connectedKeys = Object.keys(connected); + var notConnectedKeys = Object.keys(notConnected); + + for (var i = 0; i < 5; i++) { + if (connectedKeys.length < notConnectedKeys.length) { + var keys = connectedKeys; + to = connected[keys[RNG$1.getUniformInt(0, keys.length - 1)]]; + from = this._getClosest(to, notConnected); + } else { + var _keys = notConnectedKeys; + from = notConnected[_keys[RNG$1.getUniformInt(0, _keys.length - 1)]]; + to = this._getClosest(from, connected); + } + + d = (from[0] - to[0]) * (from[0] - to[0]) + (from[1] - to[1]) * (from[1] - to[1]); + + if (d < 64) { + break; + } + } // console.log(">>> connected=" + to + " notConnected=" + from + " dist=" + d); + + + return [from, to]; + }; + + _proto26._getClosest = function _getClosest(point, space) { + var minPoint = null; + var minDist = null; + + for (var k in space) { + var p = space[k]; + var d = (p[0] - point[0]) * (p[0] - point[0]) + (p[1] - point[1]) * (p[1] - point[1]); + + if (minDist == null || d < minDist) { + minDist = d; + minPoint = p; + } + } + + return minPoint; + }; + + _proto26._findConnected = function _findConnected(connected, notConnected, stack, keepNotConnected, value) { + while (stack.length > 0) { + var p = stack.splice(0, 1)[0]; + var tests = void 0; + + if (this._options.topology == 6) { + tests = [[p[0] + 2, p[1]], [p[0] + 1, p[1] - 1], [p[0] - 1, p[1] - 1], [p[0] - 2, p[1]], [p[0] - 1, p[1] + 1], [p[0] + 1, p[1] + 1]]; + } else { + tests = [[p[0] + 1, p[1]], [p[0] - 1, p[1]], [p[0], p[1] + 1], [p[0], p[1] - 1]]; + } + + for (var i = 0; i < tests.length; i++) { + var key = this._pointKey(tests[i]); + + if (connected[key] == null && this._freeSpace(tests[i][0], tests[i][1], value)) { + connected[key] = tests[i]; + + if (!keepNotConnected) { + delete notConnected[key]; + } + + stack.push(tests[i]); + } + } + } + }; + + _proto26._tunnelToConnected = function _tunnelToConnected(to, from, connected, notConnected, value, connectionCallback) { + var a, b; + + if (from[0] < to[0]) { + a = from; + b = to; + } else { + a = to; + b = from; + } + + for (var xx = a[0]; xx <= b[0]; xx++) { + this._map[xx][a[1]] = value; + var p = [xx, a[1]]; + + var pkey = this._pointKey(p); + + connected[pkey] = p; + delete notConnected[pkey]; + } + + if (connectionCallback && a[0] < b[0]) { + connectionCallback(a, [b[0], a[1]]); + } // x is now fixed + + + var x = b[0]; + + if (from[1] < to[1]) { + a = from; + b = to; + } else { + a = to; + b = from; + } + + for (var yy = a[1]; yy < b[1]; yy++) { + this._map[x][yy] = value; + var _p2 = [x, yy]; + + var _pkey = this._pointKey(_p2); + + connected[_pkey] = _p2; + delete notConnected[_pkey]; + } + + if (connectionCallback && a[1] < b[1]) { + connectionCallback([b[0], a[1]], [b[0], b[1]]); + } + }; + + _proto26._tunnelToConnected6 = function _tunnelToConnected6(to, from, connected, notConnected, value, connectionCallback) { + var a, b; + + if (from[0] < to[0]) { + a = from; + b = to; + } else { + a = to; + b = from; + } // tunnel diagonally until horizontally level + + + var xx = a[0]; + var yy = a[1]; + + while (!(xx == b[0] && yy == b[1])) { + var stepWidth = 2; + + if (yy < b[1]) { + yy++; + stepWidth = 1; + } else if (yy > b[1]) { + yy--; + stepWidth = 1; + } + + if (xx < b[0]) { + xx += stepWidth; + } else if (xx > b[0]) { + xx -= stepWidth; + } else if (b[1] % 2) { + // Won't step outside map if destination on is map's right edge + xx -= stepWidth; + } else { + // ditto for left edge + xx += stepWidth; + } + + this._map[xx][yy] = value; + var p = [xx, yy]; + + var pkey = this._pointKey(p); + + connected[pkey] = p; + delete notConnected[pkey]; + } + + if (connectionCallback) { + connectionCallback(from, to); + } + }; + + _proto26._freeSpace = function _freeSpace(x, y, value) { + return x >= 0 && x < this._width && y >= 0 && y < this._height && this._map[x][y] == value; + }; + + _proto26._pointKey = function _pointKey(p) { + return p[0] + "." + p[1]; + }; + + return Cellular; + }(Map); + + var FEATURES = { + "room": Room, + "corridor": Corridor + }; + /** + * Random dungeon generator using human-like digging patterns. + * Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at + * http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm. + */ + + var Digger = + /*#__PURE__*/ + function (_Dungeon2) { + _inheritsLoose(Digger, _Dungeon2); + + function Digger(width, height, options) { + var _this15; + + if (options === void 0) { + options = {}; + } + + _this15 = _Dungeon2.call(this, width, height) || this; + _this15._options = Object.assign({ + roomWidth: [3, 9], + roomHeight: [3, 5], + corridorLength: [3, 10], + dugPercentage: 0.2, + timeLimit: 1000 + /* we stop after this much time has passed (msec) */ + + }, options); + _this15._features = { + "room": 4, + "corridor": 4 + }; + _this15._map = []; + _this15._featureAttempts = 20; + /* how many times do we try to create a feature on a suitable wall */ + + _this15._walls = {}; + /* these are available for digging */ + + _this15._dug = 0; + _this15._digCallback = _this15._digCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + _this15._canBeDugCallback = _this15._canBeDugCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + _this15._isWallCallback = _this15._isWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + _this15._priorityWallCallback = _this15._priorityWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + return _this15; + } + + var _proto27 = Digger.prototype; + + _proto27.create = function create(callback) { + this._rooms = []; + this._corridors = []; + this._map = this._fillMap(1); + this._walls = {}; + this._dug = 0; + var area = (this._width - 2) * (this._height - 2); + + this._firstRoom(); + + var t1 = Date.now(); + var priorityWalls; + + do { + priorityWalls = 0; + var t2 = Date.now(); + + if (t2 - t1 > this._options.timeLimit) { + break; + } + /* find a good wall */ + + + var wall = this._findWall(); + + if (!wall) { + break; + } + /* no more walls */ + + + var parts = wall.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + + var dir = this._getDiggingDirection(x, y); + + if (!dir) { + continue; + } + /* this wall is not suitable */ + // console.log("wall", x, y); + + /* try adding a feature */ + + + var featureAttempts = 0; + + do { + featureAttempts++; + + if (this._tryFeature(x, y, dir[0], dir[1])) { + /* feature added */ + //if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */ + this._removeSurroundingWalls(x, y); + + this._removeSurroundingWalls(x - dir[0], y - dir[1]); + + break; + } + } while (featureAttempts < this._featureAttempts); + + for (var id in this._walls) { + if (this._walls[id] > 1) { + priorityWalls++; + } + } + } while (this._dug / area < this._options.dugPercentage || priorityWalls); + /* fixme number of priority walls */ + + + this._addDoors(); + + if (callback) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + callback(i, j, this._map[i][j]); + } + } + } + + this._walls = {}; + this._map = []; + return this; + }; + + _proto27._digCallback = function _digCallback(x, y, value) { + if (value == 0 || value == 2) { + /* empty */ + this._map[x][y] = 0; + this._dug++; + } else { + /* wall */ + this._walls[x + "," + y] = 1; + } + }; + + _proto27._isWallCallback = function _isWallCallback(x, y) { + if (x < 0 || y < 0 || x >= this._width || y >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + _proto27._canBeDugCallback = function _canBeDugCallback(x, y) { + if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + _proto27._priorityWallCallback = function _priorityWallCallback(x, y) { + this._walls[x + "," + y] = 2; + }; + + _proto27._firstRoom = function _firstRoom() { + var cx = Math.floor(this._width / 2); + var cy = Math.floor(this._height / 2); + var room = Room.createRandomCenter(cx, cy, this._options); + + this._rooms.push(room); + + room.create(this._digCallback); + }; + /** + * Get a suitable wall + */ + + + _proto27._findWall = function _findWall() { + var prio1 = []; + var prio2 = []; + + for (var _id2 in this._walls) { + var prio = this._walls[_id2]; + + if (prio == 2) { + prio2.push(_id2); + } else { + prio1.push(_id2); + } + } + + var arr = prio2.length ? prio2 : prio1; + + if (!arr.length) { + return null; + } + /* no walls :/ */ + + + var id = RNG$1.getItem(arr.sort()); // sort to make the order deterministic + + delete this._walls[id]; + return id; + }; + /** + * Tries adding a feature + * @returns {bool} was this a successful try? + */ + + + _proto27._tryFeature = function _tryFeature(x, y, dx, dy) { + var featureName = RNG$1.getWeightedValue(this._features); + var ctor = FEATURES[featureName]; + var feature = ctor.createRandomAt(x, y, dx, dy, this._options); + + if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) { + // console.log("not valid"); + // feature.debug(); + return false; + } + + feature.create(this._digCallback); // feature.debug(); + + if (feature instanceof Room) { + this._rooms.push(feature); + } + + if (feature instanceof Corridor) { + feature.createPriorityWalls(this._priorityWallCallback); + + this._corridors.push(feature); + } + + return true; + }; + + _proto27._removeSurroundingWalls = function _removeSurroundingWalls(cx, cy) { + var deltas = DIRS[4]; + + for (var i = 0; i < deltas.length; i++) { + var delta = deltas[i]; + var x = cx + delta[0]; + var y = cy + delta[1]; + delete this._walls[x + "," + y]; + x = cx + 2 * delta[0]; + y = cy + 2 * delta[1]; + delete this._walls[x + "," + y]; + } + }; + /** + * Returns vector in "digging" direction, or false, if this does not exist (or is not unique) + */ + + + _proto27._getDiggingDirection = function _getDiggingDirection(cx, cy) { + if (cx <= 0 || cy <= 0 || cx >= this._width - 1 || cy >= this._height - 1) { + return null; + } + + var result = null; + var deltas = DIRS[4]; + + for (var i = 0; i < deltas.length; i++) { + var delta = deltas[i]; + var x = cx + delta[0]; + var y = cy + delta[1]; + + if (!this._map[x][y]) { + /* there already is another empty neighbor! */ + if (result) { + return null; + } + + result = delta; + } + } + /* no empty neighbor */ + + + if (!result) { + return null; + } + + return [-result[0], -result[1]]; + }; + /** + * Find empty spaces surrounding rooms, and apply doors. + */ + + + _proto27._addDoors = function _addDoors() { + var data = this._map; + + function isWallCallback(x, y) { + return data[x][y] == 1; + } + + for (var i = 0; i < this._rooms.length; i++) { + var room = this._rooms[i]; + room.clearDoors(); + room.addDoors(isWallCallback); + } + }; + + return Digger; + }(Dungeon); + /** + * Join lists with "i" and "i+1" + */ + + + function addToList(i, L, R) { + R[L[i + 1]] = R[i]; + L[R[i]] = L[i + 1]; + R[i] = i + 1; + L[i + 1] = i; + } + /** + * Remove "i" from its list + */ + + + function removeFromList(i, L, R) { + R[L[i]] = R[i]; + L[R[i]] = L[i]; + R[i] = i; + L[i] = i; + } + /** + * Maze generator - Eller's algorithm + * See http://homepages.cwi.nl/~tromp/maze.html for explanation + */ + + + var EllerMaze = + /*#__PURE__*/ + function (_Map4) { + _inheritsLoose(EllerMaze, _Map4); + + function EllerMaze() { + return _Map4.apply(this, arguments) || this; + } + + var _proto28 = EllerMaze.prototype; + + _proto28.create = function create(callback) { + var map = this._fillMap(1); + + var w = Math.ceil((this._width - 2) / 2); + var rand = 9 / 24; + var L = []; + var R = []; + + for (var i = 0; i < w; i++) { + L.push(i); + R.push(i); + } + + L.push(w - 1); + /* fake stop-block at the right side */ + + var j; + + for (j = 1; j + 3 < this._height; j += 2) { + /* one row */ + for (var _i4 = 0; _i4 < w; _i4++) { + /* cell coords (will be always empty) */ + var x = 2 * _i4 + 1; + var y = j; + map[x][y] = 0; + /* right connection */ + + if (_i4 != L[_i4 + 1] && RNG$1.getUniform() > rand) { + addToList(_i4, L, R); + map[x + 1][y] = 0; + } + /* bottom connection */ + + + if (_i4 != L[_i4] && RNG$1.getUniform() > rand) { + /* remove connection */ + removeFromList(_i4, L, R); + } else { + /* create connection */ + map[x][y + 1] = 0; + } + } + } + /* last row */ + + + for (var _i5 = 0; _i5 < w; _i5++) { + /* cell coords (will be always empty) */ + var _x2 = 2 * _i5 + 1; + + var _y2 = j; + map[_x2][_y2] = 0; + /* right connection */ + + if (_i5 != L[_i5 + 1] && (_i5 == L[_i5] || RNG$1.getUniform() > rand)) { + /* dig right also if the cell is separated, so it gets connected to the rest of maze */ + addToList(_i5, L, R); + map[_x2 + 1][_y2] = 0; + } + + removeFromList(_i5, L, R); + } + + for (var _i6 = 0; _i6 < this._width; _i6++) { + for (var _j = 0; _j < this._height; _j++) { + callback(_i6, _j, map[_i6][_j]); + } + } + + return this; + }; + + return EllerMaze; + }(Map); + /** + * @class Recursively divided maze, http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method + * @augments ROT.Map + */ + + + var DividedMaze = + /*#__PURE__*/ + function (_Map5) { + _inheritsLoose(DividedMaze, _Map5); + + function DividedMaze() { + var _this16; + + _this16 = _Map5.apply(this, arguments) || this; + _this16._stack = []; + _this16._map = []; + return _this16; + } + + var _proto29 = DividedMaze.prototype; + + _proto29.create = function create(callback) { + var w = this._width; + var h = this._height; + this._map = []; + + for (var i = 0; i < w; i++) { + this._map.push([]); + + for (var j = 0; j < h; j++) { + var border = i == 0 || j == 0 || i + 1 == w || j + 1 == h; + + this._map[i].push(border ? 1 : 0); + } + } + + this._stack = [[1, 1, w - 2, h - 2]]; + + this._process(); + + for (var _i7 = 0; _i7 < w; _i7++) { + for (var _j2 = 0; _j2 < h; _j2++) { + callback(_i7, _j2, this._map[_i7][_j2]); + } + } + + this._map = []; + return this; + }; + + _proto29._process = function _process() { + while (this._stack.length) { + var room = this._stack.shift(); + /* [left, top, right, bottom] */ + + + this._partitionRoom(room); + } + }; + + _proto29._partitionRoom = function _partitionRoom(room) { + var availX = []; + var availY = []; + + for (var i = room[0] + 1; i < room[2]; i++) { + var top = this._map[i][room[1] - 1]; + var bottom = this._map[i][room[3] + 1]; + + if (top && bottom && !(i % 2)) { + availX.push(i); + } + } + + for (var j = room[1] + 1; j < room[3]; j++) { + var left = this._map[room[0] - 1][j]; + var right = this._map[room[2] + 1][j]; + + if (left && right && !(j % 2)) { + availY.push(j); + } + } + + if (!availX.length || !availY.length) { + return; + } + + var x = RNG$1.getItem(availX); + var y = RNG$1.getItem(availY); + this._map[x][y] = 1; + var walls = []; + var w = []; + walls.push(w); + /* left part */ + + for (var _i8 = room[0]; _i8 < x; _i8++) { + this._map[_i8][y] = 1; + w.push([_i8, y]); + } + + w = []; + walls.push(w); + /* right part */ + + for (var _i9 = x + 1; _i9 <= room[2]; _i9++) { + this._map[_i9][y] = 1; + w.push([_i9, y]); + } + + w = []; + walls.push(w); + /* top part */ + + for (var _j3 = room[1]; _j3 < y; _j3++) { + this._map[x][_j3] = 1; + w.push([x, _j3]); + } + + w = []; + walls.push(w); + /* bottom part */ + + for (var _j4 = y + 1; _j4 <= room[3]; _j4++) { + this._map[x][_j4] = 1; + w.push([x, _j4]); + } + + var solid = RNG$1.getItem(walls); + + for (var _i10 = 0; _i10 < walls.length; _i10++) { + var _w = walls[_i10]; + + if (_w == solid) { + continue; + } + + var hole = RNG$1.getItem(_w); + this._map[hole[0]][hole[1]] = 0; + } + + this._stack.push([room[0], room[1], x - 1, y - 1]); + /* left top */ + + + this._stack.push([x + 1, room[1], room[2], y - 1]); + /* right top */ + + + this._stack.push([room[0], y + 1, x - 1, room[3]]); + /* left bottom */ + + + this._stack.push([x + 1, y + 1, room[2], room[3]]); + /* right bottom */ + + }; + + return DividedMaze; + }(Map); + /** + * Icey's Maze generator + * See http://www.roguebasin.roguelikedevelopment.org/index.php?title=Simple_maze for explanation + */ + + + var IceyMaze = + /*#__PURE__*/ + function (_Map6) { + _inheritsLoose(IceyMaze, _Map6); + + function IceyMaze(width, height, regularity) { + var _this17; + + if (regularity === void 0) { + regularity = 0; + } + + _this17 = _Map6.call(this, width, height) || this; + _this17._regularity = regularity; + _this17._map = []; + return _this17; + } + + var _proto30 = IceyMaze.prototype; + + _proto30.create = function create(callback) { + var width = this._width; + var height = this._height; + + var map = this._fillMap(1); + + width -= width % 2 ? 1 : 2; + height -= height % 2 ? 1 : 2; + var cx = 0; + var cy = 0; + var nx = 0; + var ny = 0; + var done = 0; + var blocked = false; + var dirs = [[0, 0], [0, 0], [0, 0], [0, 0]]; + + do { + cx = 1 + 2 * Math.floor(RNG$1.getUniform() * (width - 1) / 2); + cy = 1 + 2 * Math.floor(RNG$1.getUniform() * (height - 1) / 2); + + if (!done) { + map[cx][cy] = 0; + } + + if (!map[cx][cy]) { + this._randomize(dirs); + + do { + if (Math.floor(RNG$1.getUniform() * (this._regularity + 1)) == 0) { + this._randomize(dirs); + } + + blocked = true; + + for (var i = 0; i < 4; i++) { + nx = cx + dirs[i][0] * 2; + ny = cy + dirs[i][1] * 2; + + if (this._isFree(map, nx, ny, width, height)) { + map[nx][ny] = 0; + map[cx + dirs[i][0]][cy + dirs[i][1]] = 0; + cx = nx; + cy = ny; + blocked = false; + done++; + break; + } + } + } while (!blocked); + } + } while (done + 1 < width * height / 4); + + for (var _i11 = 0; _i11 < this._width; _i11++) { + for (var j = 0; j < this._height; j++) { + callback(_i11, j, map[_i11][j]); + } + } + + this._map = []; + return this; + }; + + _proto30._randomize = function _randomize(dirs) { + for (var i = 0; i < 4; i++) { + dirs[i][0] = 0; + dirs[i][1] = 0; + } + + switch (Math.floor(RNG$1.getUniform() * 4)) { + case 0: + dirs[0][0] = -1; + dirs[1][0] = 1; + dirs[2][1] = -1; + dirs[3][1] = 1; + break; + + case 1: + dirs[3][0] = -1; + dirs[2][0] = 1; + dirs[1][1] = -1; + dirs[0][1] = 1; + break; + + case 2: + dirs[2][0] = -1; + dirs[3][0] = 1; + dirs[0][1] = -1; + dirs[1][1] = 1; + break; + + case 3: + dirs[1][0] = -1; + dirs[0][0] = 1; + dirs[3][1] = -1; + dirs[2][1] = 1; + break; + } + }; + + _proto30._isFree = function _isFree(map, x, y, width, height) { + if (x < 1 || y < 1 || x >= width || y >= height) { + return false; + } + + return map[x][y]; + }; + + return IceyMaze; + }(Map); + /** + * Dungeon generator which uses the "orginal" Rogue dungeon generation algorithm. See http://kuoi.com/~kamikaze/GameDesign/art07_rogue_dungeon.php + * @author hyakugei + */ + + + var Rogue = + /*#__PURE__*/ + function (_Map7) { + _inheritsLoose(Rogue, _Map7); + + function Rogue(width, height, options) { + var _this18; + + _this18 = _Map7.call(this, width, height) || this; + _this18.map = []; + _this18.rooms = []; + _this18.connectedCells = []; + options = Object.assign({ + cellWidth: 3, + cellHeight: 3 // ie. as an array with min-max values for each direction.... + + }, options); + /* + Set the room sizes according to the over-all width of the map, + and the cell sizes. + */ + + if (!options.hasOwnProperty("roomWidth")) { + options["roomWidth"] = _this18._calculateRoomSize(_this18._width, options["cellWidth"]); + } + + if (!options.hasOwnProperty("roomHeight")) { + options["roomHeight"] = _this18._calculateRoomSize(_this18._height, options["cellHeight"]); + } + + _this18._options = options; + return _this18; + } + + var _proto31 = Rogue.prototype; + + _proto31.create = function create(callback) { + this.map = this._fillMap(1); + this.rooms = []; + this.connectedCells = []; + + this._initRooms(); + + this._connectRooms(); + + this._connectUnconnectedRooms(); + + this._createRandomRoomConnections(); + + this._createRooms(); + + this._createCorridors(); + + if (callback) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + callback(i, j, this.map[i][j]); + } + } + } + + return this; + }; + + _proto31._calculateRoomSize = function _calculateRoomSize(size, cell) { + var max = Math.floor(size / cell * 0.8); + var min = Math.floor(size / cell * 0.25); + + if (min < 2) { + min = 2; + } + + if (max < 2) { + max = 2; + } + + return [min, max]; + }; + + _proto31._initRooms = function _initRooms() { + // create rooms array. This is the "grid" list from the algo. + for (var i = 0; i < this._options.cellWidth; i++) { + this.rooms.push([]); + + for (var j = 0; j < this._options.cellHeight; j++) { + this.rooms[i].push({ + "x": 0, + "y": 0, + "width": 0, + "height": 0, + "connections": [], + "cellx": i, + "celly": j + }); + } + } + }; + + _proto31._connectRooms = function _connectRooms() { + //pick random starting grid + var cgx = RNG$1.getUniformInt(0, this._options.cellWidth - 1); + var cgy = RNG$1.getUniformInt(0, this._options.cellHeight - 1); + var idx; + var ncgx; + var ncgy; + var found = false; + var room; + var otherRoom; + var dirToCheck; // find unconnected neighbour cells + + do { + //dirToCheck = [0, 1, 2, 3, 4, 5, 6, 7]; + dirToCheck = [0, 2, 4, 6]; + dirToCheck = RNG$1.shuffle(dirToCheck); + + do { + found = false; + idx = dirToCheck.pop(); + ncgx = cgx + DIRS[8][idx][0]; + ncgy = cgy + DIRS[8][idx][1]; + + if (ncgx < 0 || ncgx >= this._options.cellWidth) { + continue; + } + + if (ncgy < 0 || ncgy >= this._options.cellHeight) { + continue; + } + + room = this.rooms[cgx][cgy]; + + if (room["connections"].length > 0) { + // as long as this room doesn't already coonect to me, we are ok with it. + if (room["connections"][0][0] == ncgx && room["connections"][0][1] == ncgy) { + break; + } + } + + otherRoom = this.rooms[ncgx][ncgy]; + + if (otherRoom["connections"].length == 0) { + otherRoom["connections"].push([cgx, cgy]); + this.connectedCells.push([ncgx, ncgy]); + cgx = ncgx; + cgy = ncgy; + found = true; + } + } while (dirToCheck.length > 0 && found == false); + } while (dirToCheck.length > 0); + }; + + _proto31._connectUnconnectedRooms = function _connectUnconnectedRooms() { + //While there are unconnected rooms, try to connect them to a random connected neighbor + //(if a room has no connected neighbors yet, just keep cycling, you'll fill out to it eventually). + var cw = this._options.cellWidth; + var ch = this._options.cellHeight; + this.connectedCells = RNG$1.shuffle(this.connectedCells); + var room; + var otherRoom; + var validRoom; + + for (var i = 0; i < this._options.cellWidth; i++) { + for (var j = 0; j < this._options.cellHeight; j++) { + room = this.rooms[i][j]; + + if (room["connections"].length == 0) { + var directions = [0, 2, 4, 6]; + directions = RNG$1.shuffle(directions); + validRoom = false; + + do { + var dirIdx = directions.pop(); + var newI = i + DIRS[8][dirIdx][0]; + var newJ = j + DIRS[8][dirIdx][1]; + + if (newI < 0 || newI >= cw || newJ < 0 || newJ >= ch) { + continue; + } + + otherRoom = this.rooms[newI][newJ]; + validRoom = true; + + if (otherRoom["connections"].length == 0) { + break; + } + + for (var k = 0; k < otherRoom["connections"].length; k++) { + if (otherRoom["connections"][k][0] == i && otherRoom["connections"][k][1] == j) { + validRoom = false; + break; + } + } + + if (validRoom) { + break; + } + } while (directions.length); + + if (validRoom) { + room["connections"].push([otherRoom["cellx"], otherRoom["celly"]]); + } else { + console.log("-- Unable to connect room."); + } + } + } + } + }; + + _proto31._createRandomRoomConnections = function _createRandomRoomConnections() {// Empty for now. + }; + + _proto31._createRooms = function _createRooms() { + var w = this._width; + var h = this._height; + var cw = this._options.cellWidth; + var ch = this._options.cellHeight; + var cwp = Math.floor(this._width / cw); + var chp = Math.floor(this._height / ch); + var roomw; + var roomh; + var roomWidth = this._options["roomWidth"]; + var roomHeight = this._options["roomHeight"]; + var sx; + var sy; + var otherRoom; + + for (var i = 0; i < cw; i++) { + for (var j = 0; j < ch; j++) { + sx = cwp * i; + sy = chp * j; + + if (sx == 0) { + sx = 1; + } + + if (sy == 0) { + sy = 1; + } + + roomw = RNG$1.getUniformInt(roomWidth[0], roomWidth[1]); + roomh = RNG$1.getUniformInt(roomHeight[0], roomHeight[1]); + + if (j > 0) { + otherRoom = this.rooms[i][j - 1]; + + while (sy - (otherRoom["y"] + otherRoom["height"]) < 3) { + sy++; + } + } + + if (i > 0) { + otherRoom = this.rooms[i - 1][j]; + + while (sx - (otherRoom["x"] + otherRoom["width"]) < 3) { + sx++; + } + } + + var sxOffset = Math.round(RNG$1.getUniformInt(0, cwp - roomw) / 2); + var syOffset = Math.round(RNG$1.getUniformInt(0, chp - roomh) / 2); + + while (sx + sxOffset + roomw >= w) { + if (sxOffset) { + sxOffset--; + } else { + roomw--; + } + } + + while (sy + syOffset + roomh >= h) { + if (syOffset) { + syOffset--; + } else { + roomh--; + } + } + + sx = sx + sxOffset; + sy = sy + syOffset; + this.rooms[i][j]["x"] = sx; + this.rooms[i][j]["y"] = sy; + this.rooms[i][j]["width"] = roomw; + this.rooms[i][j]["height"] = roomh; + + for (var ii = sx; ii < sx + roomw; ii++) { + for (var jj = sy; jj < sy + roomh; jj++) { + this.map[ii][jj] = 0; + } + } + } + } + }; + + _proto31._getWallPosition = function _getWallPosition(aRoom, aDirection) { + var rx; + var ry; + var door; + + if (aDirection == 1 || aDirection == 3) { + rx = RNG$1.getUniformInt(aRoom["x"] + 1, aRoom["x"] + aRoom["width"] - 2); + + if (aDirection == 1) { + ry = aRoom["y"] - 2; + door = ry + 1; + } else { + ry = aRoom["y"] + aRoom["height"] + 1; + door = ry - 1; + } + + this.map[rx][door] = 0; // i'm not setting a specific 'door' tile value right now, just empty space. + } else { + ry = RNG$1.getUniformInt(aRoom["y"] + 1, aRoom["y"] + aRoom["height"] - 2); + + if (aDirection == 2) { + rx = aRoom["x"] + aRoom["width"] + 1; + door = rx - 1; + } else { + rx = aRoom["x"] - 2; + door = rx + 1; + } + + this.map[door][ry] = 0; // i'm not setting a specific 'door' tile value right now, just empty space. + } + + return [rx, ry]; + }; + + _proto31._drawCorridor = function _drawCorridor(startPosition, endPosition) { + var xOffset = endPosition[0] - startPosition[0]; + var yOffset = endPosition[1] - startPosition[1]; + var xpos = startPosition[0]; + var ypos = startPosition[1]; + var tempDist; + var xDir; + var yDir; + var move; // 2 element array, element 0 is the direction, element 1 is the total value to move. + + var moves = []; // a list of 2 element arrays + + var xAbs = Math.abs(xOffset); + var yAbs = Math.abs(yOffset); + var percent = RNG$1.getUniform(); // used to split the move at different places along the long axis + + var firstHalf = percent; + var secondHalf = 1 - percent; + xDir = xOffset > 0 ? 2 : 6; + yDir = yOffset > 0 ? 4 : 0; + + if (xAbs < yAbs) { + // move firstHalf of the y offset + tempDist = Math.ceil(yAbs * firstHalf); + moves.push([yDir, tempDist]); // move all the x offset + + moves.push([xDir, xAbs]); // move sendHalf of the y offset + + tempDist = Math.floor(yAbs * secondHalf); + moves.push([yDir, tempDist]); + } else { + // move firstHalf of the x offset + tempDist = Math.ceil(xAbs * firstHalf); + moves.push([xDir, tempDist]); // move all the y offset + + moves.push([yDir, yAbs]); // move secondHalf of the x offset. + + tempDist = Math.floor(xAbs * secondHalf); + moves.push([xDir, tempDist]); + } + + this.map[xpos][ypos] = 0; + + while (moves.length > 0) { + move = moves.pop(); + + while (move[1] > 0) { + xpos += DIRS[8][move[0]][0]; + ypos += DIRS[8][move[0]][1]; + this.map[xpos][ypos] = 0; + move[1] = move[1] - 1; + } + } + }; + + _proto31._createCorridors = function _createCorridors() { + // Draw Corridors between connected rooms + var cw = this._options.cellWidth; + var ch = this._options.cellHeight; + var room; + var connection; + var otherRoom; + var wall; + var otherWall; + + for (var i = 0; i < cw; i++) { + for (var j = 0; j < ch; j++) { + room = this.rooms[i][j]; + + for (var k = 0; k < room["connections"].length; k++) { + connection = room["connections"][k]; + otherRoom = this.rooms[connection[0]][connection[1]]; // figure out what wall our corridor will start one. + // figure out what wall our corridor will end on. + + if (otherRoom["cellx"] > room["cellx"]) { + wall = 2; + otherWall = 4; + } else if (otherRoom["cellx"] < room["cellx"]) { + wall = 4; + otherWall = 2; + } else if (otherRoom["celly"] > room["celly"]) { + wall = 3; + otherWall = 1; + } else { + wall = 1; + otherWall = 3; + } + + this._drawCorridor(this._getWallPosition(room, wall), this._getWallPosition(otherRoom, otherWall)); + } + } + } + }; + + return Rogue; + }(Map); + + var index$2 = { + Arena: Arena, + Uniform: Uniform, + Cellular: Cellular, + Digger: Digger, + EllerMaze: EllerMaze, + DividedMaze: DividedMaze, + IceyMaze: IceyMaze, + Rogue: Rogue + }; + /** + * Base noise generator + */ + + var Noise = function Noise() {}; + + var F2 = 0.5 * (Math.sqrt(3) - 1); + var G2 = (3 - Math.sqrt(3)) / 6; + /** + * A simple 2d implementation of simplex noise by Ondrej Zara + * + * Based on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. + * Which is based on example code by Stefan Gustavson (stegu@itn.liu.se). + * With Optimisations by Peter Eastman (peastman@drizzle.stanford.edu). + * Better rank ordering method by Stefan Gustavson in 2012. + */ + + var Simplex = + /*#__PURE__*/ + function (_Noise) { + _inheritsLoose(Simplex, _Noise); + + /** + * @param gradients Random gradients + */ + function Simplex(gradients) { + var _this19; + + if (gradients === void 0) { + gradients = 256; + } + + _this19 = _Noise.call(this) || this; + _this19._gradients = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1]]; + var permutations = []; + + for (var i = 0; i < gradients; i++) { + permutations.push(i); + } + + permutations = RNG$1.shuffle(permutations); + _this19._perms = []; + _this19._indexes = []; + + for (var _i12 = 0; _i12 < 2 * gradients; _i12++) { + _this19._perms.push(permutations[_i12 % gradients]); + + _this19._indexes.push(_this19._perms[_i12] % _this19._gradients.length); + } + + return _this19; + } + + var _proto32 = Simplex.prototype; + + _proto32.get = function get(xin, yin) { + var perms = this._perms; + var indexes = this._indexes; + var count = perms.length / 2; + var n0 = 0, + n1 = 0, + n2 = 0, + gi; // Noise contributions from the three corners + // Skew the input space to determine which simplex cell we're in + + var s = (xin + yin) * F2; // Hairy factor for 2D + + var i = Math.floor(xin + s); + var j = Math.floor(yin + s); + var t = (i + j) * G2; + var X0 = i - t; // Unskew the cell origin back to (x,y) space + + var Y0 = j - t; + var x0 = xin - X0; // The x,y distances from the cell origin + + var y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. + // Determine which simplex we are in. + + var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords + + if (x0 > y0) { + i1 = 1; + j1 = 0; + } else { + // lower triangle, XY order: (0,0)->(1,0)->(1,1) + i1 = 0; + j1 = 1; + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + + + var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + + var y1 = y0 - j1 + G2; + var x2 = x0 - 1 + 2 * G2; // Offsets for last corner in (x,y) unskewed coords + + var y2 = y0 - 1 + 2 * G2; // Work out the hashed gradient indices of the three simplex corners + + var ii = mod(i, count); + var jj = mod(j, count); // Calculate the contribution from the three corners + + var t0 = 0.5 - x0 * x0 - y0 * y0; + + if (t0 >= 0) { + t0 *= t0; + gi = indexes[ii + perms[jj]]; + var grad = this._gradients[gi]; + n0 = t0 * t0 * (grad[0] * x0 + grad[1] * y0); + } + + var t1 = 0.5 - x1 * x1 - y1 * y1; + + if (t1 >= 0) { + t1 *= t1; + gi = indexes[ii + i1 + perms[jj + j1]]; + var _grad = this._gradients[gi]; + n1 = t1 * t1 * (_grad[0] * x1 + _grad[1] * y1); + } + + var t2 = 0.5 - x2 * x2 - y2 * y2; + + if (t2 >= 0) { + t2 *= t2; + gi = indexes[ii + 1 + perms[jj + 1]]; + var _grad2 = this._gradients[gi]; + n2 = t2 * t2 * (_grad2[0] * x2 + _grad2[1] * y2); + } // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + + + return 70 * (n0 + n1 + n2); + }; + + return Simplex; + }(Noise); + + var index$3 = { + Simplex: Simplex + }; + /** + * @class Abstract pathfinder + * @param {int} toX Target X coord + * @param {int} toY Target Y coord + * @param {function} passableCallback Callback to determine map passability + * @param {object} [options] + * @param {int} [options.topology=8] + */ + + var Path = + /*#__PURE__*/ + function () { + function Path(toX, toY, passableCallback, options) { + if (options === void 0) { + options = {}; + } + + this._toX = toX; + this._toY = toY; + this._passableCallback = passableCallback; + this._options = Object.assign({ + topology: 8 + }, options); + this._dirs = DIRS[this._options.topology]; + + if (this._options.topology == 8) { + /* reorder dirs for more aesthetic result (vertical/horizontal first) */ + this._dirs = [this._dirs[0], this._dirs[2], this._dirs[4], this._dirs[6], this._dirs[1], this._dirs[3], this._dirs[5], this._dirs[7]]; + } + } + + var _proto33 = Path.prototype; + + _proto33._getNeighbors = function _getNeighbors(cx, cy) { + var result = []; + + for (var i = 0; i < this._dirs.length; i++) { + var dir = this._dirs[i]; + var x = cx + dir[0]; + var y = cy + dir[1]; + + if (!this._passableCallback(x, y)) { + continue; + } + + result.push([x, y]); + } + + return result; + }; + + return Path; + }(); + /** + * @class Simplified Dijkstra's algorithm: all edges have a value of 1 + * @augments ROT.Path + * @see ROT.Path + */ + + + var Dijkstra = + /*#__PURE__*/ + function (_Path) { + _inheritsLoose(Dijkstra, _Path); + + function Dijkstra(toX, toY, passableCallback, options) { + var _this20; + + _this20 = _Path.call(this, toX, toY, passableCallback, options) || this; + _this20._computed = {}; + _this20._todo = []; + + _this20._add(toX, toY, null); + + return _this20; + } + /** + * Compute a path from a given point + * @see ROT.Path#compute + */ + + + var _proto34 = Dijkstra.prototype; + + _proto34.compute = function compute(fromX, fromY, callback) { + var key = fromX + "," + fromY; + + if (!(key in this._computed)) { + this._compute(fromX, fromY); + } + + if (!(key in this._computed)) { + return; + } + + var item = this._computed[key]; + + while (item) { + callback(item.x, item.y); + item = item.prev; + } + }; + /** + * Compute a non-cached value + */ + + + _proto34._compute = function _compute(fromX, fromY) { + while (this._todo.length) { + var item = this._todo.shift(); + + if (item.x == fromX && item.y == fromY) { + return; + } + + var neighbors = this._getNeighbors(item.x, item.y); + + for (var i = 0; i < neighbors.length; i++) { + var neighbor = neighbors[i]; + var x = neighbor[0]; + var y = neighbor[1]; + var id = x + "," + y; + + if (id in this._computed) { + continue; + } + /* already done */ + + + this._add(x, y, item); + } + } + }; + + _proto34._add = function _add(x, y, prev) { + var obj = { + x: x, + y: y, + prev: prev + }; + this._computed[x + "," + y] = obj; + + this._todo.push(obj); + }; + + return Dijkstra; + }(Path); + /** + * @class Simplified A* algorithm: all edges have a value of 1 + * @augments ROT.Path + * @see ROT.Path + */ + + + var AStar = + /*#__PURE__*/ + function (_Path2) { + _inheritsLoose(AStar, _Path2); + + function AStar(toX, toY, passableCallback, options) { + var _this21; + + if (options === void 0) { + options = {}; + } + + _this21 = _Path2.call(this, toX, toY, passableCallback, options) || this; + _this21._todo = []; + _this21._done = {}; + return _this21; + } + /** + * Compute a path from a given point + * @see ROT.Path#compute + */ + + + var _proto35 = AStar.prototype; + + _proto35.compute = function compute(fromX, fromY, callback) { + this._todo = []; + this._done = {}; + this._fromX = fromX; + this._fromY = fromY; + + this._add(this._toX, this._toY, null); + + while (this._todo.length) { + var _item = this._todo.shift(); + + var id = _item.x + "," + _item.y; + + if (id in this._done) { + continue; + } + + this._done[id] = _item; + + if (_item.x == fromX && _item.y == fromY) { + break; + } + + var neighbors = this._getNeighbors(_item.x, _item.y); + + for (var i = 0; i < neighbors.length; i++) { + var neighbor = neighbors[i]; + var x = neighbor[0]; + var y = neighbor[1]; + + var _id3 = x + "," + y; + + if (_id3 in this._done) { + continue; + } + + this._add(x, y, _item); + } + } + + var item = this._done[fromX + "," + fromY]; + + if (!item) { + return; + } + + while (item) { + callback(item.x, item.y); + item = item.prev; + } + }; + + _proto35._add = function _add(x, y, prev) { + var h = this._distance(x, y); + + var obj = { + x: x, + y: y, + prev: prev, + g: prev ? prev.g + 1 : 0, + h: h + }; + /* insert into priority queue */ + + var f = obj.g + obj.h; + + for (var i = 0; i < this._todo.length; i++) { + var item = this._todo[i]; + var itemF = item.g + item.h; + + if (f < itemF || f == itemF && h < item.h) { + this._todo.splice(i, 0, obj); + + return; + } + } + + this._todo.push(obj); + }; + + _proto35._distance = function _distance(x, y) { + switch (this._options.topology) { + case 4: + return Math.abs(x - this._fromX) + Math.abs(y - this._fromY); + break; + + case 6: + var dx = Math.abs(x - this._fromX); + var dy = Math.abs(y - this._fromY); + return dy + Math.max(0, (dx - dy) / 2); + break; + + case 8: + return Math.max(Math.abs(x - this._fromX), Math.abs(y - this._fromY)); + break; + } + }; + + return AStar; + }(Path); + + var index$4 = { + Dijkstra: Dijkstra, + AStar: AStar + }; + /** + * @class Asynchronous main loop + * @param {ROT.Scheduler} scheduler + */ + + var Engine = + /*#__PURE__*/ + function () { + function Engine(scheduler) { + this._scheduler = scheduler; + this._lock = 1; + } + /** + * Start the main loop. When this call returns, the loop is locked. + */ + + + var _proto36 = Engine.prototype; + + _proto36.start = function start() { + return this.unlock(); + }; + /** + * Interrupt the engine by an asynchronous action + */ + + + _proto36.lock = function lock() { + this._lock++; + return this; + }; + /** + * Resume execution (paused by a previous lock) + */ + + + _proto36.unlock = function unlock() { + if (!this._lock) { + throw new Error("Cannot unlock unlocked engine"); + } + + this._lock--; + + while (!this._lock) { + var actor = this._scheduler.next(); + + if (!actor) { + return this.lock(); + } + /* no actors */ + + + var result = actor.act(); + + if (result && result.then) { + /* actor returned a "thenable", looks like a Promise */ + this.lock(); + result.then(this.unlock.bind(this)); + } + } + + return this; + }; + + return Engine; + }(); + /** + * Lighting computation, based on a traditional FOV for multiple light sources and multiple passes. + */ + + + var Lighting = + /*#__PURE__*/ + function () { + function Lighting(reflectivityCallback, options) { + if (options === void 0) { + options = {}; + } + + this._reflectivityCallback = reflectivityCallback; + this._options = {}; + options = Object.assign({ + passes: 1, + emissionThreshold: 100, + range: 10 + }, options); + this._lights = {}; + this._reflectivityCache = {}; + this._fovCache = {}; + this.setOptions(options); + } + /** + * Adjust options at runtime + */ + + + var _proto37 = Lighting.prototype; + + _proto37.setOptions = function setOptions(options) { + Object.assign(this._options, options); + + if (options && options.range) { + this.reset(); + } + + return this; + }; + /** + * Set the used Field-Of-View algo + */ + + + _proto37.setFOV = function setFOV(fov) { + this._fov = fov; + this._fovCache = {}; + return this; + }; + /** + * Set (or remove) a light source + */ + + + _proto37.setLight = function setLight(x, y, color) { + var key = x + "," + y; + + if (color) { + this._lights[key] = typeof color == "string" ? fromString(color) : color; + } else { + delete this._lights[key]; + } + + return this; + }; + /** + * Remove all light sources + */ + + + _proto37.clearLights = function clearLights() { + this._lights = {}; + }; + /** + * Reset the pre-computed topology values. Call whenever the underlying map changes its light-passability. + */ + + + _proto37.reset = function reset() { + this._reflectivityCache = {}; + this._fovCache = {}; + return this; + }; + /** + * Compute the lighting + */ + + + _proto37.compute = function compute(lightingCallback) { + var doneCells = {}; + var emittingCells = {}; + var litCells = {}; + + for (var key in this._lights) { + /* prepare emitters for first pass */ + var light = this._lights[key]; + emittingCells[key] = [0, 0, 0]; + add_(emittingCells[key], light); + } + + for (var i = 0; i < this._options.passes; i++) { + /* main loop */ + this._emitLight(emittingCells, litCells, doneCells); + + if (i + 1 == this._options.passes) { + continue; + } + /* not for the last pass */ + + + emittingCells = this._computeEmitters(litCells, doneCells); + } + + for (var litKey in litCells) { + /* let the user know what and how is lit */ + var parts = litKey.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + lightingCallback(x, y, litCells[litKey]); + } + + return this; + }; + /** + * Compute one iteration from all emitting cells + * @param emittingCells These emit light + * @param litCells Add projected light to these + * @param doneCells These already emitted, forbid them from further calculations + */ + + + _proto37._emitLight = function _emitLight(emittingCells, litCells, doneCells) { + for (var key in emittingCells) { + var parts = key.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + + this._emitLightFromCell(x, y, emittingCells[key], litCells); + + doneCells[key] = 1; + } + + return this; + }; + /** + * Prepare a list of emitters for next pass + */ + + + _proto37._computeEmitters = function _computeEmitters(litCells, doneCells) { + var result = {}; + + for (var key in litCells) { + if (key in doneCells) { + continue; + } + /* already emitted */ + + + var _color = litCells[key]; + var reflectivity = void 0; + + if (key in this._reflectivityCache) { + reflectivity = this._reflectivityCache[key]; + } else { + var parts = key.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + reflectivity = this._reflectivityCallback(x, y); + this._reflectivityCache[key] = reflectivity; + } + + if (reflectivity == 0) { + continue; + } + /* will not reflect at all */ + + /* compute emission color */ + + + var emission = [0, 0, 0]; + var intensity = 0; + + for (var i = 0; i < 3; i++) { + var part = Math.round(_color[i] * reflectivity); + emission[i] = part; + intensity += part; + } + + if (intensity > this._options.emissionThreshold) { + result[key] = emission; + } + } + + return result; + }; + /** + * Compute one iteration from one cell + */ + + + _proto37._emitLightFromCell = function _emitLightFromCell(x, y, color, litCells) { + var key = x + "," + y; + var fov; + + if (key in this._fovCache) { + fov = this._fovCache[key]; + } else { + fov = this._updateFOV(x, y); + } + + for (var fovKey in fov) { + var formFactor = fov[fovKey]; + var result = void 0; + + if (fovKey in litCells) { + /* already lit */ + result = litCells[fovKey]; + } else { + /* newly lit */ + result = [0, 0, 0]; + litCells[fovKey] = result; + } + + for (var i = 0; i < 3; i++) { + result[i] += Math.round(color[i] * formFactor); + } + /* add light color */ + + } + + return this; + }; + /** + * Compute FOV ("form factor") for a potential light source at [x,y] + */ + + + _proto37._updateFOV = function _updateFOV(x, y) { + var key1 = x + "," + y; + var cache = {}; + this._fovCache[key1] = cache; + var range = this._options.range; + + function cb(x, y, r, vis) { + var key2 = x + "," + y; + var formFactor = vis * (1 - r / range); + + if (formFactor == 0) { + return; + } + + cache[key2] = formFactor; + } + + this._fov.compute(x, y, range, cb.bind(this)); + + return cache; + }; + + return Lighting; + }(); + + var Util = util; + var Color = color; + var Text = text; + exports.Util = Util; + exports.Color = Color; + exports.Text = Text; + exports.RNG = RNG$1; + exports.Display = Display; + exports.StringGenerator = StringGenerator; + exports.EventQueue = EventQueue; + exports.Scheduler = index; + exports.FOV = index$1; + exports.Map = index$2; + exports.Noise = index$3; + exports.Path = index$4; + exports.Engine = Engine; + exports.Lighting = Lighting; + exports.DEFAULT_WIDTH = DEFAULT_WIDTH; + exports.DEFAULT_HEIGHT = DEFAULT_HEIGHT; + exports.DIRS = DIRS; + exports.KEYS = KEYS; + Object.defineProperty(exports, '__esModule', { + value: true + }); +}); + diff --git a/html/js/rot.min.js b/html/js/rot.min.js new file mode 100644 index 0000000..c8d1f38 --- /dev/null +++ b/html/js/rot.min.js @@ -0,0 +1,138 @@ +var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(g,p,r){g!=Array.prototype&&g!=Object.prototype&&(g[p]=r.value)};$jscomp.getGlobal=function(g){return"undefined"!=typeof window&&window===g?g:"undefined"!=typeof global&&null!=global?global:g};$jscomp.global=$jscomp.getGlobal(this); +$jscomp.polyfill=function(g,p,r,t){if(p){r=$jscomp.global;g=g.split(".");for(t=0;tr&&(r=Math.max(0,p+r));if(null==t||t>p)t=p;t=Number(t);0>t&&(t=Math.max(0,p+t));for(r=Number(r||0);rg||1342177279>>=1)p+=p;return t}},"es6","es3");$jscomp.stringPadding=function(g,p){g=void 0!==g?String(g):" ";return 0a?a:d}function t(d){return d.charAt(0).toUpperCase()+d.substring(1)}function w(d){for(var c=arguments.length,a=Array(1c;c++)a[c+1]+=16*a[c],a.splice(c,1);else a=(c=d.match(/rgb\(([0-9, ]+)\)/i))? +c[1].split(/\s*,\s*/).map(function(b){return parseInt(b)}):[0,0,0];Q[d]=a}return a.slice()}function Y(d){for(var c=arguments.length,a=Array(1c;c++)for(b=0;be;e++)b[e]=Math.round(b[e]+a*(c[e]-d[e]));return b}function aa(d,c,a){void 0===a&&(a=.5);d=R(d);c=R(c);for(var b=0;3>b;b++)d[b]+=a*(c[b]-d[b]);return ba(d)}function R(d){var c=d[0]/255,a=d[1]/255; +d=d[2]/255;var b=Math.max(c,a,d),e=Math.min(c,a,d),f=0,m=(b+e)/2;if(b==e)e=0;else{var k=b-e;e=.5a&&(a+=1);1a?c:a<2/3?d+(c-d)*(2/3-a)*6:d}function ba(d){var c=d[2];if(0==d[1])return c=Math.round(255*c),[c,c,c];var a=d[1];a=.5>c?c*(1+a):c+a-c*a;var b=2*c-a;c=S(b,a,d[0]+1/3);var e=S(b,a,d[0]);d=S(b,a,d[0]-1/3);return[Math.round(255* +c),Math.round(255*e),Math.round(255*d)]}function fa(d,c,a){var b=d.createShader(d.VERTEX_SHADER);d.shaderSource(b,c);d.compileShader(b);if(!d.getShaderParameter(b,d.COMPILE_STATUS))throw Error(d.getShaderInfoLog(b)||"");c=d.createShader(d.FRAGMENT_SHADER);d.shaderSource(c,a);d.compileShader(c);if(!d.getShaderParameter(c,d.COMPILE_STATUS))throw Error(d.getShaderInfoLog(c)||"");a=d.createProgram();d.attachShader(a,b);d.attachShader(a,c);d.linkProgram(a);if(!d.getProgramParameter(a,d.LINK_STATUS))throw Error(d.getProgramInfoLog(a)|| +"");return a}function ha(d){var c=new Float32Array([0,0,1,0,0,1,1,1]),a=d.createBuffer();d.bindBuffer(d.ARRAY_BUFFER,a);d.bufferData(d.ARRAY_BUFFER,c,d.STATIC_DRAW);d.enableVertexAttribArray(0);d.vertexAttribPointer(0,2,d.FLOAT,!1,0,0)}function M(d){if(!(d in T)){if("transparent"==d)var c=[0,0,0,0];else if(-1a;a++)c[a]/=255}else c=L(d).map(function(b){return b/255}),c.push(1);T[d]=c}return T[d]}function U(d){d=L(d);return 36* +Math.floor(.0234375*d[0])+6*Math.floor(.0234375*d[1])+1*Math.floor(.0234375*d[2])+16}function V(d,c){var a=[],b=0;d.replace(ia,function(e,m,k,h){var f=d.substring(b,h);f.length&&a.push({type:0,value:f});a.push({type:"c"==m?2:3,value:k.trim()});b=h+e.length;return""});var e=d.substring(b);e.length&&a.push({type:0,value:e});return ja(a,c)}function ja(d,c){c||(c=Infinity);for(var a=0,b=0,e=-1;ac){for(m=-1;;){var k=f.value.indexOf(" ",m+1);if(-1==k)break;if(b+k>c)break;m=k}-1!=m?f.value=N(d,a,m,!0):-1!=e?(a=d[e],f=a.value.lastIndexOf(" "),a.value=N(d,e,f,!0),a=e):f.value=N(d,a,c-b,!1)}else b+=f.value.length,-1!=f.value.indexOf(" ")&&(e=a);a++}else d.splice(a,1)}}d.push({type:1});c=null;for(b= +0;ba?1/a:a;this._s0=2.3283064365386963E-10*(a>>>0);a=69069*a+1>>>0;this._s1=2.3283064365386963E-10*a;this._s2=2.3283064365386963E-10*(69069*a+1>>>0);this._c=1;return this};c.getUniform=function(){var a=2091639*this._s0+2.3283064365386963E-10*this._c;this._s0=this._s1;this._s1=this._s2;this._c=a|0;return this._s2=a-this._c};c.getUniformInt=function(a,b){var e=Math.max(a,b);a=Math.min(a,b);return Math.floor(this.getUniform()* +(e-a+1))+a};c.getNormal=function(a,b){void 0===a&&(a=0);void 0===b&&(b=1);do{var e=2*this.getUniform()-1;var f=2*this.getUniform()-1;f=e*e+f*f}while(1b||0>e||b>=f.width||e>=f.height?[-1,-1]:this._normalizedEventToPosition(b,e)};return c}(I);w.map={s:"toString"};var ka=Object.freeze({mod:p,clamp:r,capitalize:t,format:w}),O=function(d){function c(){var b=d.call(this)||this; +b._spacingX=0;b._spacingY=0;b._hexSize=0;return b}_inheritsLoose(c,d);var a=c.prototype;a.draw=function(b,e){var f=b[2],a=b[3],k=b[4];b=[(b[0]+1)*this._spacingX,b[1]*this._spacingY+this._hexSize];this._options.transpose&&b.reverse();e&&(this._ctx.fillStyle=k,this._fill(b[0],b[1]));if(f)for(this._ctx.fillStyle=a,e=[].concat(f),f=0;fa;a++)for(e=0;ea;a++){for(e=0;e< +b.length;e++)c[a]*=b[e][a]/255;c[a]=Math.round(c[a])}return c},multiply_:function(d){for(var c=arguments.length,a=Array(1c;c++){for(b=0;ba;a++)d[a]+=c instanceof Array?Math.round(q.getNormal(0,c[a])):c;return d},rgb2hsl:R,hsl2rgb:ba, +toRGB:function(d){return"rgb("+d.map(function(c){return r(c,0,255)}).join(",")+")"},toHex:function(d){return"#"+d.map(function(c){return r(c,0,255).toString(16).padStart(2,"0")}).join("")}});var x=function(d){function c(){var b=d.call(this)||this;b._uniforms={};try{b._gl=b._initWebGL()}catch(e){alert(e.message)}return b}_inheritsLoose(c,d);c.isSupported=function(){return!!document.createElement("canvas").getContext("webgl2",{preserveDrawingBuffer:!0})};var a=c.prototype;a.schedule=function(b){requestAnimationFrame(b)}; +a.getContainer=function(){return this._gl.canvas};a.setOptions=function(b){var e=this;d.prototype.setOptions.call(this,b);this._updateSize();var f=this._options.tileSet;f&&"complete"in f&&!f.complete?f.addEventListener("load",function(){return e._updateTexture(f)}):this._updateTexture(f)};a.draw=function(b,e){var f=this._gl,a=this._options,k=b[0],h=b[1],c=b[2],d=b[3];b=b[4];f.scissor(k*a.tileWidth,f.canvas.height-(h+1)*a.tileHeight,a.tileWidth,a.tileHeight);e&&(a.tileColorize?f.clearColor(0,0,0,0): +f.clearColor.apply(f,M(b)),f.clear(f.COLOR_BUFFER_BIT));if(c)for(e=[].concat(c),c=[].concat(b),d=[].concat(d),f.uniform2fv(this._uniforms.targetPosRel,[k,h]),k=0;k +b||0>e||b>=f.width||e>=f.height?[-1,-1]:this._normalizedEventToPosition(b,e)};a._initWebGL=function(){var b=this,e=document.createElement("canvas").getContext("webgl2",{preserveDrawingBuffer:!0});window.gl=e;var f=fa(e,la,ma);e.useProgram(f);ha(e);na.forEach(function(a){return b._uniforms[a]=e.getUniformLocation(f,a)});this._program=f;e.enable(e.BLEND);e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);e.enable(e.SCISSOR_TEST);return e};a._normalizedEventToPosition= +function(b,e){return[Math.floor(b/this._options.tileWidth),Math.floor(e/this._options.tileHeight)]};a._updateSize=function(){var b=this._gl,e=this._options,a=[e.width*e.tileWidth,e.height*e.tileHeight];b.canvas.width=a[0];b.canvas.height=a[1];b.viewport(0,0,a[0],a[1]);b.uniform2fv(this._uniforms.tileSize,[e.tileWidth,e.tileHeight]);b.uniform2fv(this._uniforms.targetSize,a)};a._updateTexture=function(b){var e=this._gl,a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER, +e.NEAREST);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT);e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,b)};return c}(I),na="targetPosRel tilesetPosAbs tileSize targetSize colorize bg tint".split(" "),la="#version 300 es\n\nin vec2 tilePosRel;\nout vec2 tilesetPosPx;\n\nuniform vec2 tilesetPosAbs;\nuniform vec2 tileSize;\nuniform vec2 targetSize;\nuniform vec2 targetPosRel;\n\nvoid main() {\n\tvec2 targetPosPx = (targetPosRel + tilePosRel) * tileSize;\n\tvec2 targetPosNdc = ((targetPosPx / targetSize)-0.5)*2.0;\n\ttargetPosNdc.y *= -1.0;\n\n\tgl_Position = vec4(targetPosNdc, 0.0, 1.0);\n\ttilesetPosPx = tilesetPosAbs + tilePosRel * tileSize;\n}", +ma="#version 300 es\nprecision highp float;\n\nin vec2 tilesetPosPx;\nout vec4 fragColor;\nuniform sampler2D image;\nuniform bool colorize;\nuniform vec4 bg;\nuniform vec4 tint;\n\nvoid main() {\n\tfragColor = vec4(0, 0, 0, 1);\n\n\tvec4 texel = texelFetch(image, ivec2(tilesetPosPx), 0);\n\n\tif (colorize) {\n\t\ttexel.rgb = tint.a * tint.rgb + (1.0-tint.a) * texel.rgb;\n\t\tfragColor.rgb = texel.a*texel.rgb + (1.0-texel.a)*bg.rgb;\n\t\tfragColor.a = texel.a + (1.0-texel.a)*bg.a;\n\t} else {\n\t\tfragColor = texel;\n\t}\n}", +T={},u=function(d){function c(){var b=d.call(this)||this;b._offset=[0,0];b._cursor=[-1,-1];b._lastColor="";return b}_inheritsLoose(c,d);var a=c.prototype;a.schedule=function(b){setTimeout(b,1E3/60)};a.setOptions=function(b){d.prototype.setOptions.call(this,b);var e=[b.width,b.height];this._offset=this.computeSize().map(function(b,a){return Math.floor((b-e[a])/2)})};a.clear=function(){process.stdout.write("\u001b[0;48;5;"+U(this._options.bg)+"m\u001b[2J")};a.draw=function(b,e){var a=b[2],m=b[3],k= +b[4],c=this._offset[0]+b[0],d=this._offset[1]+b[1];b=this.computeSize();if(!(0>c||c>=b[0]||0>d||d>=b[1])){if(c!==this._cursor[0]||d!==this._cursor[1])process.stdout.write("\u001b["+(d+1)+";"+(c+1)+"H"),this._cursor[0]=c,this._cursor[1]=d;e&&(a||(a=" "));a&&(e="\u001b[0;38;5;"+U(m)+";48;5;"+U(k)+"m",e!==this._lastColor&&(process.stdout.write(e),this._lastColor=e),a=[].concat(a),process.stdout.write(a[0]),this._cursor[0]++,this._cursor[0]>=b[0]&&(this._cursor[0]=0,this._cursor[1]++))}};a.computeFontSize= +function(){throw Error("Terminal backend has no notion of font size");};a.eventToPosition=function(b,e){return[b,e]};a.computeSize=function(){return[process.stdout.columns,process.stdout.rows]};return c}(I),ia=/%([bc]){([^}]*)}/g;I=Object.freeze({TYPE_TEXT:0,TYPE_NEWLINE:1,TYPE_FG:2,TYPE_BG:3,measure:function(d,c){var a={width:0,height:1};d=V(d,c);for(var b=c=0;bl||65500l||65518this._options.order?a=a.slice(-this._options.order):a.lengthb){e=f;break}this._events.splice(e,0,a);this._eventTimes.splice(e,0,b)};c.get=function(){if(!this._events.length)return null;var a=this._eventTimes.splice(0,1)[0];if(0b)return e=this._visibleCoords(0,e,a,m),b=this._visibleCoords(360+b,360,a,m),e||b;for(var f=0;fe[0])return b=this._checkVisibility(b,[b[1],b[1]],a,c),e=this._checkVisibility([0,1],e,a,c),(b+e)/2;for(var f=0,m=!1;fd&&f%2&&(g=!1);if(!g)return 0;m=d-f+1;if(m%2)f%2?(d=c[f],d=(e[0]*d[1]-d[0]*e[1])/(d[1]*e[1]),a&&c.splice(f,m,e)):(d=c[d],d=(d[0]*b[1]-b[0]*d[1])/(b[1]*d[1]),a&&c.splice(f,m,b));else if(f%2)l=c[f],d=c[d],d=(d[0]*l[1]-l[0]*d[1])/(l[1]*d[1]),a&&c.splice(f,m);else return a&&c.splice(f,m,b,e),1;return d/((e[0]*b[1]-b[0]*e[1])/(b[1]*e[1]))};return c}(u);var C=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1, +0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]];u=function(d){function c(){return d.apply(this,arguments)||this}_inheritsLoose(c,d);var a=c.prototype;a.compute=function(b,e,a,c){c(b,e,0,1);for(var f=0;f=f;){f+=1;var z=b+f*n+m*l,y=e+f*g+m*q,r=(f-.5)/(m+.5),t=(f+.5)/(m-.5);if(!(t>c)){if(rthis._options.timeLimit)return null;this._map=this._fillMap(1);this._dug=0;this._rooms=[];this._unconnected=[];this._generateRooms();if(!(2>this._rooms.length)&&this._generateCorridors())break}if(b)for(a=0;athis._options.roomDugPercentage)break}while(f)};a._generateRoom=function(){for(var b=0;b=n&&d[e]<=l){c=d.slice();n=0;switch(h){case 0:n=a.getTop()- +1;break;case 1:n=a.getRight()+1;break;case 2:n=a.getBottom()+1;break;case 3:n=a.getLeft()-1}c[(e+1)%2]=n;this._digLine([d,c])}else if(d[e]l+1){c=d[e]-c[e];n=0;switch(h){case 0:case 1:n=0>c?3:1;break;case 2:case 3:n=0>c?1:3}c=this._placeInWall(a,(h+n)%4);if(!c)return!1;h=[0,0];h[e]=d[e];e=(e+1)%2;h[e]=c[e];this._digLine([d,h,c])}else{n=(e+1)%2;c=this._placeInWall(a,h);if(!c)return!1;h=Math.round((c[n]+d[n])/2);l=[0,0];var g=[0,0];l[e]=d[e];l[n]=h;g[e]=c[e];g[n]=h;this._digLine([d,l,g,c])}b.addDoor(d[0], +d[1]);a.addDoor(c[0],c[1]);e=this._unconnected.indexOf(b);-1!=e&&(this._unconnected.splice(e,1),this._connected.push(b));e=this._unconnected.indexOf(a);-1!=e&&(this._unconnected.splice(e,1),this._connected.push(a));return!0};a._placeInWall=function(b,a){var e=[0,0],c=[0,0],d=0;switch(a){case 0:c=[1,0];e=[b.getLeft(),b.getTop()-1];d=b.getRight()-b.getLeft()+1;break;case 1:c=[0,1];e=[b.getRight()+1,b.getTop()];d=b.getBottom()-b.getTop()+1;break;case 2:c=[1,0];e=[b.getLeft(),b.getBottom()+1];d=b.getRight()- +b.getLeft()+1;break;case 3:c=[0,1],e=[b.getLeft()-1,b.getTop()],d=b.getBottom()-b.getTop()+1}b=[];a=-2;for(var h=0;hb||0>a||b>=this._width||a>=this._height?!1:1==this._map[b][a]};a._canBeDugCallback=function(b,a){return 1>b||1>a||b+1>=this._width||a+1>=this._height?!1:1==this._map[b][a]};return c}(H);var E=function(d){function c(b,a,f){void 0===f&&(f={});b=d.call(this,b,a)||this;b._options={born:[5,6,7,8],survive:[4,5,6,7,8],topology:8};b.setOptions(f);b._dirs=v[b._options.topology];b._map=b._fillMap(0);return b}_inheritsLoose(c,d);var a=c.prototype; +a.randomize=function(b){for(var a=0;ah||h>=this._width||0>d||d>=this._height||(e+=1==this._map[h][d]?1:0)}return e};a.connect=function(b,a,f){a||(a=0);var e=[],c={},d=1,n=[0,0];6==this._options.topology&& +(d=2,n=[0,1]);for(var l=0;ll&&!(h.lengthd);l++);return[e,c]};a._getClosest=function(b,a){var e=null,c=null,d;for(d in a){var h=a[d],n=(h[0]-b[0])*(h[0]-b[0])+(h[1]- +b[1])*(h[1]-b[1]);if(null==c||nf[1]&&(e--, +g=1);m=mf[0]?m-g:f[1]%2?m-g:m+g;this._map[m][e]=k;g=[m,e];var q=this._pointKey(g);c[q]=g;delete d[q]}h&&h(a,b)};a._freeSpace=function(b,a,f){return 0<=b&&bthis._options.timeLimit)break;var d=this._findWall();if(!d)break;var h=d.split(",");d=parseInt(h[0]);h=parseInt(h[1]);var g=this._getDiggingDirection(d,h);if(g){var l=0;do if(l++,this._tryFeature(d,h,g[0],g[1])){this._removeSurroundingWalls(d,h);this._removeSurroundingWalls(d-g[0],h-g[1]);break}while(l< +this._featureAttempts);for(var q in this._walls)1b||0>a||b>=this._width||a>=this._height?!1:1==this._map[b][a]};a._canBeDugCallback=function(b,a){return 1> +b||1>a||b+1>=this._width||a+1>=this._height?!1:1==this._map[b][a]};a._priorityWallCallback=function(b,a){this._walls[b+","+a]=2};a._firstRoom=function(){var b=P.createRandomCenter(Math.floor(this._width/2),Math.floor(this._height/2),this._options);this._rooms.push(b);b.create(this._digCallback)};a._findWall=function(){var b=[],a=[],f;for(f in this._walls)2==this._walls[f]?a.push(f):b.push(f);b=a.length?a:b;if(!b.length)return null;b=q.getItem(b.sort());delete this._walls[b];return b};a._tryFeature= +function(b,a,f,c){var e=q.getWeightedValue(this._features);b=qa[e].createRandomAt(b,a,f,c,this._options);if(!b.isValid(this._isWallCallback,this._canBeDugCallback))return!1;b.create(this._digCallback);b instanceof P&&this._rooms.push(b);b instanceof X&&(b.createPriorityWalls(this._priorityWallCallback),this._corridors.push(b));return!0};a._removeSurroundingWalls=function(b,a){for(var e=v[4],c=0;c=b||0>=a||b>=this._width-1||a>=this._height-1)return null;for(var e=null,c=v[4],d=0;dr;r++){var t=g+2*h[r][0];var A=l+2*h[r][1];if(this._isFree(d,t,A,a,c)){d[t][A]=0;d[g+h[r][0]][l+h[r][1]]=0;g=t;l= +A;p=!1;k++;break}}}while(!p)}}while(k+1a;a++)b[a][0]=0,b[a][1]=0;switch(Math.floor(4*q.getUniform())){case 0:b[0][0]=-1;b[1][0]=1;b[2][1]=-1;b[3][1]=1;break;case 1:b[3][0]=-1;b[2][0]=1;b[1][1]=-1;b[0][1]=1;break;case 2:b[2][0]=-1;b[3][0]=1;b[0][1]=-1;b[1][1]=1;break;case 3:b[1][0]=-1,b[0][0]=1,b[3][1]=-1,b[2][1]=1}};a._isFree=function(b,a,c,d,k){return 1>a|| +1>c||a>=d||c>=k?!1:b[a][c]};return c}(u);u=function(d){function c(b,a,c){b=d.call(this,b,a)||this;b.map=[];b.rooms=[];b.connectedCells=[];c=Object.assign({cellWidth:3,cellHeight:3},c);c.hasOwnProperty("roomWidth")||(c.roomWidth=b._calculateRoomSize(b._width,c.cellWidth));c.hasOwnProperty("roomHeight")||(c.roomHeight=b._calculateRoomSize(b._height,c.cellHeight));b._options=c;return b}_inheritsLoose(c,d);var a=c.prototype;a.create=function(b){this.map=this._fillMap(1);this.rooms=[];this.connectedCells= +[];this._initRooms();this._connectRooms();this._connectUnconnectedRooms();this._createRandomRoomConnections();this._createRooms();this._createCorridors();if(b)for(var a=0;ab&&(b=2);2>c&&(c=2);return[b,c]};a._initRooms=function(){for(var b=0;bh||h>=this._options.cellWidth||0>k||k>=this._options.cellHeight)){var g=this.rooms[b][a];if(0r||r>=b||0>p||p>=a)){d=this.rooms[r][p]; +k=!0;if(0==d.connections.length)break;for(r=0;rA-(u.y+u.height);)A++;if(0t-(u.x+u.width);)t++;u=Math.round(q.getUniformInt(0,k-g)/2);for(var x=Math.round(q.getUniformInt(0,h-l)/2);t+u+g>=b;)u?u--:g--;for(;A+x+l>=a;)x?x--:l--;t+=u;A+=x;this.rooms[v][w].x=t;this.rooms[v][w].y=A;this.rooms[v][w].width=g;this.rooms[v][w].height=l;for(u=t;ud.cellx? +(k=2,h=4):g.cellxd.celly?(k=3,h=1):(k=1,h=3),this._drawCorridor(this._getWallPosition(d,k),this._getWallPosition(g,h))}};return c}(u);x={Arena:x,Uniform:D,Cellular:E,Digger:H,EllerMaze:ra,DividedMaze:sa,IceyMaze:ta,Rogue:u};var ua=.5*(Math.sqrt(3)-1),K=(3-Math.sqrt(3))/6;u={Simplex:function(d){function c(a){void 0===a&&(a=256);var b=d.call(this)||this;b._gradients=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(var c=[],f=0;fu){var v=1;var w=0}else v=0,w=1;t=l-v+K;var x=u-w+K;b=l-1+2*K;a=u-1+2*K;q=p(q,g);g=p(r,g);var B=.5-l*l-u*u;0<=B&&(B*=B,r=d[q+c[g]],k=this._gradients[r],k=B*B*(k[0]*l+k[1]*u));l=.5-t*t- +x*x;0<=l&&(l*=l,r=d[q+v+c[g+w]],h=this._gradients[r],h=l*l*(h[0]*t+h[1]*x));l=.5-b*b-a*a;0<=l&&(l*=l,r=d[q+1+c[g+1]],c=this._gradients[r],n=l*l*(c[0]*b+c[1]*a));return 70*(k+h+n)};return c}(function(){})};E=function(){function d(c,a,b,d){void 0===d&&(d={});this._toX=c;this._toY=a;this._passableCallback=b;this._options=Object.assign({topology:8},d);this._dirs=v[this._options.topology];8==this._options.topology&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3], +this._dirs[5],this._dirs[7]])}d.prototype._getNeighbors=function(c,a){for(var b=[],d=0;dl;l++){var p=Math.round(g[l]*k);h[l]=p;n+=p}n>this._options.emissionThreshold&&(c[d]=h)}}return c};c._emitLightFromCell=function(a,b,c,d){var e=a+","+b;a=e in this._fovCache?this._fovCache[e]:this._updateFOV(a,b);for(var f in a){b=a[f];f in +d?e=d[f]:(e=[0,0,0],d[f]=e);for(var g=0;3>g;g++)e[g]+=Math.round(c[g]*b)}return this};c._updateFOV=function(a,b){var c={};this._fovCache[a+","+b]=c;var d=this._options.range;this._fov.compute(a,b,d,function(a,b,e,f){e=f*(1-e/d);0!=e&&(c[a+","+b]=e)}.bind(this));return c};return d}();g.Util=ka;g.Color=J;g.Text=I;g.RNG=q;g.Display=G;g.StringGenerator=O;g.EventQueue=ea;g.Scheduler=F;g.FOV=B;g.Map=x;g.Noise=u;g.Path=D;g.Engine=E;g.Lighting=H;g.DEFAULT_WIDTH=80;g.DEFAULT_HEIGHT=25;g.DIRS=v;g.KEYS={VK_CANCEL:3, +VK_HELP:6,VK_BACK_SPACE:8,VK_TAB:9,VK_CLEAR:12,VK_RETURN:13,VK_ENTER:14,VK_SHIFT:16,VK_CONTROL:17,VK_ALT:18,VK_PAUSE:19,VK_CAPS_LOCK:20,VK_ESCAPE:27,VK_SPACE:32,VK_PAGE_UP:33,VK_PAGE_DOWN:34,VK_END:35,VK_HOME:36,VK_LEFT:37,VK_UP:38,VK_RIGHT:39,VK_DOWN:40,VK_PRINTSCREEN:44,VK_INSERT:45,VK_DELETE:46,VK_0:48,VK_1:49,VK_2:50,VK_3:51,VK_4:52,VK_5:53,VK_6:54,VK_7:55,VK_8:56,VK_9:57,VK_COLON:58,VK_SEMICOLON:59,VK_LESS_THAN:60,VK_EQUALS:61,VK_GREATER_THAN:62,VK_QUESTION_MARK:63,VK_AT:64,VK_A:65,VK_B:66,VK_C:67, +VK_D:68,VK_E:69,VK_F:70,VK_G:71,VK_H:72,VK_I:73,VK_J:74,VK_K:75,VK_L:76,VK_M:77,VK_N:78,VK_O:79,VK_P:80,VK_Q:81,VK_R:82,VK_S:83,VK_T:84,VK_U:85,VK_V:86,VK_W:87,VK_X:88,VK_Y:89,VK_Z:90,VK_CONTEXT_MENU:93,VK_NUMPAD0:96,VK_NUMPAD1:97,VK_NUMPAD2:98,VK_NUMPAD3:99,VK_NUMPAD4:100,VK_NUMPAD5:101,VK_NUMPAD6:102,VK_NUMPAD7:103,VK_NUMPAD8:104,VK_NUMPAD9:105,VK_MULTIPLY:106,VK_ADD:107,VK_SEPARATOR:108,VK_SUBTRACT:109,VK_DECIMAL:110,VK_DIVIDE:111,VK_F1:112,VK_F2:113,VK_F3:114,VK_F4:115,VK_F5:116,VK_F6:117,VK_F7:118, +VK_F8:119,VK_F9:120,VK_F10:121,VK_F11:122,VK_F12:123,VK_F13:124,VK_F14:125,VK_F15:126,VK_F16:127,VK_F17:128,VK_F18:129,VK_F19:130,VK_F20:131,VK_F21:132,VK_F22:133,VK_F23:134,VK_F24:135,VK_NUM_LOCK:144,VK_SCROLL_LOCK:145,VK_CIRCUMFLEX:160,VK_EXCLAMATION:161,VK_DOUBLE_QUOTE:162,VK_HASH:163,VK_DOLLAR:164,VK_PERCENT:165,VK_AMPERSAND:166,VK_UNDERSCORE:167,VK_OPEN_PAREN:168,VK_CLOSE_PAREN:169,VK_ASTERISK:170,VK_PLUS:171,VK_PIPE:172,VK_HYPHEN_MINUS:173,VK_OPEN_CURLY_BRACKET:174,VK_CLOSE_CURLY_BRACKET:175, +VK_TILDE:176,VK_COMMA:188,VK_PERIOD:190,VK_SLASH:191,VK_BACK_QUOTE:192,VK_OPEN_BRACKET:219,VK_BACK_SLASH:220,VK_CLOSE_BRACKET:221,VK_QUOTE:222,VK_META:224,VK_ALTGR:225,VK_WIN:91,VK_KANA:21,VK_HANGUL:21,VK_EISU:22,VK_JUNJA:23,VK_FINAL:24,VK_HANJA:25,VK_KANJI:25,VK_CONVERT:28,VK_NONCONVERT:29,VK_ACCEPT:30,VK_MODECHANGE:31,VK_SELECT:41,VK_PRINT:42,VK_EXECUTE:43,VK_SLEEP:95};Object.defineProperty(g,"__esModule",{value:!0})}); diff --git a/html/js/teletype.js b/html/js/teletype.js new file mode 100644 index 0000000..48476b5 --- /dev/null +++ b/html/js/teletype.js @@ -0,0 +1,81 @@ +(function ($) { + // writes the string + // + // @param jQuery $target + // @param String str + // @param Numeric cursor + // @param Numeric delay + // @param Function cb + // @return void + function typeString($target, str, cursor, delay, cb) { + $target.html(function (_, html) { + return html + str[cursor]; + }); + + if (cursor < str.length - 1) { + setTimeout(function () { + typeString($target, str, cursor + 1, delay, cb); + }, delay); + } + else { + cb(); + } + } + + // clears the string + // + // @param jQuery $target + // @param Numeric delay + // @param Function cb + // @return void + function deleteString($target, delay, cb) { + var length; + + $target.html(function (_, html) { + length = html.length; + return html.substr(0, length - 1); + }); + + if (length > 1) { + setTimeout(function () { + deleteString($target, delay, cb); + }, delay); + } + else { + cb(); + } + } + + // jQuery hook + $.fn.extend({ + teletype: function (opts) { + var settings = $.extend({}, $.teletype.defaults, opts); + + return $(this).each(function () { + (function loop($tar, idx) { + // type + typeString($tar, settings.text[idx], 0, settings.delay, function () { + // delete + setTimeout(function () { + deleteString($tar, settings.delay, function () { + loop($tar, (idx + 1) % settings.text.length); + }); + }, settings.pause); + }); + + }($(this), 0)); + }); + } + }); + + // plugin defaults + $.extend({ + teletype: { + defaults: { + delay: 100, + pause: 2500, + text: [] + } + } + }); + }(jQuery)); \ No newline at end of file diff --git a/html/styles/fonts/pixel-operator/.uuid b/html/styles/fonts/pixel-operator/.uuid new file mode 100644 index 0000000..a337373 --- /dev/null +++ b/html/styles/fonts/pixel-operator/.uuid @@ -0,0 +1 @@ +90232dfa-09e6-43b8-baa1-f3fc548757e8 \ No newline at end of file diff --git a/html/styles/fonts/pixel-operator/LICENSE.txt b/html/styles/fonts/pixel-operator/LICENSE.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/html/styles/fonts/pixel-operator/LICENSE.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/html/styles/fonts/pixel-operator/PixelOperator-Bold.ttf b/html/styles/fonts/pixel-operator/PixelOperator-Bold.ttf new file mode 100644 index 0000000..745734f Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperator-Bold.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperator.ttf b/html/styles/fonts/pixel-operator/PixelOperator.ttf new file mode 100644 index 0000000..34fe947 Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperator.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperator8-Bold.ttf b/html/styles/fonts/pixel-operator/PixelOperator8-Bold.ttf new file mode 100644 index 0000000..10225eb Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperator8-Bold.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperator8.ttf b/html/styles/fonts/pixel-operator/PixelOperator8.ttf new file mode 100644 index 0000000..f9146ac Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperator8.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorHB.ttf b/html/styles/fonts/pixel-operator/PixelOperatorHB.ttf new file mode 100644 index 0000000..d63fa39 Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorHB.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorHB8.ttf b/html/styles/fonts/pixel-operator/PixelOperatorHB8.ttf new file mode 100644 index 0000000..5283cb5 Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorHB8.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorHBSC.ttf b/html/styles/fonts/pixel-operator/PixelOperatorHBSC.ttf new file mode 100644 index 0000000..b8fa149 Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorHBSC.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorMono-Bold.ttf b/html/styles/fonts/pixel-operator/PixelOperatorMono-Bold.ttf new file mode 100644 index 0000000..215d4a2 Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorMono-Bold.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorMono.ttf b/html/styles/fonts/pixel-operator/PixelOperatorMono.ttf new file mode 100644 index 0000000..1c1edcc Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorMono.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorMono8-Bold.ttf b/html/styles/fonts/pixel-operator/PixelOperatorMono8-Bold.ttf new file mode 100644 index 0000000..fc5b82b Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorMono8-Bold.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorMono8.ttf b/html/styles/fonts/pixel-operator/PixelOperatorMono8.ttf new file mode 100644 index 0000000..9e871ea Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorMono8.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorMonoHB.ttf b/html/styles/fonts/pixel-operator/PixelOperatorMonoHB.ttf new file mode 100644 index 0000000..55410fb Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorMonoHB.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorMonoHB8.ttf b/html/styles/fonts/pixel-operator/PixelOperatorMonoHB8.ttf new file mode 100644 index 0000000..1e10e3b Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorMonoHB8.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorSC-Bold.ttf b/html/styles/fonts/pixel-operator/PixelOperatorSC-Bold.ttf new file mode 100644 index 0000000..a44caaf Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorSC-Bold.ttf differ diff --git a/html/styles/fonts/pixel-operator/PixelOperatorSC.ttf b/html/styles/fonts/pixel-operator/PixelOperatorSC.ttf new file mode 100644 index 0000000..06783f8 Binary files /dev/null and b/html/styles/fonts/pixel-operator/PixelOperatorSC.ttf differ diff --git a/html/styles/fonts/stylesheet.css b/html/styles/fonts/stylesheet.css new file mode 100644 index 0000000..687be9e --- /dev/null +++ b/html/styles/fonts/stylesheet.css @@ -0,0 +1,67 @@ +/* +@font-face { + font-family: 'pixel_operator_monoregular'; + src: url('pixeloperatormono-webfont.woff2') format('woff2'), + url('pixeloperatormono-webfont.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'pixel_operator_mono_8regular'; + src: url('pixeloperatormono8-webfont.woff2') format('woff2'), + url('pixeloperatormono8-webfont.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'pixel_operator_mono_8bold'; + src: url('pixeloperatormono8-bold-webfont.woff2') format('woff2'), + url('pixeloperatormono8-bold-webfont.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'pixel_operator_monobold'; + src: url('pixeloperatormono-bold-webfont.woff2') format('woff2'), + url('pixeloperatormono-bold-webfont.woff') format('woff'); + font-weight: normal; + font-style: normal; +} +*/ +body { + font-family: pixel_operator_monoregular; + background-color: lightgray; + color: blue; +} + +.header { + background-color: lightslategrey; +} + +h1 { + font-family: pixel_operator_monobold; + +} + +.wrapper { + display: grid; + grid-template-columns: auto auto auto; + grid-gap: 10px; + background-color: #2196F3; + padding: 10px; +} + +.wrapper > div { + background-color: rgba(255, 255, 255, 0.8); + text-align: center; + padding: 20px 0; + font-size: 30px; +} + +#item1 { + grid-column-start: 2; + grid-column-end: 3; +} \ No newline at end of file diff --git a/html/styles/pixeloperatormono-bold-webfont.woff b/html/styles/pixeloperatormono-bold-webfont.woff new file mode 100644 index 0000000..40f690d Binary files /dev/null and b/html/styles/pixeloperatormono-bold-webfont.woff differ diff --git a/html/styles/pixeloperatormono-bold-webfont.woff2 b/html/styles/pixeloperatormono-bold-webfont.woff2 new file mode 100644 index 0000000..76a19b0 Binary files /dev/null and b/html/styles/pixeloperatormono-bold-webfont.woff2 differ diff --git a/html/styles/pixeloperatormono-webfont.woff b/html/styles/pixeloperatormono-webfont.woff new file mode 100644 index 0000000..a4af396 Binary files /dev/null and b/html/styles/pixeloperatormono-webfont.woff differ diff --git a/html/styles/pixeloperatormono-webfont.woff2 b/html/styles/pixeloperatormono-webfont.woff2 new file mode 100644 index 0000000..4ca4b2b Binary files /dev/null and b/html/styles/pixeloperatormono-webfont.woff2 differ diff --git a/html/styles/stylesheet.css b/html/styles/stylesheet.css new file mode 100644 index 0000000..e15c511 --- /dev/null +++ b/html/styles/stylesheet.css @@ -0,0 +1,199 @@ +/* Basic body styling */ +body { + background-color: #222; + color: #eee; + font-family: sans-serif; + margin: 0; + padding: 0; + display: flex; /* Use flexbox to center wrapper */ + justify-content: center; + align-items: flex-start; /* Align wrapper to top */ + min-height: 100vh; +} + +/* Wrapper grid container */ +.wrapper { + display: grid; + /* Define grid areas */ + grid-template-areas: + "header header header" + "status game game" + "chat game game" + "chat game game" + "chat input input" + "footer footer footer"; + /* Define column sizes: status/chat column, game columns */ + grid-template-columns: 250px 1fr 1fr; /* Left sidebar fixed width, game takes remaining space */ + /* Define row sizes */ + grid-template-rows: auto auto 1fr 1fr auto auto; /* Header, status, chat rows, input, footer */ + gap: 10px; /* Spacing between grid items */ + padding: 10px; + max-width: 1400px; + width: 95%; + border: 1px solid #444; + background-color: #333; + height: 95vh; /* Set height to fill most of viewport */ +} + +/* Assign elements to grid areas */ +.header { + grid-area: header; + background-color: #444; + padding: 5px; +} + +.status { + grid-area: status; + background-color: #444; + padding: 10px; + font-weight: bold; +} + +.chat { + grid-area: chat; + background-color: #444; + padding: 10px; + display: flex; + flex-direction: column; + overflow: hidden; /* Prevent overflow */ +} + +.rotdis { + grid-area: game; + background-color: #111; + display: flex; + justify-content: center; + align-items: center; + overflow: hidden; +} + +/* Make ROT.js canvas display properly */ +.rotdis canvas { + display: block; + max-width: 100%; + max-height: 100%; + object-fit: contain; /* Preserve aspect ratio */ +} + +#messageInput { + grid-area: input; + background-color: #444; + padding: 10px; +} + +.footer { + grid-area: footer; + background-color: #444; + padding: 5px; + text-align: center; +} + +/* Header styling */ +.header h1 { + margin: 0; + padding: 5px; + text-align: center; +} + +/* Status styling */ +#blockheight { + color: lightblue; +} + +/* Chat box styling */ +#messageBox { + flex-grow: 1; /* Allow message box to fill chat area */ + border: 1px solid #555; + background-color: #2a2a2a; + overflow-y: auto; /* Enable vertical scrolling */ + height: 100%; /* Fill available height */ + margin-bottom: 5px; +} + +#messages { + list-style-type: none; + margin: 0; + padding: 5px; +} + +#messages li { + padding: 2px 0; + border-bottom: 1px dashed #444; + font-size: 0.9em; +} + +/* Chat input styling */ +#chatForm { + display: flex; +} + +#chatInput { + flex-grow: 1; + padding: 5px; + border: 1px solid #555; + background-color: #eee; + color: #111; +} + +#chatForm button { + padding: 5px 10px; + border: 1px solid #555; + background-color: #666; + color: #eee; + cursor: pointer; +} + +#chatForm button:hover { + background-color: #777; +} + +/* Teletype styling */ +#staticbanner { + margin: 0; + padding: 5px; + text-align: left; + font-size: 24px; + color: #fff; +} + +#banner { + display: inline-block; + min-height: 1em; +} + +#bannercursor { + display: inline-block; + color: #fff; +} + +/* Add these styles for chat messages */ + +#messages li.self-command { + color: #aaf; + font-style: italic; +} + +#messages li.payment { + color: #ff0; + font-weight: bold; + border-left: 3px solid #ff0; + padding-left: 5px; + margin: 5px 0; +} + +#messages li.win { + color: #0f0; + font-weight: bold; +} + +#messages li.lose { + color: #f00; + font-weight: bold; +} + +#messages li.game-start { + color: #0ff; + font-weight: bold; + margin: 5px 0; +} + diff --git a/html/styles/test.css b/html/styles/test.css new file mode 100644 index 0000000..8d7d127 --- /dev/null +++ b/html/styles/test.css @@ -0,0 +1,3 @@ +body { + color: green; +} \ No newline at end of file diff --git a/html/test.html b/html/test.html new file mode 100644 index 0000000..ad1f55a --- /dev/null +++ b/html/test.html @@ -0,0 +1,24 @@ + + + + Wowgue + + + + + + +
+

Welcome traveler...

+
+
+
1
+
2
+
3
+
4
+
5
+
6sssssssssssssssssssssssss
+
+ + + \ No newline at end of file diff --git a/html/tiles.png b/html/tiles.png new file mode 100644 index 0000000..3e8101c Binary files /dev/null and b/html/tiles.png differ diff --git a/html/tiles.xcf b/html/tiles.xcf new file mode 100644 index 0000000..2fbed9d Binary files /dev/null and b/html/tiles.xcf differ diff --git a/index.js b/index.js new file mode 100644 index 0000000..a568585 --- /dev/null +++ b/index.js @@ -0,0 +1,285 @@ +const express = require('express'); +var app = require('express')(); +var http = require('http').Server(app); +var io = require('socket.io')(http); +var rpc = require('./rpccalls.js'); +var db = require('./dbcalls.js'); +var user = require('./user.js'); +const Game = require('./game'); +const activeGames = new Map(); // Maps socketId to Game objects +let lastBlockHeight = 0; // Track last block height +const MIN_FEE = 10; // Minimum entrance fee in WOW +const MAX_FEE = 100; // Maximum entrance fee in WOW +const WAITING_PLAYERS = []; // Players waiting for the next block + +var users = []; +var players = []; + +app.use(express.static('html')); +app.get('/', function(req, res) { + res.sendfile('index.html'); +}); + +// Function to get a user by socket ID +function getUserBySocket(socketId) { + return users.find(user => user.socketid === socketId); +} + +// Modified block check function +setInterval(function() { + rpc.daemonCall("get_block_count", "", function(result) { + const currentHeight = result.result.count; + rpc.lastBlock.setHeight(currentHeight); + + // If new block found + if (currentHeight > lastBlockHeight) { + console.log(`New block found: ${currentHeight}`); + io.emit('blockheight', currentHeight); + + // Start games for waiting players + startGamesForWaiting(currentHeight); + + // Check active games for timeout + checkGamesTimeout(currentHeight); + + lastBlockHeight = currentHeight; + } else { + io.emit('blockheight', currentHeight); + } + }); +}, 10000); + +// Start games for waiting players +function startGamesForWaiting(blockHeight) { + while (WAITING_PLAYERS.length > 0) { + const userId = WAITING_PLAYERS.shift(); + const user = getUserBySocket(userId); + + if (user) { + user.blockRec = blockHeight; + const game = user.startGame(80, 40); // Create a new game + activeGames.set(userId, game); + + io.to(userId).emit('game_start', { + map: game.dungeon.map, + player: game.player, + monster: game.monster, + entrance: game.dungeon.entrance, + exit: game.dungeon.exit, + treasure: game.dungeon.treasure, + blockHeight: blockHeight + }); + } + } +} + +// Check if any active games have timed out +function checkGamesTimeout(currentHeight) { + activeGames.forEach((game, socketId) => { + const user = getUserBySocket(socketId); + + if (user && user.blockRec && currentHeight > user.blockRec + 1) { + // Game has timed out - player didn't escape in time + game.gameState = 'lost'; + io.to(socketId).emit('game_over', { + status: 'lost', + reason: 'timeout', + message: 'You didn\'t escape before the next block was found!' + }); + + activeGames.delete(socketId); + } + }); +} + +// Socket.io handlers +io.on('connection', function(socket) { + console.log('A user connected'); + console.log(socket.client.id); + console.log(socket.handshake.address); + + db.insertVisitor(socket.client.id, socket.handshake.address, 0); + users.push(new user.User(socket.client.id, socket.handshake.address)); + + io.to(`${socket.client.id}`).emit('welcome', socket.client.id); + + socket.on('chat message', function(msg) { + console.log(msg); + + if (msg.toLowerCase() == 'hello') { + io.to(`${socket.client.id}`).emit('message', + 'Welcome, to enter the dungeon type Enter, and you will be given a Wownero address, ' + + 'which you must send between 10-100 WOW to enter. The more you send, the more you can win.'); + } + else if (msg.toLowerCase() == 'enter') { + const currentUser = getUserBySocket(socket.client.id); + + if (currentUser) { + // FOR TESTING: Skip payment and directly queue the player + currentUser.verifyPayment(10); // Minimal test fee + WAITING_PLAYERS.push(socket.client.id); + + io.to(`${socket.client.id}`).emit('message', + 'For testing: You will enter the dungeon when the next block is found.'); + + // To test without waiting for a block, immediately start a game + startGameForPlayer(socket.client.id, lastBlockHeight || 1); + } + } + else { + io.emit('message', msg); + } + }); + + // Handle player movement + socket.on('move', function(direction) { + const game = activeGames.get(socket.client.id); + + if (game) { + let dx = 0, dy = 0; + + // Convert direction to dx,dy + switch(direction) { + case 'up': dy = -1; break; + case 'down': dy = 1; break; + case 'left': dx = -1; break; + case 'right': dx = 1; break; + } + + const result = game.movePlayer(dx, dy); + + // Send updated game state + socket.emit('game_update', { + player: game.player, + monster: game.monster, + status: result.status + }); + + // Handle win/lose conditions + if (result.status === 'won') { + const user = getUserBySocket(socket.client.id); + const reward = user.calculateReward(); + + socket.emit('game_over', { + status: 'won', + hasTreasure: game.player.hasTreasure, + reward: reward + }); + + // TODO: Process payout + + activeGames.delete(socket.client.id); + } + else if (result.status === 'lost') { + socket.emit('game_over', { + status: 'lost', + reason: result.reason + }); + + activeGames.delete(socket.client.id); + } + } + }); + + // Handle disconnection + socket.on('disconnect', function () { + console.log('A user disconnected'); + + // Clean up any active games + if (activeGames.has(socket.client.id)) { + activeGames.delete(socket.client.id); + } + + users = spliceOut(socket.client.id, "socketid", users); + }); +}); + +http.listen(3000, function() { + console.log('listening on *:3000'); +}); + + +// Remove objects from an array if one attribute matches +function spliceOut(target, field, array) { + for (var i = array.length - 1; i >= 0; --i) { + if (array[i][field] == target) { + array.splice(i,1); + } + } + return array; +} +// Check if objects are in an array if one attribute matches +function checkArray(target, field, array) { + for (var i = array.length - 1; i >= 0; --i) { + if (array[i][field] == target) { + return true; + } + } + return false; +} + +// Add this function to generate a dungeon +function generateDungeon(width, height) { + // Create a new instance of ROT.Map.Digger + const digger = new ROT.Map.Digger(width, height, { + roomWidth: [3, 9], + roomHeight: [3, 5], + corridorLength: [2, 5], + dugPercentage: 0.2 + }); + + // Create a map representation + const map = Array(height).fill().map(() => Array(width).fill(1)); // 1 = wall + + // Callback to dig out rooms and corridors + digger.create((x, y, value) => { + map[y][x] = value; // 0 = floor, 1 = wall + }); + + // Get rooms and place special features + const rooms = digger.getRooms(); + let entrance = null; + let exit = null; + let treasure = null; + + if (rooms.length > 0) { + // Place entrance in the first room + entrance = rooms[0].getCenter(); + + // Place exit in the last room + exit = rooms[rooms.length-1].getCenter(); + + // Place treasure in a middle room + const treasureRoom = rooms[Math.floor(rooms.length/2)]; + treasure = treasureRoom.getCenter(); + } + + return { + map: map, + entrance: entrance, + exit: exit, + treasure: treasure, + rooms: rooms + }; +} + +// Add this helper function to start a game for a specific player immediately: +function startGameForPlayer(socketId, blockHeight) { + const user = getUserBySocket(socketId); + + if (user) { + user.blockRec = blockHeight; + const game = user.startGame(25, 19); // Create a new game with dimensions matching our display + activeGames.set(socketId, game); + + io.to(socketId).emit('game_start', { + map: game.dungeon.map, + player: game.player, + monster: game.monster, + entrance: game.dungeon.entrance, + exit: game.dungeon.exit, + treasure: game.dungeon.treasure, + blockHeight: blockHeight + }); + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..30547ec --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1597 @@ +{ + "name": "bitrogue", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "bitrogue", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "axios": "^1.9.0", + "express": "^4.17.1", + "pg": "^8.15.5", + "request": "^2.88.0", + "socket.io": "^4.8.1" + } + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==" + }, + "node_modules/@types/cors": { + "version": "2.8.17", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz", + "integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "22.15.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.0.tgz", + "integrity": "sha512-99S8dWD2DkeE6PBaEDw+In3aar7hdoBvjyJMR6vaKBTzpvR0P00ClzJMOoVrj9D2+Sy/YCwACYHnBTpMhg1UCA==", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==", + "engines": { + "node": "*" + } + }, + "node_modules/aws4": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz", + "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" + }, + "node_modules/axios": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", + "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/axios/node_modules/form-data": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", + "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", + "dependencies": { + "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", + "dependencies": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/engine.io": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.4.tgz", + "integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/engine.io/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/engine.io/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "node_modules/extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==", + "engines": [ + "node >=0.6.0" + ] + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==", + "engines": { + "node": "*" + } + }, + "node_modules/form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", + "dependencies": { + "assert-plus": "^1.0.0" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==", + "engines": { + "node": ">=4" + } + }, + "node_modules/har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "deprecated": "this library is no longer supported", + "dependencies": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", + "dependencies": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.3.7" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" + }, + "node_modules/isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==" + }, + "node_modules/jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" + }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" + }, + "node_modules/jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "dependencies": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "engines": { + "node": "*" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==" + }, + "node_modules/performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==" + }, + "node_modules/pg": { + "version": "8.15.5", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.15.5.tgz", + "integrity": "sha512-EpAhHFQc+aH9VfeffWIVC+XXk6lmAhS9W1FxtxcPXs94yxhrI1I6w/zkWfIOII/OkBv3Be04X3xMOj0kQ78l6w==", + "dependencies": { + "pg-connection-string": "^2.8.5", + "pg-pool": "^3.9.5", + "pg-protocol": "^1.9.5", + "pg-types": "^2.1.0", + "pgpass": "1.x" + }, + "engines": { + "node": ">= 8.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.2.5" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.2.5.tgz", + "integrity": "sha512-OOX22Vt0vOSRrdoUPKJ8Wi2OpE/o/h9T8X1s4qSkCedbNah9ei2W2765be8iMVxQUsvgT7zIAT2eIa9fs5+vtg==", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.8.5.tgz", + "integrity": "sha512-Ni8FuZ8yAF+sWZzojvtLE2b03cqjO5jNULcHFfM9ZZ0/JXrgom5pBREbtnAw7oxsxJqHw9Nz/XWORUEL3/IFow==" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.9.5", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.9.5.tgz", + "integrity": "sha512-DxyAlOgvUzRFpFAZjbCc8fUfG7BcETDHgepFPf724B0i08k9PAiZV1tkGGgQIL0jbMEuR9jW1YN7eX+WgXxCsQ==", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.9.5.tgz", + "integrity": "sha512-DYTWtWpfd5FOro3UnAfwvhD8jh59r2ig8bPtc9H8Ds7MscE/9NYruUQWFAOuraRl29jwcT2kyMFQ3MxeaVjUhg==" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", + "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/psl": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", + "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", + "dependencies": { + "punycode": "^2.3.1" + }, + "funding": { + "url": "https://github.com/sponsors/lupomontero" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", + "dependencies": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/request/node_modules/qs": { + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/socket.io": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.1.tgz", + "integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==", + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "cors": "~2.8.5", + "debug": "~4.3.2", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz", + "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==", + "dependencies": { + "debug": "~4.3.4", + "ws": "~8.17.1" + } + }, + "node_modules/socket.io-adapter/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-adapter/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/socket.io-parser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", + "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-parser/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/socket.io/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/sshpk": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz", + "integrity": "sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==", + "dependencies": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + }, + "bin": { + "sshpk-conv": "bin/sshpk-conv", + "sshpk-sign": "bin/sshpk-sign", + "sshpk-verify": "bin/sshpk-verify" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dependencies": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "engines": [ + "node >=0.6.0" + ], + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "node_modules/ws": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..3a569eb --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "bitrogue", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "node index.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "jw", + "license": "ISC", + "dependencies": { + "axios": "^1.9.0", + "express": "^4.17.1", + "pg": "^8.15.5", + "request": "^2.88.0", + "socket.io": "^4.8.1" + } +} diff --git a/rot.js b/rot.js new file mode 100644 index 0000000..03f3919 --- /dev/null +++ b/rot.js @@ -0,0 +1,7228 @@ +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.ROT = {}); +})(this, function (exports) { + 'use strict'; + /** + * This code is an implementation of Alea algorithm; (C) 2010 Johannes Baagøe. + * Alea is licensed according to the http://en.wikipedia.org/wiki/MIT_License. + */ + + var FRAC = 2.3283064365386963e-10; + /* 2^-32 */ + + var RNG = + /*#__PURE__*/ + function () { + function RNG() { + this._seed = 0; + this._s0 = 0; + this._s1 = 0; + this._s2 = 0; + this._c = 0; + } + + var _proto = RNG.prototype; + + _proto.getSeed = function getSeed() { + return this._seed; + }; + /** + * Seed the number generator + */ + + + _proto.setSeed = function setSeed(seed) { + seed = seed < 1 ? 1 / seed : seed; + this._seed = seed; + this._s0 = (seed >>> 0) * FRAC; + seed = seed * 69069 + 1 >>> 0; + this._s1 = seed * FRAC; + seed = seed * 69069 + 1 >>> 0; + this._s2 = seed * FRAC; + this._c = 1; + return this; + }; + /** + * @returns Pseudorandom value [0,1), uniformly distributed + */ + + + _proto.getUniform = function getUniform() { + var t = 2091639 * this._s0 + this._c * FRAC; + this._s0 = this._s1; + this._s1 = this._s2; + this._c = t | 0; + this._s2 = t - this._c; + return this._s2; + }; + /** + * @param lowerBound The lower end of the range to return a value from, inclusive + * @param upperBound The upper end of the range to return a value from, inclusive + * @returns Pseudorandom value [lowerBound, upperBound], using ROT.RNG.getUniform() to distribute the value + */ + + + _proto.getUniformInt = function getUniformInt(lowerBound, upperBound) { + var max = Math.max(lowerBound, upperBound); + var min = Math.min(lowerBound, upperBound); + return Math.floor(this.getUniform() * (max - min + 1)) + min; + }; + /** + * @param mean Mean value + * @param stddev Standard deviation. ~95% of the absolute values will be lower than 2*stddev. + * @returns A normally distributed pseudorandom value + */ + + + _proto.getNormal = function getNormal(mean, stddev) { + if (mean === void 0) { + mean = 0; + } + + if (stddev === void 0) { + stddev = 1; + } + + var u, v, r; + + do { + u = 2 * this.getUniform() - 1; + v = 2 * this.getUniform() - 1; + r = u * u + v * v; + } while (r > 1 || r == 0); + + var gauss = u * Math.sqrt(-2 * Math.log(r) / r); + return mean + gauss * stddev; + }; + /** + * @returns Pseudorandom value [1,100] inclusive, uniformly distributed + */ + + + _proto.getPercentage = function getPercentage() { + return 1 + Math.floor(this.getUniform() * 100); + }; + /** + * @returns Randomly picked item, null when length=0 + */ + + + _proto.getItem = function getItem(array) { + if (!array.length) { + return null; + } + + return array[Math.floor(this.getUniform() * array.length)]; + }; + /** + * @returns New array with randomized items + */ + + + _proto.shuffle = function shuffle(array) { + var result = []; + var clone = array.slice(); + + while (clone.length) { + var _index = clone.indexOf(this.getItem(clone)); + + result.push(clone.splice(_index, 1)[0]); + } + + return result; + }; + /** + * @param data key=whatever, value=weight (relative probability) + * @returns whatever + */ + + + _proto.getWeightedValue = function getWeightedValue(data) { + var total = 0; + + for (var _id in data) { + total += data[_id]; + } + + var random = this.getUniform() * total; + var id, + part = 0; + + for (id in data) { + part += data[id]; + + if (random < part) { + return id; + } + } // If by some floating-point annoyance we have + // random >= total, just return the last id. + + + return id; + }; + /** + * Get RNG state. Useful for storing the state and re-setting it via setState. + * @returns Internal state + */ + + + _proto.getState = function getState() { + return [this._s0, this._s1, this._s2, this._c]; + }; + /** + * Set a previously retrieved state. + */ + + + _proto.setState = function setState(state) { + this._s0 = state[0]; + this._s1 = state[1]; + this._s2 = state[2]; + this._c = state[3]; + return this; + }; + /** + * Returns a cloned RNG + */ + + + _proto.clone = function clone() { + var clone = new RNG(); + return clone.setState(this.getState()); + }; + + return RNG; + }(); + + var RNG$1 = new RNG().setSeed(Date.now()); + /** + * @class Abstract display backend module + * @private + */ + + var Backend = + /*#__PURE__*/ + function () { + function Backend() {} + + var _proto2 = Backend.prototype; + + _proto2.getContainer = function getContainer() { + return null; + }; + + _proto2.setOptions = function setOptions(options) { + this._options = options; + }; + + return Backend; + }(); + + var Canvas = + /*#__PURE__*/ + function (_Backend) { + _inheritsLoose(Canvas, _Backend); + + function Canvas() { + var _this; + + _this = _Backend.call(this) || this; + _this._ctx = document.createElement("canvas").getContext("2d"); + return _this; + } + + var _proto3 = Canvas.prototype; + + _proto3.schedule = function schedule(cb) { + requestAnimationFrame(cb); + }; + + _proto3.getContainer = function getContainer() { + return this._ctx.canvas; + }; + + _proto3.setOptions = function setOptions(opts) { + _Backend.prototype.setOptions.call(this, opts); + + var style = opts.fontStyle ? opts.fontStyle + " " : ""; + var font = style + " " + opts.fontSize + "px " + opts.fontFamily; + this._ctx.font = font; + + this._updateSize(); + + this._ctx.font = font; + this._ctx.textAlign = "center"; + this._ctx.textBaseline = "middle"; + }; + + _proto3.clear = function clear() { + this._ctx.fillStyle = this._options.bg; + + this._ctx.fillRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height); + }; + + _proto3.eventToPosition = function eventToPosition(x, y) { + var canvas = this._ctx.canvas; + var rect = canvas.getBoundingClientRect(); + x -= rect.left; + y -= rect.top; + x *= canvas.width / rect.width; + y *= canvas.height / rect.height; + + if (x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) { + return [-1, -1]; + } + + return this._normalizedEventToPosition(x, y); + }; + + return Canvas; + }(Backend); + /** + * Always positive modulus + * @param x Operand + * @param n Modulus + * @returns x modulo n + */ + + + function mod(x, n) { + return (x % n + n) % n; + } + + function clamp(val, min, max) { + if (min === void 0) { + min = 0; + } + + if (max === void 0) { + max = 1; + } + + if (val < min) return min; + if (val > max) return max; + return val; + } + + function capitalize(string) { + return string.charAt(0).toUpperCase() + string.substring(1); + } + /** + * Format a string in a flexible way. Scans for %s strings and replaces them with arguments. List of patterns is modifiable via String.format.map. + * @param {string} template + * @param {any} [argv] + */ + + + function format(template) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + var map = format.map; + + var replacer = function replacer(match, group1, group2, index) { + if (template.charAt(index - 1) == "%") { + return match.substring(1); + } + + if (!args.length) { + return match; + } + + var obj = args[0]; + var group = group1 || group2; + var parts = group.split(","); + var name = parts.shift() || ""; + var method = map[name.toLowerCase()]; + + if (!method) { + return match; + } + + obj = args.shift(); + var replaced = obj[method].apply(obj, parts); + var first = name.charAt(0); + + if (first != first.toLowerCase()) { + replaced = capitalize(replaced); + } + + return replaced; + }; + + return template.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi, replacer); + } + + format.map = { + "s": "toString" + }; + var util = + /*#__PURE__*/ + Object.freeze({ + mod: mod, + clamp: clamp, + capitalize: capitalize, + format: format + }); + /** + * @class Hexagonal backend + * @private + */ + + var Hex = + /*#__PURE__*/ + function (_Canvas) { + _inheritsLoose(Hex, _Canvas); + + function Hex() { + var _this2; + + _this2 = _Canvas.call(this) || this; + _this2._spacingX = 0; + _this2._spacingY = 0; + _this2._hexSize = 0; + return _this2; + } + + var _proto4 = Hex.prototype; + + _proto4.draw = function draw(data, clearBefore) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var px = [(x + 1) * this._spacingX, y * this._spacingY + this._hexSize]; + + if (this._options.transpose) { + px.reverse(); + } + + if (clearBefore) { + this._ctx.fillStyle = bg; + + this._fill(px[0], px[1]); + } + + if (!ch) { + return; + } + + this._ctx.fillStyle = fg; + var chars = [].concat(ch); + + for (var i = 0; i < chars.length; i++) { + this._ctx.fillText(chars[i], px[0], Math.ceil(px[1])); + } + }; + + _proto4.computeSize = function computeSize(availWidth, availHeight) { + if (this._options.transpose) { + availWidth += availHeight; + availHeight = availWidth - availHeight; + availWidth -= availHeight; + } + + var width = Math.floor(availWidth / this._spacingX) - 1; + var height = Math.floor((availHeight - 2 * this._hexSize) / this._spacingY + 1); + return [width, height]; + }; + + _proto4.computeFontSize = function computeFontSize(availWidth, availHeight) { + if (this._options.transpose) { + availWidth += availHeight; + availHeight = availWidth - availHeight; + availWidth -= availHeight; + } + + var hexSizeWidth = 2 * availWidth / ((this._options.width + 1) * Math.sqrt(3)) - 1; + var hexSizeHeight = availHeight / (2 + 1.5 * (this._options.height - 1)); + var hexSize = Math.min(hexSizeWidth, hexSizeHeight); // compute char ratio + + var oldFont = this._ctx.font; + this._ctx.font = "100px " + this._options.fontFamily; + var width = Math.ceil(this._ctx.measureText("W").width); + this._ctx.font = oldFont; + var ratio = width / 100; + hexSize = Math.floor(hexSize) + 1; // closest larger hexSize + // FIXME char size computation does not respect transposed hexes + + var fontSize = 2 * hexSize / (this._options.spacing * (1 + ratio / Math.sqrt(3))); // closest smaller fontSize + + return Math.ceil(fontSize) - 1; + }; + + _proto4._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + var nodeSize; + + if (this._options.transpose) { + x += y; + y = x - y; + x -= y; + nodeSize = this._ctx.canvas.width; + } else { + nodeSize = this._ctx.canvas.height; + } + + var size = nodeSize / this._options.height; + y = Math.floor(y / size); + + if (mod(y, 2)) { + /* odd row */ + x -= this._spacingX; + x = 1 + 2 * Math.floor(x / (2 * this._spacingX)); + } else { + x = 2 * Math.floor(x / (2 * this._spacingX)); + } + + return [x, y]; + }; + /** + * Arguments are pixel values. If "transposed" mode is enabled, then these two are already swapped. + */ + + + _proto4._fill = function _fill(cx, cy) { + var a = this._hexSize; + var b = this._options.border; + var ctx = this._ctx; + ctx.beginPath(); + + if (this._options.transpose) { + ctx.moveTo(cx - a + b, cy); + ctx.lineTo(cx - a / 2 + b, cy + this._spacingX - b); + ctx.lineTo(cx + a / 2 - b, cy + this._spacingX - b); + ctx.lineTo(cx + a - b, cy); + ctx.lineTo(cx + a / 2 - b, cy - this._spacingX + b); + ctx.lineTo(cx - a / 2 + b, cy - this._spacingX + b); + ctx.lineTo(cx - a + b, cy); + } else { + ctx.moveTo(cx, cy - a + b); + ctx.lineTo(cx + this._spacingX - b, cy - a / 2 + b); + ctx.lineTo(cx + this._spacingX - b, cy + a / 2 - b); + ctx.lineTo(cx, cy + a - b); + ctx.lineTo(cx - this._spacingX + b, cy + a / 2 - b); + ctx.lineTo(cx - this._spacingX + b, cy - a / 2 + b); + ctx.lineTo(cx, cy - a + b); + } + + ctx.fill(); + }; + + _proto4._updateSize = function _updateSize() { + var opts = this._options; + var charWidth = Math.ceil(this._ctx.measureText("W").width); + this._hexSize = Math.floor(opts.spacing * (opts.fontSize + charWidth / Math.sqrt(3)) / 2); + this._spacingX = this._hexSize * Math.sqrt(3) / 2; + this._spacingY = this._hexSize * 1.5; + var xprop; + var yprop; + + if (opts.transpose) { + xprop = "height"; + yprop = "width"; + } else { + xprop = "width"; + yprop = "height"; + } + + this._ctx.canvas[xprop] = Math.ceil((opts.width + 1) * this._spacingX); + this._ctx.canvas[yprop] = Math.ceil((opts.height - 1) * this._spacingY + 2 * this._hexSize); + }; + + return Hex; + }(Canvas); + /** + * @class Rectangular backend + * @private + */ + + + var Rect = + /*#__PURE__*/ + function (_Canvas2) { + _inheritsLoose(Rect, _Canvas2); + + function Rect() { + var _this3; + + _this3 = _Canvas2.call(this) || this; + _this3._spacingX = 0; + _this3._spacingY = 0; + _this3._canvasCache = {}; + return _this3; + } + + var _proto5 = Rect.prototype; + + _proto5.setOptions = function setOptions(options) { + _Canvas2.prototype.setOptions.call(this, options); + + this._canvasCache = {}; + }; + + _proto5.draw = function draw(data, clearBefore) { + if (Rect.cache) { + this._drawWithCache(data); + } else { + this._drawNoCache(data, clearBefore); + } + }; + + _proto5._drawWithCache = function _drawWithCache(data) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var hash = "" + ch + fg + bg; + var canvas; + + if (hash in this._canvasCache) { + canvas = this._canvasCache[hash]; + } else { + var b = this._options.border; + canvas = document.createElement("canvas"); + var ctx = canvas.getContext("2d"); + canvas.width = this._spacingX; + canvas.height = this._spacingY; + ctx.fillStyle = bg; + ctx.fillRect(b, b, canvas.width - b, canvas.height - b); + + if (ch) { + ctx.fillStyle = fg; + ctx.font = this._ctx.font; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + var chars = [].concat(ch); + + for (var i = 0; i < chars.length; i++) { + ctx.fillText(chars[i], this._spacingX / 2, Math.ceil(this._spacingY / 2)); + } + } + + this._canvasCache[hash] = canvas; + } + + this._ctx.drawImage(canvas, x * this._spacingX, y * this._spacingY); + }; + + _proto5._drawNoCache = function _drawNoCache(data, clearBefore) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + + if (clearBefore) { + var b = this._options.border; + this._ctx.fillStyle = bg; + + this._ctx.fillRect(x * this._spacingX + b, y * this._spacingY + b, this._spacingX - b, this._spacingY - b); + } + + if (!ch) { + return; + } + + this._ctx.fillStyle = fg; + var chars = [].concat(ch); + + for (var i = 0; i < chars.length; i++) { + this._ctx.fillText(chars[i], (x + 0.5) * this._spacingX, Math.ceil((y + 0.5) * this._spacingY)); + } + }; + + _proto5.computeSize = function computeSize(availWidth, availHeight) { + var width = Math.floor(availWidth / this._spacingX); + var height = Math.floor(availHeight / this._spacingY); + return [width, height]; + }; + + _proto5.computeFontSize = function computeFontSize(availWidth, availHeight) { + var boxWidth = Math.floor(availWidth / this._options.width); + var boxHeight = Math.floor(availHeight / this._options.height); + /* compute char ratio */ + + var oldFont = this._ctx.font; + this._ctx.font = "100px " + this._options.fontFamily; + var width = Math.ceil(this._ctx.measureText("W").width); + this._ctx.font = oldFont; + var ratio = width / 100; + var widthFraction = ratio * boxHeight / boxWidth; + + if (widthFraction > 1) { + /* too wide with current aspect ratio */ + boxHeight = Math.floor(boxHeight / widthFraction); + } + + return Math.floor(boxHeight / this._options.spacing); + }; + + _proto5._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + return [Math.floor(x / this._spacingX), Math.floor(y / this._spacingY)]; + }; + + _proto5._updateSize = function _updateSize() { + var opts = this._options; + var charWidth = Math.ceil(this._ctx.measureText("W").width); + this._spacingX = Math.ceil(opts.spacing * charWidth); + this._spacingY = Math.ceil(opts.spacing * opts.fontSize); + + if (opts.forceSquareRatio) { + this._spacingX = this._spacingY = Math.max(this._spacingX, this._spacingY); + } + + this._ctx.canvas.width = opts.width * this._spacingX; + this._ctx.canvas.height = opts.height * this._spacingY; + }; + + return Rect; + }(Canvas); + + Rect.cache = false; + /** + * @class Tile backend + * @private + */ + + var Tile = + /*#__PURE__*/ + function (_Canvas3) { + _inheritsLoose(Tile, _Canvas3); + + function Tile() { + var _this4; + + _this4 = _Canvas3.call(this) || this; + _this4._colorCanvas = document.createElement("canvas"); + return _this4; + } + + var _proto6 = Tile.prototype; + + _proto6.draw = function draw(data, clearBefore) { + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var tileWidth = this._options.tileWidth; + var tileHeight = this._options.tileHeight; + + if (clearBefore) { + if (this._options.tileColorize) { + this._ctx.clearRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } else { + this._ctx.fillStyle = bg; + + this._ctx.fillRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } + } + + if (!ch) { + return; + } + + var chars = [].concat(ch); + var fgs = [].concat(fg); + var bgs = [].concat(bg); + + for (var i = 0; i < chars.length; i++) { + var tile = this._options.tileMap[chars[i]]; + + if (!tile) { + throw new Error("Char \"" + chars[i] + "\" not found in tileMap"); + } + + if (this._options.tileColorize) { + // apply colorization + var canvas = this._colorCanvas; + var context = canvas.getContext("2d"); + context.globalCompositeOperation = "source-over"; + context.clearRect(0, 0, tileWidth, tileHeight); + var _fg = fgs[i]; + var _bg = bgs[i]; + context.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, 0, 0, tileWidth, tileHeight); + + if (_fg != "transparent") { + context.fillStyle = _fg; + context.globalCompositeOperation = "source-atop"; + context.fillRect(0, 0, tileWidth, tileHeight); + } + + if (_bg != "transparent") { + context.fillStyle = _bg; + context.globalCompositeOperation = "destination-over"; + context.fillRect(0, 0, tileWidth, tileHeight); + } + + this._ctx.drawImage(canvas, x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } else { + // no colorizing, easy + this._ctx.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, x * tileWidth, y * tileHeight, tileWidth, tileHeight); + } + } + }; + + _proto6.computeSize = function computeSize(availWidth, availHeight) { + var width = Math.floor(availWidth / this._options.tileWidth); + var height = Math.floor(availHeight / this._options.tileHeight); + return [width, height]; + }; + + _proto6.computeFontSize = function computeFontSize() { + throw new Error("Tile backend does not understand font size"); + }; + + _proto6._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + return [Math.floor(x / this._options.tileWidth), Math.floor(y / this._options.tileHeight)]; + }; + + _proto6._updateSize = function _updateSize() { + var opts = this._options; + this._ctx.canvas.width = opts.width * opts.tileWidth; + this._ctx.canvas.height = opts.height * opts.tileHeight; + this._colorCanvas.width = opts.tileWidth; + this._colorCanvas.height = opts.tileHeight; + }; + + return Tile; + }(Canvas); + + function fromString(str) { + var cached, r; + + if (str in CACHE) { + cached = CACHE[str]; + } else { + if (str.charAt(0) == "#") { + // hex rgb + var matched = str.match(/[0-9a-f]/gi) || []; + var values = matched.map(function (x) { + return parseInt(x, 16); + }); + + if (values.length == 3) { + cached = values.map(function (x) { + return x * 17; + }); + } else { + for (var i = 0; i < 3; i++) { + values[i + 1] += 16 * values[i]; + values.splice(i, 1); + } + + cached = values; + } + } else if (r = str.match(/rgb\(([0-9, ]+)\)/i)) { + // decimal rgb + cached = r[1].split(/\s*,\s*/).map(function (x) { + return parseInt(x); + }); + } else { + // html name + cached = [0, 0, 0]; + } + + CACHE[str] = cached; + } + + return cached.slice(); + } + /** + * Add two or more colors + */ + + + function add(color1) { + var result = color1.slice(); + + for (var _len2 = arguments.length, colors = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + colors[_key2 - 1] = arguments[_key2]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + result[i] += colors[j][i]; + } + } + + return result; + } + /** + * Add two or more colors, MODIFIES FIRST ARGUMENT + */ + + + function add_(color1) { + for (var _len3 = arguments.length, colors = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + colors[_key3 - 1] = arguments[_key3]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + color1[i] += colors[j][i]; + } + } + + return color1; + } + /** + * Multiply (mix) two or more colors + */ + + + function multiply(color1) { + var result = color1.slice(); + + for (var _len4 = arguments.length, colors = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + colors[_key4 - 1] = arguments[_key4]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + result[i] *= colors[j][i] / 255; + } + + result[i] = Math.round(result[i]); + } + + return result; + } + /** + * Multiply (mix) two or more colors, MODIFIES FIRST ARGUMENT + */ + + + function multiply_(color1) { + for (var _len5 = arguments.length, colors = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + colors[_key5 - 1] = arguments[_key5]; + } + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < colors.length; j++) { + color1[i] *= colors[j][i] / 255; + } + + color1[i] = Math.round(color1[i]); + } + + return color1; + } + /** + * Interpolate (blend) two colors with a given factor + */ + + + function interpolate(color1, color2, factor) { + if (factor === void 0) { + factor = 0.5; + } + + var result = color1.slice(); + + for (var i = 0; i < 3; i++) { + result[i] = Math.round(result[i] + factor * (color2[i] - color1[i])); + } + + return result; + } + + var lerp = interpolate; + /** + * Interpolate (blend) two colors with a given factor in HSL mode + */ + + function interpolateHSL(color1, color2, factor) { + if (factor === void 0) { + factor = 0.5; + } + + var hsl1 = rgb2hsl(color1); + var hsl2 = rgb2hsl(color2); + + for (var i = 0; i < 3; i++) { + hsl1[i] += factor * (hsl2[i] - hsl1[i]); + } + + return hsl2rgb(hsl1); + } + + var lerpHSL = interpolateHSL; + /** + * Create a new random color based on this one + * @param color + * @param diff Set of standard deviations + */ + + function randomize(color, diff) { + if (!(diff instanceof Array)) { + diff = Math.round(RNG$1.getNormal(0, diff)); + } + + var result = color.slice(); + + for (var i = 0; i < 3; i++) { + result[i] += diff instanceof Array ? Math.round(RNG$1.getNormal(0, diff[i])) : diff; + } + + return result; + } + /** + * Converts an RGB color value to HSL. Expects 0..255 inputs, produces 0..1 outputs. + */ + + + function rgb2hsl(color) { + var r = color[0] / 255; + var g = color[1] / 255; + var b = color[2] / 255; + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h = 0, + s, + l = (max + min) / 2; + + if (max == min) { + s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + + case g: + h = (b - r) / d + 2; + break; + + case b: + h = (r - g) / d + 4; + break; + } + + h /= 6; + } + + return [h, s, l]; + } + + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + /** + * Converts an HSL color value to RGB. Expects 0..1 inputs, produces 0..255 outputs. + */ + + + function hsl2rgb(color) { + var l = color[2]; + + if (color[1] == 0) { + l = Math.round(l * 255); + return [l, l, l]; + } else { + var s = color[1]; + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + var r = hue2rgb(p, q, color[0] + 1 / 3); + var g = hue2rgb(p, q, color[0]); + var b = hue2rgb(p, q, color[0] - 1 / 3); + return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; + } + } + + function toRGB(color) { + var clamped = color.map(function (x) { + return clamp(x, 0, 255); + }); + return "rgb(" + clamped.join(",") + ")"; + } + + function toHex(color) { + var clamped = color.map(function (x) { + return clamp(x, 0, 255).toString(16).padStart(2, "0"); + }); + return "#" + clamped.join(""); + } + + var CACHE = { + "black": [0, 0, 0], + "navy": [0, 0, 128], + "darkblue": [0, 0, 139], + "mediumblue": [0, 0, 205], + "blue": [0, 0, 255], + "darkgreen": [0, 100, 0], + "green": [0, 128, 0], + "teal": [0, 128, 128], + "darkcyan": [0, 139, 139], + "deepskyblue": [0, 191, 255], + "darkturquoise": [0, 206, 209], + "mediumspringgreen": [0, 250, 154], + "lime": [0, 255, 0], + "springgreen": [0, 255, 127], + "aqua": [0, 255, 255], + "cyan": [0, 255, 255], + "midnightblue": [25, 25, 112], + "dodgerblue": [30, 144, 255], + "forestgreen": [34, 139, 34], + "seagreen": [46, 139, 87], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "limegreen": [50, 205, 50], + "mediumseagreen": [60, 179, 113], + "turquoise": [64, 224, 208], + "royalblue": [65, 105, 225], + "steelblue": [70, 130, 180], + "darkslateblue": [72, 61, 139], + "mediumturquoise": [72, 209, 204], + "indigo": [75, 0, 130], + "darkolivegreen": [85, 107, 47], + "cadetblue": [95, 158, 160], + "cornflowerblue": [100, 149, 237], + "mediumaquamarine": [102, 205, 170], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "slateblue": [106, 90, 205], + "olivedrab": [107, 142, 35], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "mediumslateblue": [123, 104, 238], + "lawngreen": [124, 252, 0], + "chartreuse": [127, 255, 0], + "aquamarine": [127, 255, 212], + "maroon": [128, 0, 0], + "purple": [128, 0, 128], + "olive": [128, 128, 0], + "gray": [128, 128, 128], + "grey": [128, 128, 128], + "skyblue": [135, 206, 235], + "lightskyblue": [135, 206, 250], + "blueviolet": [138, 43, 226], + "darkred": [139, 0, 0], + "darkmagenta": [139, 0, 139], + "saddlebrown": [139, 69, 19], + "darkseagreen": [143, 188, 143], + "lightgreen": [144, 238, 144], + "mediumpurple": [147, 112, 216], + "darkviolet": [148, 0, 211], + "palegreen": [152, 251, 152], + "darkorchid": [153, 50, 204], + "yellowgreen": [154, 205, 50], + "sienna": [160, 82, 45], + "brown": [165, 42, 42], + "darkgray": [169, 169, 169], + "darkgrey": [169, 169, 169], + "lightblue": [173, 216, 230], + "greenyellow": [173, 255, 47], + "paleturquoise": [175, 238, 238], + "lightsteelblue": [176, 196, 222], + "powderblue": [176, 224, 230], + "firebrick": [178, 34, 34], + "darkgoldenrod": [184, 134, 11], + "mediumorchid": [186, 85, 211], + "rosybrown": [188, 143, 143], + "darkkhaki": [189, 183, 107], + "silver": [192, 192, 192], + "mediumvioletred": [199, 21, 133], + "indianred": [205, 92, 92], + "peru": [205, 133, 63], + "chocolate": [210, 105, 30], + "tan": [210, 180, 140], + "lightgray": [211, 211, 211], + "lightgrey": [211, 211, 211], + "palevioletred": [216, 112, 147], + "thistle": [216, 191, 216], + "orchid": [218, 112, 214], + "goldenrod": [218, 165, 32], + "crimson": [220, 20, 60], + "gainsboro": [220, 220, 220], + "plum": [221, 160, 221], + "burlywood": [222, 184, 135], + "lightcyan": [224, 255, 255], + "lavender": [230, 230, 250], + "darksalmon": [233, 150, 122], + "violet": [238, 130, 238], + "palegoldenrod": [238, 232, 170], + "lightcoral": [240, 128, 128], + "khaki": [240, 230, 140], + "aliceblue": [240, 248, 255], + "honeydew": [240, 255, 240], + "azure": [240, 255, 255], + "sandybrown": [244, 164, 96], + "wheat": [245, 222, 179], + "beige": [245, 245, 220], + "whitesmoke": [245, 245, 245], + "mintcream": [245, 255, 250], + "ghostwhite": [248, 248, 255], + "salmon": [250, 128, 114], + "antiquewhite": [250, 235, 215], + "linen": [250, 240, 230], + "lightgoldenrodyellow": [250, 250, 210], + "oldlace": [253, 245, 230], + "red": [255, 0, 0], + "fuchsia": [255, 0, 255], + "magenta": [255, 0, 255], + "deeppink": [255, 20, 147], + "orangered": [255, 69, 0], + "tomato": [255, 99, 71], + "hotpink": [255, 105, 180], + "coral": [255, 127, 80], + "darkorange": [255, 140, 0], + "lightsalmon": [255, 160, 122], + "orange": [255, 165, 0], + "lightpink": [255, 182, 193], + "pink": [255, 192, 203], + "gold": [255, 215, 0], + "peachpuff": [255, 218, 185], + "navajowhite": [255, 222, 173], + "moccasin": [255, 228, 181], + "bisque": [255, 228, 196], + "mistyrose": [255, 228, 225], + "blanchedalmond": [255, 235, 205], + "papayawhip": [255, 239, 213], + "lavenderblush": [255, 240, 245], + "seashell": [255, 245, 238], + "cornsilk": [255, 248, 220], + "lemonchiffon": [255, 250, 205], + "floralwhite": [255, 250, 240], + "snow": [255, 250, 250], + "yellow": [255, 255, 0], + "lightyellow": [255, 255, 224], + "ivory": [255, 255, 240], + "white": [255, 255, 255] + }; + var color = + /*#__PURE__*/ + Object.freeze({ + fromString: fromString, + add: add, + add_: add_, + multiply: multiply, + multiply_: multiply_, + interpolate: interpolate, + lerp: lerp, + interpolateHSL: interpolateHSL, + lerpHSL: lerpHSL, + randomize: randomize, + rgb2hsl: rgb2hsl, + hsl2rgb: hsl2rgb, + toRGB: toRGB, + toHex: toHex + }); + /** + * @class Tile backend + * @private + */ + + var TileGL = + /*#__PURE__*/ + function (_Backend2) { + _inheritsLoose(TileGL, _Backend2); + + TileGL.isSupported = function isSupported() { + return !!document.createElement("canvas").getContext("webgl2", { + preserveDrawingBuffer: true + }); + }; + + function TileGL() { + var _this5; + + _this5 = _Backend2.call(this) || this; + _this5._uniforms = {}; + + try { + _this5._gl = _this5._initWebGL(); + } catch (e) { + alert(e.message); + } + + return _this5; + } + + var _proto7 = TileGL.prototype; + + _proto7.schedule = function schedule(cb) { + requestAnimationFrame(cb); + }; + + _proto7.getContainer = function getContainer() { + return this._gl.canvas; + }; + + _proto7.setOptions = function setOptions(opts) { + var _this6 = this; + + _Backend2.prototype.setOptions.call(this, opts); + + this._updateSize(); + + var tileSet = this._options.tileSet; + + if (tileSet && "complete" in tileSet && !tileSet.complete) { + tileSet.addEventListener("load", function () { + return _this6._updateTexture(tileSet); + }); + } else { + this._updateTexture(tileSet); + } + }; + + _proto7.draw = function draw(data, clearBefore) { + var gl = this._gl; + var opts = this._options; + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; + var scissorY = gl.canvas.height - (y + 1) * opts.tileHeight; + gl.scissor(x * opts.tileWidth, scissorY, opts.tileWidth, opts.tileHeight); + + if (clearBefore) { + if (opts.tileColorize) { + gl.clearColor(0, 0, 0, 0); + } else { + gl.clearColor.apply(gl, parseColor(bg)); + } + + gl.clear(gl.COLOR_BUFFER_BIT); + } + + if (!ch) { + return; + } + + var chars = [].concat(ch); + var bgs = [].concat(bg); + var fgs = [].concat(fg); + gl.uniform2fv(this._uniforms["targetPosRel"], [x, y]); + + for (var i = 0; i < chars.length; i++) { + var tile = this._options.tileMap[chars[i]]; + + if (!tile) { + throw new Error("Char \"" + chars[i] + "\" not found in tileMap"); + } + + gl.uniform1f(this._uniforms["colorize"], opts.tileColorize ? 1 : 0); + gl.uniform2fv(this._uniforms["tilesetPosAbs"], tile); + + if (opts.tileColorize) { + gl.uniform4fv(this._uniforms["tint"], parseColor(fgs[i])); + gl.uniform4fv(this._uniforms["bg"], parseColor(bgs[i])); + } + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + } + /* + + + for (let i=0;i= canvas.width || y >= canvas.height) { + return [-1, -1]; + } + + return this._normalizedEventToPosition(x, y); + }; + + _proto7._initWebGL = function _initWebGL() { + var _this7 = this; + + var gl = document.createElement("canvas").getContext("webgl2", { + preserveDrawingBuffer: true + }); + window.gl = gl; + var program = createProgram(gl, VS, FS); + gl.useProgram(program); + createQuad(gl); + UNIFORMS.forEach(function (name) { + return _this7._uniforms[name] = gl.getUniformLocation(program, name); + }); + this._program = program; + gl.enable(gl.BLEND); + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + gl.enable(gl.SCISSOR_TEST); + return gl; + }; + + _proto7._normalizedEventToPosition = function _normalizedEventToPosition(x, y) { + return [Math.floor(x / this._options.tileWidth), Math.floor(y / this._options.tileHeight)]; + }; + + _proto7._updateSize = function _updateSize() { + var gl = this._gl; + var opts = this._options; + var canvasSize = [opts.width * opts.tileWidth, opts.height * opts.tileHeight]; + gl.canvas.width = canvasSize[0]; + gl.canvas.height = canvasSize[1]; + gl.viewport(0, 0, canvasSize[0], canvasSize[1]); + gl.uniform2fv(this._uniforms["tileSize"], [opts.tileWidth, opts.tileHeight]); + gl.uniform2fv(this._uniforms["targetSize"], canvasSize); + }; + + _proto7._updateTexture = function _updateTexture(tileSet) { + createTexture(this._gl, tileSet); + }; + + return TileGL; + }(Backend); + + var UNIFORMS = ["targetPosRel", "tilesetPosAbs", "tileSize", "targetSize", "colorize", "bg", "tint"]; + var VS = "\n#version 300 es\n\nin vec2 tilePosRel;\nout vec2 tilesetPosPx;\n\nuniform vec2 tilesetPosAbs;\nuniform vec2 tileSize;\nuniform vec2 targetSize;\nuniform vec2 targetPosRel;\n\nvoid main() {\n\tvec2 targetPosPx = (targetPosRel + tilePosRel) * tileSize;\n\tvec2 targetPosNdc = ((targetPosPx / targetSize)-0.5)*2.0;\n\ttargetPosNdc.y *= -1.0;\n\n\tgl_Position = vec4(targetPosNdc, 0.0, 1.0);\n\ttilesetPosPx = tilesetPosAbs + tilePosRel * tileSize;\n}".trim(); + var FS = "\n#version 300 es\nprecision highp float;\n\nin vec2 tilesetPosPx;\nout vec4 fragColor;\nuniform sampler2D image;\nuniform bool colorize;\nuniform vec4 bg;\nuniform vec4 tint;\n\nvoid main() {\n\tfragColor = vec4(0, 0, 0, 1);\n\n\tvec4 texel = texelFetch(image, ivec2(tilesetPosPx), 0);\n\n\tif (colorize) {\n\t\ttexel.rgb = tint.a * tint.rgb + (1.0-tint.a) * texel.rgb;\n\t\tfragColor.rgb = texel.a*texel.rgb + (1.0-texel.a)*bg.rgb;\n\t\tfragColor.a = texel.a + (1.0-texel.a)*bg.a;\n\t} else {\n\t\tfragColor = texel;\n\t}\n}".trim(); + + function createProgram(gl, vss, fss) { + var vs = gl.createShader(gl.VERTEX_SHADER); + gl.shaderSource(vs, vss); + gl.compileShader(vs); + + if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) { + throw new Error(gl.getShaderInfoLog(vs) || ""); + } + + var fs = gl.createShader(gl.FRAGMENT_SHADER); + gl.shaderSource(fs, fss); + gl.compileShader(fs); + + if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) { + throw new Error(gl.getShaderInfoLog(fs) || ""); + } + + var p = gl.createProgram(); + gl.attachShader(p, vs); + gl.attachShader(p, fs); + gl.linkProgram(p); + + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { + throw new Error(gl.getProgramInfoLog(p) || ""); + } + + return p; + } + + function createQuad(gl) { + var pos = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]); + var buf = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, buf); + gl.bufferData(gl.ARRAY_BUFFER, pos, gl.STATIC_DRAW); + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + } + + function createTexture(gl, data) { + var t = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, t); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, data); + return t; + } + + var colorCache = {}; + + function parseColor(color) { + if (!(color in colorCache)) { + var parsed; + + if (color == "transparent") { + parsed = [0, 0, 0, 0]; + } else if (color.indexOf("rgba") > -1) { + parsed = (color.match(/[\d.]+/g) || []).map(Number); + + for (var i = 0; i < 3; i++) { + parsed[i] = parsed[i] / 255; + } + } else { + parsed = fromString(color).map(function ($) { + return $ / 255; + }); + parsed.push(1); + } + + colorCache[color] = parsed; + } + + return colorCache[color]; + } + + function clearToAnsi(bg) { + return "\x1B[0;48;5;" + termcolor(bg) + "m\x1B[2J"; + } + + function colorToAnsi(fg, bg) { + return "\x1B[0;38;5;" + termcolor(fg) + ";48;5;" + termcolor(bg) + "m"; + } + + function positionToAnsi(x, y) { + return "\x1B[" + (y + 1) + ";" + (x + 1) + "H"; + } + + function termcolor(color) { + var SRC_COLORS = 256.0; + var DST_COLORS = 6.0; + var COLOR_RATIO = DST_COLORS / SRC_COLORS; + var rgb = fromString(color); + var r = Math.floor(rgb[0] * COLOR_RATIO); + var g = Math.floor(rgb[1] * COLOR_RATIO); + var b = Math.floor(rgb[2] * COLOR_RATIO); + return r * 36 + g * 6 + b * 1 + 16; + } + + var Term = + /*#__PURE__*/ + function (_Backend3) { + _inheritsLoose(Term, _Backend3); + + function Term() { + var _this8; + + _this8 = _Backend3.call(this) || this; + _this8._offset = [0, 0]; + _this8._cursor = [-1, -1]; + _this8._lastColor = ""; + return _this8; + } + + var _proto8 = Term.prototype; + + _proto8.schedule = function schedule(cb) { + setTimeout(cb, 1000 / 60); + }; + + _proto8.setOptions = function setOptions(options) { + _Backend3.prototype.setOptions.call(this, options); + + var size = [options.width, options.height]; + var avail = this.computeSize(); + this._offset = avail.map(function (val, index) { + return Math.floor((val - size[index]) / 2); + }); + }; + + _proto8.clear = function clear() { + process.stdout.write(clearToAnsi(this._options.bg)); + }; + + _proto8.draw = function draw(data, clearBefore) { + // determine where to draw what with what colors + var x = data[0], + y = data[1], + ch = data[2], + fg = data[3], + bg = data[4]; // determine if we need to move the terminal cursor + + var dx = this._offset[0] + x; + var dy = this._offset[1] + y; + var size = this.computeSize(); + + if (dx < 0 || dx >= size[0]) { + return; + } + + if (dy < 0 || dy >= size[1]) { + return; + } + + if (dx !== this._cursor[0] || dy !== this._cursor[1]) { + process.stdout.write(positionToAnsi(dx, dy)); + this._cursor[0] = dx; + this._cursor[1] = dy; + } // terminals automatically clear, but if we're clearing when we're + // not otherwise provided with a character, just use a space instead + + + if (clearBefore) { + if (!ch) { + ch = " "; + } + } // if we're not clearing and not provided with a character, do nothing + + + if (!ch) { + return; + } // determine if we need to change colors + + + var newColor = colorToAnsi(fg, bg); + + if (newColor !== this._lastColor) { + process.stdout.write(newColor); + this._lastColor = newColor; + } // write the provided symbol to the display + + + var chars = [].concat(ch); + process.stdout.write(chars[0]); // update our position, given that we wrote a character + + this._cursor[0]++; + + if (this._cursor[0] >= size[0]) { + this._cursor[0] = 0; + this._cursor[1]++; + } + }; + + _proto8.computeFontSize = function computeFontSize() { + throw new Error("Terminal backend has no notion of font size"); + }; + + _proto8.eventToPosition = function eventToPosition(x, y) { + return [x, y]; + }; + + _proto8.computeSize = function computeSize() { + return [process.stdout.columns, process.stdout.rows]; + }; + + return Term; + }(Backend); + /** + * @namespace + * Contains text tokenization and breaking routines + */ + + + var RE_COLORS = /%([bc]){([^}]*)}/g; // token types + + var TYPE_TEXT = 0; + var TYPE_NEWLINE = 1; + var TYPE_FG = 2; + var TYPE_BG = 3; + /** + * Measure size of a resulting text block + */ + + function measure(str, maxWidth) { + var result = { + width: 0, + height: 1 + }; + var tokens = tokenize(str, maxWidth); + var lineWidth = 0; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + + switch (token.type) { + case TYPE_TEXT: + lineWidth += token.value.length; + break; + + case TYPE_NEWLINE: + result.height++; + result.width = Math.max(result.width, lineWidth); + lineWidth = 0; + break; + } + } + + result.width = Math.max(result.width, lineWidth); + return result; + } + /** + * Convert string to a series of a formatting commands + */ + + + function tokenize(str, maxWidth) { + var result = []; + /* first tokenization pass - split texts and color formatting commands */ + + var offset = 0; + str.replace(RE_COLORS, function (match, type, name, index) { + /* string before */ + var part = str.substring(offset, index); + + if (part.length) { + result.push({ + type: TYPE_TEXT, + value: part + }); + } + /* color command */ + + + result.push({ + type: type == "c" ? TYPE_FG : TYPE_BG, + value: name.trim() + }); + offset = index + match.length; + return ""; + }); + /* last remaining part */ + + var part = str.substring(offset); + + if (part.length) { + result.push({ + type: TYPE_TEXT, + value: part + }); + } + + return breakLines(result, maxWidth); + } + /* insert line breaks into first-pass tokenized data */ + + + function breakLines(tokens, maxWidth) { + if (!maxWidth) { + maxWidth = Infinity; + } + + var i = 0; + var lineLength = 0; + var lastTokenWithSpace = -1; + + while (i < tokens.length) { + /* take all text tokens, remove space, apply linebreaks */ + var token = tokens[i]; + + if (token.type == TYPE_NEWLINE) { + /* reset */ + lineLength = 0; + lastTokenWithSpace = -1; + } + + if (token.type != TYPE_TEXT) { + /* skip non-text tokens */ + i++; + continue; + } + /* remove spaces at the beginning of line */ + + + while (lineLength == 0 && token.value.charAt(0) == " ") { + token.value = token.value.substring(1); + } + /* forced newline? insert two new tokens after this one */ + + + var _index2 = token.value.indexOf("\n"); + + if (_index2 != -1) { + token.value = breakInsideToken(tokens, i, _index2, true); + /* if there are spaces at the end, we must remove them (we do not want the line too long) */ + + var arr = token.value.split(""); + + while (arr.length && arr[arr.length - 1] == " ") { + arr.pop(); + } + + token.value = arr.join(""); + } + /* token degenerated? */ + + + if (!token.value.length) { + tokens.splice(i, 1); + continue; + } + + if (lineLength + token.value.length > maxWidth) { + /* line too long, find a suitable breaking spot */ + + /* is it possible to break within this token? */ + var _index3 = -1; + + while (1) { + var nextIndex = token.value.indexOf(" ", _index3 + 1); + + if (nextIndex == -1) { + break; + } + + if (lineLength + nextIndex > maxWidth) { + break; + } + + _index3 = nextIndex; + } + + if (_index3 != -1) { + /* break at space within this one */ + token.value = breakInsideToken(tokens, i, _index3, true); + } else if (lastTokenWithSpace != -1) { + /* is there a previous token where a break can occur? */ + var _token = tokens[lastTokenWithSpace]; + + var breakIndex = _token.value.lastIndexOf(" "); + + _token.value = breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true); + i = lastTokenWithSpace; + } else { + /* force break in this token */ + token.value = breakInsideToken(tokens, i, maxWidth - lineLength, false); + } + } else { + /* line not long, continue */ + lineLength += token.value.length; + + if (token.value.indexOf(" ") != -1) { + lastTokenWithSpace = i; + } + } + + i++; + /* advance to next token */ + } + + tokens.push({ + type: TYPE_NEWLINE + }); + /* insert fake newline to fix the last text line */ + + /* remove trailing space from text tokens before newlines */ + + var lastTextToken = null; + + for (var _i = 0; _i < tokens.length; _i++) { + var _token2 = tokens[_i]; + + switch (_token2.type) { + case TYPE_TEXT: + lastTextToken = _token2; + break; + + case TYPE_NEWLINE: + if (lastTextToken) { + /* remove trailing space */ + var _arr = lastTextToken.value.split(""); + + while (_arr.length && _arr[_arr.length - 1] == " ") { + _arr.pop(); + } + + lastTextToken.value = _arr.join(""); + } + + lastTextToken = null; + break; + } + } + + tokens.pop(); + /* remove fake token */ + + return tokens; + } + /** + * Create new tokens and insert them into the stream + * @param {object[]} tokens + * @param {int} tokenIndex Token being processed + * @param {int} breakIndex Index within current token's value + * @param {bool} removeBreakChar Do we want to remove the breaking character? + * @returns {string} remaining unbroken token value + */ + + + function breakInsideToken(tokens, tokenIndex, breakIndex, removeBreakChar) { + var newBreakToken = { + type: TYPE_NEWLINE + }; + var newTextToken = { + type: TYPE_TEXT, + value: tokens[tokenIndex].value.substring(breakIndex + (removeBreakChar ? 1 : 0)) + }; + tokens.splice(tokenIndex + 1, 0, newBreakToken, newTextToken); + return tokens[tokenIndex].value.substring(0, breakIndex); + } + + var text = + /*#__PURE__*/ + Object.freeze({ + TYPE_TEXT: TYPE_TEXT, + TYPE_NEWLINE: TYPE_NEWLINE, + TYPE_FG: TYPE_FG, + TYPE_BG: TYPE_BG, + measure: measure, + tokenize: tokenize + }); + /** Default with for display and map generators */ + + var DEFAULT_WIDTH = 80; + /** Default height for display and map generators */ + + var DEFAULT_HEIGHT = 25; + var DIRS = { + 4: [[0, -1], [1, 0], [0, 1], [-1, 0]], + 8: [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1]], + 6: [[-1, -1], [1, -1], [2, 0], [1, 1], [-1, 1], [-2, 0]] + }; + var KEYS = { + /** Cancel key. */ + VK_CANCEL: 3, + + /** Help key. */ + VK_HELP: 6, + + /** Backspace key. */ + VK_BACK_SPACE: 8, + + /** Tab key. */ + VK_TAB: 9, + + /** 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. */ + VK_CLEAR: 12, + + /** Return/enter key on the main keyboard. */ + VK_RETURN: 13, + + /** Reserved, but not used. */ + VK_ENTER: 14, + + /** Shift key. */ + VK_SHIFT: 16, + + /** Control key. */ + VK_CONTROL: 17, + + /** Alt (Option on Mac) key. */ + VK_ALT: 18, + + /** Pause key. */ + VK_PAUSE: 19, + + /** Caps lock. */ + VK_CAPS_LOCK: 20, + + /** Escape key. */ + VK_ESCAPE: 27, + + /** Space bar. */ + VK_SPACE: 32, + + /** Page Up key. */ + VK_PAGE_UP: 33, + + /** Page Down key. */ + VK_PAGE_DOWN: 34, + + /** End key. */ + VK_END: 35, + + /** Home key. */ + VK_HOME: 36, + + /** Left arrow. */ + VK_LEFT: 37, + + /** Up arrow. */ + VK_UP: 38, + + /** Right arrow. */ + VK_RIGHT: 39, + + /** Down arrow. */ + VK_DOWN: 40, + + /** Print Screen key. */ + VK_PRINTSCREEN: 44, + + /** Ins(ert) key. */ + VK_INSERT: 45, + + /** Del(ete) key. */ + VK_DELETE: 46, + + /***/ + VK_0: 48, + + /***/ + VK_1: 49, + + /***/ + VK_2: 50, + + /***/ + VK_3: 51, + + /***/ + VK_4: 52, + + /***/ + VK_5: 53, + + /***/ + VK_6: 54, + + /***/ + VK_7: 55, + + /***/ + VK_8: 56, + + /***/ + VK_9: 57, + + /** Colon (:) key. Requires Gecko 15.0 */ + VK_COLON: 58, + + /** Semicolon (;) key. */ + VK_SEMICOLON: 59, + + /** Less-than (<) key. Requires Gecko 15.0 */ + VK_LESS_THAN: 60, + + /** Equals (=) key. */ + VK_EQUALS: 61, + + /** Greater-than (>) key. Requires Gecko 15.0 */ + VK_GREATER_THAN: 62, + + /** Question mark (?) key. Requires Gecko 15.0 */ + VK_QUESTION_MARK: 63, + + /** Atmark (@) key. Requires Gecko 15.0 */ + VK_AT: 64, + + /***/ + VK_A: 65, + + /***/ + VK_B: 66, + + /***/ + VK_C: 67, + + /***/ + VK_D: 68, + + /***/ + VK_E: 69, + + /***/ + VK_F: 70, + + /***/ + VK_G: 71, + + /***/ + VK_H: 72, + + /***/ + VK_I: 73, + + /***/ + VK_J: 74, + + /***/ + VK_K: 75, + + /***/ + VK_L: 76, + + /***/ + VK_M: 77, + + /***/ + VK_N: 78, + + /***/ + VK_O: 79, + + /***/ + VK_P: 80, + + /***/ + VK_Q: 81, + + /***/ + VK_R: 82, + + /***/ + VK_S: 83, + + /***/ + VK_T: 84, + + /***/ + VK_U: 85, + + /***/ + VK_V: 86, + + /***/ + VK_W: 87, + + /***/ + VK_X: 88, + + /***/ + VK_Y: 89, + + /***/ + VK_Z: 90, + + /***/ + VK_CONTEXT_MENU: 93, + + /** 0 on the numeric keypad. */ + VK_NUMPAD0: 96, + + /** 1 on the numeric keypad. */ + VK_NUMPAD1: 97, + + /** 2 on the numeric keypad. */ + VK_NUMPAD2: 98, + + /** 3 on the numeric keypad. */ + VK_NUMPAD3: 99, + + /** 4 on the numeric keypad. */ + VK_NUMPAD4: 100, + + /** 5 on the numeric keypad. */ + VK_NUMPAD5: 101, + + /** 6 on the numeric keypad. */ + VK_NUMPAD6: 102, + + /** 7 on the numeric keypad. */ + VK_NUMPAD7: 103, + + /** 8 on the numeric keypad. */ + VK_NUMPAD8: 104, + + /** 9 on the numeric keypad. */ + VK_NUMPAD9: 105, + + /** * on the numeric keypad. */ + VK_MULTIPLY: 106, + + /** + on the numeric keypad. */ + VK_ADD: 107, + + /***/ + VK_SEPARATOR: 108, + + /** - on the numeric keypad. */ + VK_SUBTRACT: 109, + + /** Decimal point on the numeric keypad. */ + VK_DECIMAL: 110, + + /** / on the numeric keypad. */ + VK_DIVIDE: 111, + + /** F1 key. */ + VK_F1: 112, + + /** F2 key. */ + VK_F2: 113, + + /** F3 key. */ + VK_F3: 114, + + /** F4 key. */ + VK_F4: 115, + + /** F5 key. */ + VK_F5: 116, + + /** F6 key. */ + VK_F6: 117, + + /** F7 key. */ + VK_F7: 118, + + /** F8 key. */ + VK_F8: 119, + + /** F9 key. */ + VK_F9: 120, + + /** F10 key. */ + VK_F10: 121, + + /** F11 key. */ + VK_F11: 122, + + /** F12 key. */ + VK_F12: 123, + + /** F13 key. */ + VK_F13: 124, + + /** F14 key. */ + VK_F14: 125, + + /** F15 key. */ + VK_F15: 126, + + /** F16 key. */ + VK_F16: 127, + + /** F17 key. */ + VK_F17: 128, + + /** F18 key. */ + VK_F18: 129, + + /** F19 key. */ + VK_F19: 130, + + /** F20 key. */ + VK_F20: 131, + + /** F21 key. */ + VK_F21: 132, + + /** F22 key. */ + VK_F22: 133, + + /** F23 key. */ + VK_F23: 134, + + /** F24 key. */ + VK_F24: 135, + + /** Num Lock key. */ + VK_NUM_LOCK: 144, + + /** Scroll Lock key. */ + VK_SCROLL_LOCK: 145, + + /** Circumflex (^) key. Requires Gecko 15.0 */ + VK_CIRCUMFLEX: 160, + + /** Exclamation (!) key. Requires Gecko 15.0 */ + VK_EXCLAMATION: 161, + + /** Double quote () key. Requires Gecko 15.0 */ + VK_DOUBLE_QUOTE: 162, + + /** Hash (#) key. Requires Gecko 15.0 */ + VK_HASH: 163, + + /** Dollar sign ($) key. Requires Gecko 15.0 */ + VK_DOLLAR: 164, + + /** Percent (%) key. Requires Gecko 15.0 */ + VK_PERCENT: 165, + + /** Ampersand (&) key. Requires Gecko 15.0 */ + VK_AMPERSAND: 166, + + /** Underscore (_) key. Requires Gecko 15.0 */ + VK_UNDERSCORE: 167, + + /** Open parenthesis (() key. Requires Gecko 15.0 */ + VK_OPEN_PAREN: 168, + + /** Close parenthesis ()) key. Requires Gecko 15.0 */ + VK_CLOSE_PAREN: 169, + + /* Asterisk (*) key. Requires Gecko 15.0 */ + VK_ASTERISK: 170, + + /** Plus (+) key. Requires Gecko 15.0 */ + VK_PLUS: 171, + + /** Pipe (|) key. Requires Gecko 15.0 */ + VK_PIPE: 172, + + /** Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 */ + VK_HYPHEN_MINUS: 173, + + /** Open curly bracket ({) key. Requires Gecko 15.0 */ + VK_OPEN_CURLY_BRACKET: 174, + + /** Close curly bracket (}) key. Requires Gecko 15.0 */ + VK_CLOSE_CURLY_BRACKET: 175, + + /** Tilde (~) key. Requires Gecko 15.0 */ + VK_TILDE: 176, + + /** Comma (,) key. */ + VK_COMMA: 188, + + /** Period (.) key. */ + VK_PERIOD: 190, + + /** Slash (/) key. */ + VK_SLASH: 191, + + /** Back tick (`) key. */ + VK_BACK_QUOTE: 192, + + /** Open square bracket ([) key. */ + VK_OPEN_BRACKET: 219, + + /** Back slash (\) key. */ + VK_BACK_SLASH: 220, + + /** Close square bracket (]) key. */ + VK_CLOSE_BRACKET: 221, + + /** Quote (''') key. */ + VK_QUOTE: 222, + + /** Meta key on Linux, Command key on Mac. */ + VK_META: 224, + + /** AltGr key on Linux. Requires Gecko 15.0 */ + VK_ALTGR: 225, + + /** Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 */ + VK_WIN: 91, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANA: 21, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANGUL: 21, + + /** 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 */ + VK_EISU: 22, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_JUNJA: 23, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_FINAL: 24, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANJA: 25, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANJI: 25, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_CONVERT: 28, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_NONCONVERT: 29, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_ACCEPT: 30, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_MODECHANGE: 31, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SELECT: 41, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_PRINT: 42, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_EXECUTE: 43, + + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SLEEP: 95 + }; + var BACKENDS = { + "hex": Hex, + "rect": Rect, + "tile": Tile, + "tile-gl": TileGL, + "term": Term + }; + var DEFAULT_OPTIONS = { + width: DEFAULT_WIDTH, + height: DEFAULT_HEIGHT, + transpose: false, + layout: "rect", + fontSize: 15, + spacing: 1, + border: 0, + forceSquareRatio: false, + fontFamily: "monospace", + fontStyle: "", + fg: "#ccc", + bg: "#000", + tileWidth: 32, + tileHeight: 32, + tileMap: {}, + tileSet: null, + tileColorize: false + }; + /** + * @class Visual map display + */ + + var Display = + /*#__PURE__*/ + function () { + function Display(options) { + if (options === void 0) { + options = {}; + } + + this._data = {}; + this._dirty = false; // false = nothing, true = all, object = dirty cells + + this._options = {}; + options = Object.assign({}, DEFAULT_OPTIONS, options); + this.setOptions(options); + this.DEBUG = this.DEBUG.bind(this); + this._tick = this._tick.bind(this); + + this._backend.schedule(this._tick); + } + /** + * Debug helper, ideal as a map generator callback. Always bound to this. + * @param {int} x + * @param {int} y + * @param {int} what + */ + + + var _proto9 = Display.prototype; + + _proto9.DEBUG = function DEBUG(x, y, what) { + var colors = [this._options.bg, this._options.fg]; + this.draw(x, y, null, null, colors[what % colors.length]); + }; + /** + * Clear the whole display (cover it with background color) + */ + + + _proto9.clear = function clear() { + this._data = {}; + this._dirty = true; + }; + /** + * @see ROT.Display + */ + + + _proto9.setOptions = function setOptions(options) { + Object.assign(this._options, options); + + if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) { + if (options.layout) { + var ctor = BACKENDS[options.layout]; + this._backend = new ctor(); + } + + this._backend.setOptions(this._options); + + this._dirty = true; + } + + return this; + }; + /** + * Returns currently set options + */ + + + _proto9.getOptions = function getOptions() { + return this._options; + }; + /** + * Returns the DOM node of this display + */ + + + _proto9.getContainer = function getContainer() { + return this._backend.getContainer(); + }; + /** + * Compute the maximum width/height to fit into a set of given constraints + * @param {int} availWidth Maximum allowed pixel width + * @param {int} availHeight Maximum allowed pixel height + * @returns {int[2]} cellWidth,cellHeight + */ + + + _proto9.computeSize = function computeSize(availWidth, availHeight) { + return this._backend.computeSize(availWidth, availHeight); + }; + /** + * Compute the maximum font size to fit into a set of given constraints + * @param {int} availWidth Maximum allowed pixel width + * @param {int} availHeight Maximum allowed pixel height + * @returns {int} fontSize + */ + + + _proto9.computeFontSize = function computeFontSize(availWidth, availHeight) { + return this._backend.computeFontSize(availWidth, availHeight); + }; + + _proto9.computeTileSize = function computeTileSize(availWidth, availHeight) { + var width = Math.floor(availWidth / this._options.width); + var height = Math.floor(availHeight / this._options.height); + return [width, height]; + }; + /** + * Convert a DOM event (mouse or touch) to map coordinates. Uses first touch for multi-touch. + * @param {Event} e event + * @returns {int[2]} -1 for values outside of the canvas + */ + + + _proto9.eventToPosition = function eventToPosition(e) { + var x, y; + + if ("touches" in e) { + x = e.touches[0].clientX; + y = e.touches[0].clientY; + } else { + x = e.clientX; + y = e.clientY; + } + + return this._backend.eventToPosition(x, y); + }; + /** + * @param {int} x + * @param {int} y + * @param {string || string[]} ch One or more chars (will be overlapping themselves) + * @param {string} [fg] foreground color + * @param {string} [bg] background color + */ + + + _proto9.draw = function draw(x, y, ch, fg, bg) { + if (!fg) { + fg = this._options.fg; + } + + if (!bg) { + bg = this._options.bg; + } + + var key = x + "," + y; + this._data[key] = [x, y, ch, fg, bg]; + + if (this._dirty === true) { + return; + } // will already redraw everything + + + if (!this._dirty) { + this._dirty = {}; + } // first! + + + this._dirty[key] = true; + }; + /** + * Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout. + * @param {int} x + * @param {int} y + * @param {string} text May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default. + * @param {int} [maxWidth] wrap at what width? + * @returns {int} lines drawn + */ + + + _proto9.drawText = function drawText(x, y, text, maxWidth) { + var fg = null; + var bg = null; + var cx = x; + var cy = y; + var lines = 1; + + if (!maxWidth) { + maxWidth = this._options.width - x; + } + + var tokens = tokenize(text, maxWidth); + + while (tokens.length) { + // interpret tokenized opcode stream + var token = tokens.shift(); + + switch (token.type) { + case TYPE_TEXT: + var isSpace = false, + isPrevSpace = false, + isFullWidth = false, + isPrevFullWidth = false; + + for (var i = 0; i < token.value.length; i++) { + var cc = token.value.charCodeAt(i); + var c = token.value.charAt(i); // Assign to `true` when the current char is full-width. + + isFullWidth = cc > 0xff00 && cc < 0xff61 || cc > 0xffdc && cc < 0xffe8 || cc > 0xffee; // Current char is space, whatever full-width or half-width both are OK. + + isSpace = c.charCodeAt(0) == 0x20 || c.charCodeAt(0) == 0x3000; // The previous char is full-width and + // current char is nether half-width nor a space. + + if (isPrevFullWidth && !isFullWidth && !isSpace) { + cx++; + } // add an extra position + // The current char is full-width and + // the previous char is not a space. + + + if (isFullWidth && !isPrevSpace) { + cx++; + } // add an extra position + + + this.draw(cx++, cy, c, fg, bg); + isPrevSpace = isSpace; + isPrevFullWidth = isFullWidth; + } + + break; + + case TYPE_FG: + fg = token.value || null; + break; + + case TYPE_BG: + bg = token.value || null; + break; + + case TYPE_NEWLINE: + cx = x; + cy++; + lines++; + break; + } + } + + return lines; + }; + /** + * Timer tick: update dirty parts + */ + + + _proto9._tick = function _tick() { + this._backend.schedule(this._tick); + + if (!this._dirty) { + return; + } + + if (this._dirty === true) { + // draw all + this._backend.clear(); + + for (var id in this._data) { + this._draw(id, false); + } // redraw cached data + + } else { + // draw only dirty + for (var key in this._dirty) { + this._draw(key, true); + } + } + + this._dirty = false; + }; + /** + * @param {string} key What to draw + * @param {bool} clearBefore Is it necessary to clean before? + */ + + + _proto9._draw = function _draw(key, clearBefore) { + var data = this._data[key]; + + if (data[4] != this._options.bg) { + clearBefore = true; + } + + this._backend.draw(data, clearBefore); + }; + + return Display; + }(); + + Display.Rect = Rect; + Display.Hex = Hex; + Display.Tile = Tile; + Display.TileGL = TileGL; + Display.Term = Term; + /** + * @class (Markov process)-based string generator. + * Copied from a RogueBasin article. + * Offers configurable order and prior. + */ + + var StringGenerator = + /*#__PURE__*/ + function () { + function StringGenerator(options) { + this._options = { + words: false, + order: 3, + prior: 0.001 + }; + Object.assign(this._options, options); + this._boundary = String.fromCharCode(0); + this._suffix = this._boundary; + this._prefix = []; + + for (var i = 0; i < this._options.order; i++) { + this._prefix.push(this._boundary); + } + + this._priorValues = {}; + this._priorValues[this._boundary] = this._options.prior; + this._data = {}; + } + /** + * Remove all learning data + */ + + + var _proto10 = StringGenerator.prototype; + + _proto10.clear = function clear() { + this._data = {}; + this._priorValues = {}; + }; + /** + * @returns {string} Generated string + */ + + + _proto10.generate = function generate() { + var result = [this._sample(this._prefix)]; + + while (result[result.length - 1] != this._boundary) { + result.push(this._sample(result)); + } + + return this._join(result.slice(0, -1)); + }; + /** + * Observe (learn) a string from a training set + */ + + + _proto10.observe = function observe(string) { + var tokens = this._split(string); + + for (var i = 0; i < tokens.length; i++) { + this._priorValues[tokens[i]] = this._options.prior; + } + + tokens = this._prefix.concat(tokens).concat(this._suffix); + /* add boundary symbols */ + + for (var _i2 = this._options.order; _i2 < tokens.length; _i2++) { + var context = tokens.slice(_i2 - this._options.order, _i2); + var event = tokens[_i2]; + + for (var j = 0; j < context.length; j++) { + var subcontext = context.slice(j); + + this._observeEvent(subcontext, event); + } + } + }; + + _proto10.getStats = function getStats() { + var parts = []; + var priorCount = Object.keys(this._priorValues).length; + priorCount--; // boundary + + parts.push("distinct samples: " + priorCount); + var dataCount = Object.keys(this._data).length; + var eventCount = 0; + + for (var p in this._data) { + eventCount += Object.keys(this._data[p]).length; + } + + parts.push("dictionary size (contexts): " + dataCount); + parts.push("dictionary size (events): " + eventCount); + return parts.join(", "); + }; + /** + * @param {string} + * @returns {string[]} + */ + + + _proto10._split = function _split(str) { + return str.split(this._options.words ? /\s+/ : ""); + }; + /** + * @param {string[]} + * @returns {string} + */ + + + _proto10._join = function _join(arr) { + return arr.join(this._options.words ? " " : ""); + }; + /** + * @param {string[]} context + * @param {string} event + */ + + + _proto10._observeEvent = function _observeEvent(context, event) { + var key = this._join(context); + + if (!(key in this._data)) { + this._data[key] = {}; + } + + var data = this._data[key]; + + if (!(event in data)) { + data[event] = 0; + } + + data[event]++; + }; + /** + * @param {string[]} + * @returns {string} + */ + + + _proto10._sample = function _sample(context) { + context = this._backoff(context); + + var key = this._join(context); + + var data = this._data[key]; + var available = {}; + + if (this._options.prior) { + for (var event in this._priorValues) { + available[event] = this._priorValues[event]; + } + + for (var _event in data) { + available[_event] += data[_event]; + } + } else { + available = data; + } + + return RNG$1.getWeightedValue(available); + }; + /** + * @param {string[]} + * @returns {string[]} + */ + + + _proto10._backoff = function _backoff(context) { + if (context.length > this._options.order) { + context = context.slice(-this._options.order); + } else if (context.length < this._options.order) { + context = this._prefix.slice(0, this._options.order - context.length).concat(context); + } + + while (!(this._join(context) in this._data) && context.length > 0) { + context = context.slice(1); + } + + return context; + }; + + return StringGenerator; + }(); + + var EventQueue = + /*#__PURE__*/ + function () { + /** + * @class Generic event queue: stores events and retrieves them based on their time + */ + function EventQueue() { + this._time = 0; + this._events = []; + this._eventTimes = []; + } + /** + * @returns {number} Elapsed time + */ + + + var _proto11 = EventQueue.prototype; + + _proto11.getTime = function getTime() { + return this._time; + }; + /** + * Clear all scheduled events + */ + + + _proto11.clear = function clear() { + this._events = []; + this._eventTimes = []; + return this; + }; + /** + * @param {?} event + * @param {number} time + */ + + + _proto11.add = function add(event, time) { + var index = this._events.length; + + for (var i = 0; i < this._eventTimes.length; i++) { + if (this._eventTimes[i] > time) { + index = i; + break; + } + } + + this._events.splice(index, 0, event); + + this._eventTimes.splice(index, 0, time); + }; + /** + * Locates the nearest event, advances time if necessary. Returns that event and removes it from the queue. + * @returns {? || null} The event previously added by addEvent, null if no event available + */ + + + _proto11.get = function get() { + if (!this._events.length) { + return null; + } + + var time = this._eventTimes.splice(0, 1)[0]; + + if (time > 0) { + /* advance */ + this._time += time; + + for (var i = 0; i < this._eventTimes.length; i++) { + this._eventTimes[i] -= time; + } + } + + return this._events.splice(0, 1)[0]; + }; + /** + * Get the time associated with the given event + * @param {?} event + * @returns {number} time + */ + + + _proto11.getEventTime = function getEventTime(event) { + var index = this._events.indexOf(event); + + if (index == -1) { + return undefined; + } + + return this._eventTimes[index]; + }; + /** + * Remove an event from the queue + * @param {?} event + * @returns {bool} success? + */ + + + _proto11.remove = function remove(event) { + var index = this._events.indexOf(event); + + if (index == -1) { + return false; + } + + this._remove(index); + + return true; + }; + + /** + * Remove an event from the queue + * @param {int} index + */ + _proto11._remove = function _remove(index) { + this._events.splice(index, 1); + + this._eventTimes.splice(index, 1); + }; + + return EventQueue; + }(); + + var Scheduler = + /*#__PURE__*/ + function () { + /** + * @class Abstract scheduler + */ + function Scheduler() { + this._queue = new EventQueue(); + this._repeat = []; + this._current = null; + } + /** + * @see ROT.EventQueue#getTime + */ + + + var _proto12 = Scheduler.prototype; + + _proto12.getTime = function getTime() { + return this._queue.getTime(); + }; + /** + * @param {?} item + * @param {bool} repeat + */ + + + _proto12.add = function add(item, repeat) { + if (repeat) { + this._repeat.push(item); + } + + return this; + }; + /** + * Get the time the given item is scheduled for + * @param {?} item + * @returns {number} time + */ + + + _proto12.getTimeOf = function getTimeOf(item) { + return this._queue.getEventTime(item); + }; + /** + * Clear all items + */ + + + _proto12.clear = function clear() { + this._queue.clear(); + + this._repeat = []; + this._current = null; + return this; + }; + /** + * Remove a previously added item + * @param {?} item + * @returns {bool} successful? + */ + + + _proto12.remove = function remove(item) { + var result = this._queue.remove(item); + + var index = this._repeat.indexOf(item); + + if (index != -1) { + this._repeat.splice(index, 1); + } + + if (this._current == item) { + this._current = null; + } + + return result; + }; + /** + * Schedule next item + * @returns {?} + */ + + + _proto12.next = function next() { + this._current = this._queue.get(); + return this._current; + }; + + return Scheduler; + }(); + /** + * @class Simple fair scheduler (round-robin style) + */ + + + var Simple = + /*#__PURE__*/ + function (_Scheduler) { + _inheritsLoose(Simple, _Scheduler); + + function Simple() { + return _Scheduler.apply(this, arguments) || this; + } + + var _proto13 = Simple.prototype; + + _proto13.add = function add(item, repeat) { + this._queue.add(item, 0); + + return _Scheduler.prototype.add.call(this, item, repeat); + }; + + _proto13.next = function next() { + if (this._current !== null && this._repeat.indexOf(this._current) != -1) { + this._queue.add(this._current, 0); + } + + return _Scheduler.prototype.next.call(this); + }; + + return Simple; + }(Scheduler); + /** + * @class Speed-based scheduler + */ + + + var Speed = + /*#__PURE__*/ + function (_Scheduler2) { + _inheritsLoose(Speed, _Scheduler2); + + function Speed() { + return _Scheduler2.apply(this, arguments) || this; + } + + var _proto14 = Speed.prototype; + + /** + * @param {object} item anything with "getSpeed" method + * @param {bool} repeat + * @param {number} [time=1/item.getSpeed()] + * @see ROT.Scheduler#add + */ + _proto14.add = function add(item, repeat, time) { + this._queue.add(item, time !== undefined ? time : 1 / item.getSpeed()); + + return _Scheduler2.prototype.add.call(this, item, repeat); + }; + /** + * @see ROT.Scheduler#next + */ + + + _proto14.next = function next() { + if (this._current && this._repeat.indexOf(this._current) != -1) { + this._queue.add(this._current, 1 / this._current.getSpeed()); + } + + return _Scheduler2.prototype.next.call(this); + }; + + return Speed; + }(Scheduler); + /** + * @class Action-based scheduler + * @augments ROT.Scheduler + */ + + + var Action = + /*#__PURE__*/ + function (_Scheduler3) { + _inheritsLoose(Action, _Scheduler3); + + function Action() { + var _this9; + + _this9 = _Scheduler3.call(this) || this; + _this9._defaultDuration = 1; + /* for newly added */ + + _this9._duration = _this9._defaultDuration; + /* for this._current */ + + return _this9; + } + /** + * @param {object} item + * @param {bool} repeat + * @param {number} [time=1] + * @see ROT.Scheduler#add + */ + + + var _proto15 = Action.prototype; + + _proto15.add = function add(item, repeat, time) { + this._queue.add(item, time || this._defaultDuration); + + return _Scheduler3.prototype.add.call(this, item, repeat); + }; + + _proto15.clear = function clear() { + this._duration = this._defaultDuration; + return _Scheduler3.prototype.clear.call(this); + }; + + _proto15.remove = function remove(item) { + if (item == this._current) { + this._duration = this._defaultDuration; + } + + return _Scheduler3.prototype.remove.call(this, item); + }; + /** + * @see ROT.Scheduler#next + */ + + + _proto15.next = function next() { + if (this._current !== null && this._repeat.indexOf(this._current) != -1) { + this._queue.add(this._current, this._duration || this._defaultDuration); + + this._duration = this._defaultDuration; + } + + return _Scheduler3.prototype.next.call(this); + }; + /** + * Set duration for the active item + */ + + + _proto15.setDuration = function setDuration(time) { + if (this._current) { + this._duration = time; + } + + return this; + }; + + return Action; + }(Scheduler); + + var index = { + Simple: Simple, + Speed: Speed, + Action: Action + }; + + var FOV = + /*#__PURE__*/ + function () { + /** + * @class Abstract FOV algorithm + * @param {function} lightPassesCallback Does the light pass through x,y? + * @param {object} [options] + * @param {int} [options.topology=8] 4/6/8 + */ + function FOV(lightPassesCallback, options) { + if (options === void 0) { + options = {}; + } + + this._lightPasses = lightPassesCallback; + this._options = Object.assign({ + topology: 8 + }, options); + } + /** + * Return all neighbors in a concentric ring + * @param {int} cx center-x + * @param {int} cy center-y + * @param {int} r range + */ + + + var _proto16 = FOV.prototype; + + _proto16._getCircle = function _getCircle(cx, cy, r) { + var result = []; + var dirs, countFactor, startOffset; + + switch (this._options.topology) { + case 4: + countFactor = 1; + startOffset = [0, 1]; + dirs = [DIRS[8][7], DIRS[8][1], DIRS[8][3], DIRS[8][5]]; + break; + + case 6: + dirs = DIRS[6]; + countFactor = 1; + startOffset = [-1, 1]; + break; + + case 8: + dirs = DIRS[4]; + countFactor = 2; + startOffset = [-1, 1]; + break; + + default: + throw new Error("Incorrect topology for FOV computation"); + break; + } + /* starting neighbor */ + + + var x = cx + startOffset[0] * r; + var y = cy + startOffset[1] * r; + /* circle */ + + for (var i = 0; i < dirs.length; i++) { + for (var j = 0; j < r * countFactor; j++) { + result.push([x, y]); + x += dirs[i][0]; + y += dirs[i][1]; + } + } + + return result; + }; + + return FOV; + }(); + /** + * @class Discrete shadowcasting algorithm. Obsoleted by Precise shadowcasting. + * @augments ROT.FOV + */ + + + var DiscreteShadowcasting = + /*#__PURE__*/ + function (_FOV) { + _inheritsLoose(DiscreteShadowcasting, _FOV); + + function DiscreteShadowcasting() { + return _FOV.apply(this, arguments) || this; + } + + var _proto17 = DiscreteShadowcasting.prototype; + + _proto17.compute = function compute(x, y, R, callback) { + /* this place is always visible */ + callback(x, y, 0, 1); + /* standing in a dark place. FIXME is this a good idea? */ + + if (!this._lightPasses(x, y)) { + return; + } + /* start and end angles */ + + + var DATA = []; + var A, B, cx, cy, blocks; + /* analyze surrounding cells in concentric rings, starting from the center */ + + for (var r = 1; r <= R; r++) { + var neighbors = this._getCircle(x, y, r); + + var angle = 360 / neighbors.length; + + for (var i = 0; i < neighbors.length; i++) { + cx = neighbors[i][0]; + cy = neighbors[i][1]; + A = angle * (i - 0.5); + B = A + angle; + blocks = !this._lightPasses(cx, cy); + + if (this._visibleCoords(Math.floor(A), Math.ceil(B), blocks, DATA)) { + callback(cx, cy, r, 1); + } + + if (DATA.length == 2 && DATA[0] == 0 && DATA[1] == 360) { + return; + } + /* cutoff? */ + + } + /* for all cells in this ring */ + + } + /* for all rings */ + + }; + /** + * @param {int} A start angle + * @param {int} B end angle + * @param {bool} blocks Does current cell block visibility? + * @param {int[][]} DATA shadowed angle pairs + */ + + + _proto17._visibleCoords = function _visibleCoords(A, B, blocks, DATA) { + if (A < 0) { + var v1 = this._visibleCoords(0, B, blocks, DATA); + + var v2 = this._visibleCoords(360 + A, 360, blocks, DATA); + + return v1 || v2; + } + + var index = 0; + + while (index < DATA.length && DATA[index] < A) { + index++; + } + + if (index == DATA.length) { + /* completely new shadow */ + if (blocks) { + DATA.push(A, B); + } + + return true; + } + + var count = 0; + + if (index % 2) { + /* this shadow starts in an existing shadow, or within its ending boundary */ + while (index < DATA.length && DATA[index] < B) { + index++; + count++; + } + + if (count == 0) { + return false; + } + + if (blocks) { + if (count % 2) { + DATA.splice(index - count, count, B); + } else { + DATA.splice(index - count, count); + } + } + + return true; + } else { + /* this shadow starts outside an existing shadow, or within a starting boundary */ + while (index < DATA.length && DATA[index] < B) { + index++; + count++; + } + /* visible when outside an existing shadow, or when overlapping */ + + + if (A == DATA[index - count] && count == 1) { + return false; + } + + if (blocks) { + if (count % 2) { + DATA.splice(index - count, count, A); + } else { + DATA.splice(index - count, count, A, B); + } + } + + return true; + } + }; + + return DiscreteShadowcasting; + }(FOV); + /** + * @class Precise shadowcasting algorithm + * @augments ROT.FOV + */ + + + var PreciseShadowcasting = + /*#__PURE__*/ + function (_FOV2) { + _inheritsLoose(PreciseShadowcasting, _FOV2); + + function PreciseShadowcasting() { + return _FOV2.apply(this, arguments) || this; + } + + var _proto18 = PreciseShadowcasting.prototype; + + _proto18.compute = function compute(x, y, R, callback) { + /* this place is always visible */ + callback(x, y, 0, 1); + /* standing in a dark place. FIXME is this a good idea? */ + + if (!this._lightPasses(x, y)) { + return; + } + /* list of all shadows */ + + + var SHADOWS = []; + var cx, cy, blocks, A1, A2, visibility; + /* analyze surrounding cells in concentric rings, starting from the center */ + + for (var r = 1; r <= R; r++) { + var neighbors = this._getCircle(x, y, r); + + var neighborCount = neighbors.length; + + for (var i = 0; i < neighborCount; i++) { + cx = neighbors[i][0]; + cy = neighbors[i][1]; + /* shift half-an-angle backwards to maintain consistency of 0-th cells */ + + A1 = [i ? 2 * i - 1 : 2 * neighborCount - 1, 2 * neighborCount]; + A2 = [2 * i + 1, 2 * neighborCount]; + blocks = !this._lightPasses(cx, cy); + visibility = this._checkVisibility(A1, A2, blocks, SHADOWS); + + if (visibility) { + callback(cx, cy, r, visibility); + } + + if (SHADOWS.length == 2 && SHADOWS[0][0] == 0 && SHADOWS[1][0] == SHADOWS[1][1]) { + return; + } + /* cutoff? */ + + } + /* for all cells in this ring */ + + } + /* for all rings */ + + }; + /** + * @param {int[2]} A1 arc start + * @param {int[2]} A2 arc end + * @param {bool} blocks Does current arc block visibility? + * @param {int[][]} SHADOWS list of active shadows + */ + + + _proto18._checkVisibility = function _checkVisibility(A1, A2, blocks, SHADOWS) { + if (A1[0] > A2[0]) { + /* split into two sub-arcs */ + var v1 = this._checkVisibility(A1, [A1[1], A1[1]], blocks, SHADOWS); + + var v2 = this._checkVisibility([0, 1], A2, blocks, SHADOWS); + + return (v1 + v2) / 2; + } + /* index1: first shadow >= A1 */ + + + var index1 = 0, + edge1 = false; + + while (index1 < SHADOWS.length) { + var old = SHADOWS[index1]; + var diff = old[0] * A1[1] - A1[0] * old[1]; + + if (diff >= 0) { + /* old >= A1 */ + if (diff == 0 && !(index1 % 2)) { + edge1 = true; + } + + break; + } + + index1++; + } + /* index2: last shadow <= A2 */ + + + var index2 = SHADOWS.length, + edge2 = false; + + while (index2--) { + var _old = SHADOWS[index2]; + + var _diff = A2[0] * _old[1] - _old[0] * A2[1]; + + if (_diff >= 0) { + /* old <= A2 */ + if (_diff == 0 && index2 % 2) { + edge2 = true; + } + + break; + } + } + + var visible = true; + + if (index1 == index2 && (edge1 || edge2)) { + /* subset of existing shadow, one of the edges match */ + visible = false; + } else if (edge1 && edge2 && index1 + 1 == index2 && index2 % 2) { + /* completely equivalent with existing shadow */ + visible = false; + } else if (index1 > index2 && index1 % 2) { + /* subset of existing shadow, not touching */ + visible = false; + } + + if (!visible) { + return 0; + } + /* fast case: not visible */ + + + var visibleLength; + /* compute the length of visible arc, adjust list of shadows (if blocking) */ + + var remove = index2 - index1 + 1; + + if (remove % 2) { + if (index1 % 2) { + /* first edge within existing shadow, second outside */ + var P = SHADOWS[index1]; + visibleLength = (A2[0] * P[1] - P[0] * A2[1]) / (P[1] * A2[1]); + + if (blocks) { + SHADOWS.splice(index1, remove, A2); + } + } else { + /* second edge within existing shadow, first outside */ + var _P = SHADOWS[index2]; + visibleLength = (_P[0] * A1[1] - A1[0] * _P[1]) / (A1[1] * _P[1]); + + if (blocks) { + SHADOWS.splice(index1, remove, A1); + } + } + } else { + if (index1 % 2) { + /* both edges within existing shadows */ + var P1 = SHADOWS[index1]; + var P2 = SHADOWS[index2]; + visibleLength = (P2[0] * P1[1] - P1[0] * P2[1]) / (P1[1] * P2[1]); + + if (blocks) { + SHADOWS.splice(index1, remove); + } + } else { + /* both edges outside existing shadows */ + if (blocks) { + SHADOWS.splice(index1, remove, A1, A2); + } + + return 1; + /* whole arc visible! */ + } + } + + var arcLength = (A2[0] * A1[1] - A1[0] * A2[1]) / (A1[1] * A2[1]); + return visibleLength / arcLength; + }; + + return PreciseShadowcasting; + }(FOV); + /** Octants used for translating recursive shadowcasting offsets */ + + + var OCTANTS = [[-1, 0, 0, 1], [0, -1, 1, 0], [0, -1, -1, 0], [-1, 0, 0, -1], [1, 0, 0, -1], [0, 1, -1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]; + /** + * @class Recursive shadowcasting algorithm + * Currently only supports 4/8 topologies, not hexagonal. + * Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting + * @augments ROT.FOV + */ + + var RecursiveShadowcasting = + /*#__PURE__*/ + function (_FOV3) { + _inheritsLoose(RecursiveShadowcasting, _FOV3); + + function RecursiveShadowcasting() { + return _FOV3.apply(this, arguments) || this; + } + + var _proto19 = RecursiveShadowcasting.prototype; + + /** + * Compute visibility for a 360-degree circle + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {function} callback + */ + _proto19.compute = function compute(x, y, R, callback) { + //You can always see your own tile + callback(x, y, 0, 1); + + for (var i = 0; i < OCTANTS.length; i++) { + this._renderOctant(x, y, OCTANTS[i], R, callback); + } + }; + /** + * Compute visibility for a 180-degree arc + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {int} dir Direction to look in (expressed in a ROT.DIRS value); + * @param {function} callback + */ + + + _proto19.compute180 = function compute180(x, y, R, dir, callback) { + //You can always see your own tile + callback(x, y, 0, 1); + var previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees + + var nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees + + var nextOctant = (dir + 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees + + this._renderOctant(x, y, OCTANTS[nextPreviousOctant], R, callback); + + this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); + + this._renderOctant(x, y, OCTANTS[dir], R, callback); + + this._renderOctant(x, y, OCTANTS[nextOctant], R, callback); + }; + + /** + * Compute visibility for a 90-degree arc + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {int} dir Direction to look in (expressed in a ROT.DIRS value); + * @param {function} callback + */ + _proto19.compute90 = function compute90(x, y, R, dir, callback) { + //You can always see your own tile + callback(x, y, 0, 1); + var previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees + + this._renderOctant(x, y, OCTANTS[dir], R, callback); + + this._renderOctant(x, y, OCTANTS[previousOctant], R, callback); + }; + /** + * Render one octant (45-degree arc) of the viewshed + * @param {int} x + * @param {int} y + * @param {int} octant Octant to be rendered + * @param {int} R Maximum visibility radius + * @param {function} callback + */ + + + _proto19._renderOctant = function _renderOctant(x, y, octant, R, callback) { + //Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses + this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback); + }; + /** + * Actually calculates the visibility + * @param {int} startX The starting X coordinate + * @param {int} startY The starting Y coordinate + * @param {int} row The row to render + * @param {float} visSlopeStart The slope to start at + * @param {float} visSlopeEnd The slope to end at + * @param {int} radius The radius to reach out to + * @param {int} xx + * @param {int} xy + * @param {int} yx + * @param {int} yy + * @param {function} callback The callback to use when we hit a block that is visible + */ + + + _proto19._castVisibility = function _castVisibility(startX, startY, row, visSlopeStart, visSlopeEnd, radius, xx, xy, yx, yy, callback) { + if (visSlopeStart < visSlopeEnd) { + return; + } + + for (var i = row; i <= radius; i++) { + var dx = -i - 1; + var dy = -i; + var blocked = false; + var newStart = 0; //'Row' could be column, names here assume octant 0 and would be flipped for half the octants + + while (dx <= 0) { + dx += 1; //Translate from relative coordinates to map coordinates + + var mapX = startX + dx * xx + dy * xy; + var mapY = startY + dx * yx + dy * yy; //Range of the row + + var slopeStart = (dx - 0.5) / (dy + 0.5); + var slopeEnd = (dx + 0.5) / (dy - 0.5); //Ignore if not yet at left edge of Octant + + if (slopeEnd > visSlopeStart) { + continue; + } //Done if past right edge + + + if (slopeStart < visSlopeEnd) { + break; + } //If it's in range, it's visible + + + if (dx * dx + dy * dy < radius * radius) { + callback(mapX, mapY, i, 1); + } + + if (!blocked) { + //If tile is a blocking tile, cast around it + if (!this._lightPasses(mapX, mapY) && i < radius) { + blocked = true; + + this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback); + + newStart = slopeEnd; + } + } else { + //Keep narrowing if scanning across a block + if (!this._lightPasses(mapX, mapY)) { + newStart = slopeEnd; + continue; + } //Block has ended + + + blocked = false; + visSlopeStart = newStart; + } + } + + if (blocked) { + break; + } + } + }; + + return RecursiveShadowcasting; + }(FOV); + + var index$1 = { + DiscreteShadowcasting: DiscreteShadowcasting, + PreciseShadowcasting: PreciseShadowcasting, + RecursiveShadowcasting: RecursiveShadowcasting + }; + + var Map = + /*#__PURE__*/ + function () { + /** + * @class Base map generator + * @param {int} [width=ROT.DEFAULT_WIDTH] + * @param {int} [height=ROT.DEFAULT_HEIGHT] + */ + function Map(width, height) { + if (width === void 0) { + width = DEFAULT_WIDTH; + } + + if (height === void 0) { + height = DEFAULT_HEIGHT; + } + + this._width = width; + this._height = height; + } + + var _proto20 = Map.prototype; + + _proto20._fillMap = function _fillMap(value) { + var map = []; + + for (var i = 0; i < this._width; i++) { + map.push([]); + + for (var j = 0; j < this._height; j++) { + map[i].push(value); + } + } + + return map; + }; + + return Map; + }(); + /** + * @class Simple empty rectangular room + * @augments ROT.Map + */ + + + var Arena = + /*#__PURE__*/ + function (_Map) { + _inheritsLoose(Arena, _Map); + + function Arena() { + return _Map.apply(this, arguments) || this; + } + + var _proto21 = Arena.prototype; + + _proto21.create = function create(callback) { + var w = this._width - 1; + var h = this._height - 1; + + for (var i = 0; i <= w; i++) { + for (var j = 0; j <= h; j++) { + var empty = i && j && i < w && j < h; + callback(i, j, empty ? 0 : 1); + } + } + + return this; + }; + + return Arena; + }(Map); + /** + * @class Dungeon map: has rooms and corridors + * @augments ROT.Map + */ + + + var Dungeon = + /*#__PURE__*/ + function (_Map2) { + _inheritsLoose(Dungeon, _Map2); + + function Dungeon(width, height) { + var _this10; + + _this10 = _Map2.call(this, width, height) || this; + _this10._rooms = []; + _this10._corridors = []; + return _this10; + } + /** + * Get all generated rooms + * @returns {ROT.Map.Feature.Room[]} + */ + + + var _proto22 = Dungeon.prototype; + + _proto22.getRooms = function getRooms() { + return this._rooms; + }; + /** + * Get all generated corridors + * @returns {ROT.Map.Feature.Corridor[]} + */ + + + _proto22.getCorridors = function getCorridors() { + return this._corridors; + }; + + return Dungeon; + }(Map); + /** + * @class Dungeon feature; has own .create() method + */ + + + var Feature = function Feature() {}; + /** + * @class Room + * @augments ROT.Map.Feature + * @param {int} x1 + * @param {int} y1 + * @param {int} x2 + * @param {int} y2 + * @param {int} [doorX] + * @param {int} [doorY] + */ + + + var Room = + /*#__PURE__*/ + function (_Feature) { + _inheritsLoose(Room, _Feature); + + function Room(x1, y1, x2, y2, doorX, doorY) { + var _this11; + + _this11 = _Feature.call(this) || this; + _this11._x1 = x1; + _this11._y1 = y1; + _this11._x2 = x2; + _this11._y2 = y2; + _this11._doors = {}; + + if (doorX !== undefined && doorY !== undefined) { + _this11.addDoor(doorX, doorY); + } + + return _this11; + } + + /** + * Room of random size, with a given doors and direction + */ + Room.createRandomAt = function createRandomAt(x, y, dx, dy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = RNG$1.getUniformInt(min, max); + min = options.roomHeight[0]; + max = options.roomHeight[1]; + var height = RNG$1.getUniformInt(min, max); + + if (dx == 1) { + /* to the right */ + var y2 = y - Math.floor(RNG$1.getUniform() * height); + return new this(x + 1, y2, x + width, y2 + height - 1, x, y); + } + + if (dx == -1) { + /* to the left */ + var _y = y - Math.floor(RNG$1.getUniform() * height); + + return new this(x - width, _y, x - 1, _y + height - 1, x, y); + } + + if (dy == 1) { + /* to the bottom */ + var x2 = x - Math.floor(RNG$1.getUniform() * width); + return new this(x2, y + 1, x2 + width - 1, y + height, x, y); + } + + if (dy == -1) { + /* to the top */ + var _x = x - Math.floor(RNG$1.getUniform() * width); + + return new this(_x, y - height, _x + width - 1, y - 1, x, y); + } + + throw new Error("dx or dy must be 1 or -1"); + }; + /** + * Room of random size, positioned around center coords + */ + + + Room.createRandomCenter = function createRandomCenter(cx, cy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = RNG$1.getUniformInt(min, max); + min = options.roomHeight[0]; + max = options.roomHeight[1]; + var height = RNG$1.getUniformInt(min, max); + var x1 = cx - Math.floor(RNG$1.getUniform() * width); + var y1 = cy - Math.floor(RNG$1.getUniform() * height); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + return new this(x1, y1, x2, y2); + }; + /** + * Room of random size within a given dimensions + */ + + + Room.createRandom = function createRandom(availWidth, availHeight, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = RNG$1.getUniformInt(min, max); + min = options.roomHeight[0]; + max = options.roomHeight[1]; + var height = RNG$1.getUniformInt(min, max); + var left = availWidth - width - 1; + var top = availHeight - height - 1; + var x1 = 1 + Math.floor(RNG$1.getUniform() * left); + var y1 = 1 + Math.floor(RNG$1.getUniform() * top); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + return new this(x1, y1, x2, y2); + }; + + var _proto23 = Room.prototype; + + _proto23.addDoor = function addDoor(x, y) { + this._doors[x + "," + y] = 1; + return this; + }; + /** + * @param {function} + */ + + + _proto23.getDoors = function getDoors(cb) { + for (var key in this._doors) { + var parts = key.split(","); + cb(parseInt(parts[0]), parseInt(parts[1])); + } + + return this; + }; + + _proto23.clearDoors = function clearDoors() { + this._doors = {}; + return this; + }; + + _proto23.addDoors = function addDoors(isWallCallback) { + var left = this._x1 - 1; + var right = this._x2 + 1; + var top = this._y1 - 1; + var bottom = this._y2 + 1; + + for (var x = left; x <= right; x++) { + for (var y = top; y <= bottom; y++) { + if (x != left && x != right && y != top && y != bottom) { + continue; + } + + if (isWallCallback(x, y)) { + continue; + } + + this.addDoor(x, y); + } + } + + return this; + }; + + _proto23.debug = function debug() { + console.log("room", this._x1, this._y1, this._x2, this._y2); + }; + + _proto23.isValid = function isValid(isWallCallback, canBeDugCallback) { + var left = this._x1 - 1; + var right = this._x2 + 1; + var top = this._y1 - 1; + var bottom = this._y2 + 1; + + for (var x = left; x <= right; x++) { + for (var y = top; y <= bottom; y++) { + if (x == left || x == right || y == top || y == bottom) { + if (!isWallCallback(x, y)) { + return false; + } + } else { + if (!canBeDugCallback(x, y)) { + return false; + } + } + } + } + + return true; + }; + /** + * @param {function} digCallback Dig callback with a signature (x, y, value). Values: 0 = empty, 1 = wall, 2 = door. Multiple doors are allowed. + */ + + + _proto23.create = function create(digCallback) { + var left = this._x1 - 1; + var right = this._x2 + 1; + var top = this._y1 - 1; + var bottom = this._y2 + 1; + var value = 0; + + for (var x = left; x <= right; x++) { + for (var y = top; y <= bottom; y++) { + if (x + "," + y in this._doors) { + value = 2; + } else if (x == left || x == right || y == top || y == bottom) { + value = 1; + } else { + value = 0; + } + + digCallback(x, y, value); + } + } + }; + + _proto23.getCenter = function getCenter() { + return [Math.round((this._x1 + this._x2) / 2), Math.round((this._y1 + this._y2) / 2)]; + }; + + _proto23.getLeft = function getLeft() { + return this._x1; + }; + + _proto23.getRight = function getRight() { + return this._x2; + }; + + _proto23.getTop = function getTop() { + return this._y1; + }; + + _proto23.getBottom = function getBottom() { + return this._y2; + }; + + return Room; + }(Feature); + /** + * @class Corridor + * @augments ROT.Map.Feature + * @param {int} startX + * @param {int} startY + * @param {int} endX + * @param {int} endY + */ + + + var Corridor = + /*#__PURE__*/ + function (_Feature2) { + _inheritsLoose(Corridor, _Feature2); + + function Corridor(startX, startY, endX, endY) { + var _this12; + + _this12 = _Feature2.call(this) || this; + _this12._startX = startX; + _this12._startY = startY; + _this12._endX = endX; + _this12._endY = endY; + _this12._endsWithAWall = true; + return _this12; + } + + Corridor.createRandomAt = function createRandomAt(x, y, dx, dy, options) { + var min = options.corridorLength[0]; + var max = options.corridorLength[1]; + var length = RNG$1.getUniformInt(min, max); + return new this(x, y, x + dx * length, y + dy * length); + }; + + var _proto24 = Corridor.prototype; + + _proto24.debug = function debug() { + console.log("corridor", this._startX, this._startY, this._endX, this._endY); + }; + + _proto24.isValid = function isValid(isWallCallback, canBeDugCallback) { + var sx = this._startX; + var sy = this._startY; + var dx = this._endX - sx; + var dy = this._endY - sy; + var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); + + if (dx) { + dx = dx / Math.abs(dx); + } + + if (dy) { + dy = dy / Math.abs(dy); + } + + var nx = dy; + var ny = -dx; + var ok = true; + + for (var i = 0; i < length; i++) { + var x = sx + i * dx; + var y = sy + i * dy; + + if (!canBeDugCallback(x, y)) { + ok = false; + } + + if (!isWallCallback(x + nx, y + ny)) { + ok = false; + } + + if (!isWallCallback(x - nx, y - ny)) { + ok = false; + } + + if (!ok) { + length = i; + this._endX = x - dx; + this._endY = y - dy; + break; + } + } + /** + * If the length degenerated, this corridor might be invalid + */ + + /* not supported */ + + + if (length == 0) { + return false; + } + /* length 1 allowed only if the next space is empty */ + + + if (length == 1 && isWallCallback(this._endX + dx, this._endY + dy)) { + return false; + } + /** + * We do not want the corridor to crash into a corner of a room; + * if any of the ending corners is empty, the N+1th cell of this corridor must be empty too. + * + * Situation: + * #######1 + * .......? + * #######2 + * + * The corridor was dug from left to right. + * 1, 2 - problematic corners, ? = N+1th cell (not dug) + */ + + + var firstCornerBad = !isWallCallback(this._endX + dx + nx, this._endY + dy + ny); + var secondCornerBad = !isWallCallback(this._endX + dx - nx, this._endY + dy - ny); + this._endsWithAWall = isWallCallback(this._endX + dx, this._endY + dy); + + if ((firstCornerBad || secondCornerBad) && this._endsWithAWall) { + return false; + } + + return true; + }; + /** + * @param {function} digCallback Dig callback with a signature (x, y, value). Values: 0 = empty. + */ + + + _proto24.create = function create(digCallback) { + var sx = this._startX; + var sy = this._startY; + var dx = this._endX - sx; + var dy = this._endY - sy; + var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); + + if (dx) { + dx = dx / Math.abs(dx); + } + + if (dy) { + dy = dy / Math.abs(dy); + } + + for (var i = 0; i < length; i++) { + var x = sx + i * dx; + var y = sy + i * dy; + digCallback(x, y, 0); + } + + return true; + }; + + _proto24.createPriorityWalls = function createPriorityWalls(priorityWallCallback) { + if (!this._endsWithAWall) { + return; + } + + var sx = this._startX; + var sy = this._startY; + var dx = this._endX - sx; + var dy = this._endY - sy; + + if (dx) { + dx = dx / Math.abs(dx); + } + + if (dy) { + dy = dy / Math.abs(dy); + } + + var nx = dy; + var ny = -dx; + priorityWallCallback(this._endX + dx, this._endY + dy); + priorityWallCallback(this._endX + nx, this._endY + ny); + priorityWallCallback(this._endX - nx, this._endY - ny); + }; + + return Corridor; + }(Feature); + /** + * @class Dungeon generator which tries to fill the space evenly. Generates independent rooms and tries to connect them. + * @augments ROT.Map.Dungeon + */ + + + var Uniform = + /*#__PURE__*/ + function (_Dungeon) { + _inheritsLoose(Uniform, _Dungeon); + + function Uniform(width, height, options) { + var _this13; + + _this13 = _Dungeon.call(this, width, height) || this; + _this13._options = { + roomWidth: [3, 9], + roomHeight: [3, 5], + roomDugPercentage: 0.1, + timeLimit: 1000 + /* we stop after this much time has passed (msec) */ + + }; + Object.assign(_this13._options, options); + _this13._map = []; + _this13._dug = 0; + _this13._roomAttempts = 20; + /* new room is created N-times until is considered as impossible to generate */ + + _this13._corridorAttempts = 20; + /* corridors are tried N-times until the level is considered as impossible to connect */ + + _this13._connected = []; + /* list of already connected rooms */ + + _this13._unconnected = []; + /* list of remaining unconnected rooms */ + + _this13._digCallback = _this13._digCallback.bind(_assertThisInitialized(_assertThisInitialized(_this13))); + _this13._canBeDugCallback = _this13._canBeDugCallback.bind(_assertThisInitialized(_assertThisInitialized(_this13))); + _this13._isWallCallback = _this13._isWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this13))); + return _this13; + } + /** + * Create a map. If the time limit has been hit, returns null. + * @see ROT.Map#create + */ + + + var _proto25 = Uniform.prototype; + + _proto25.create = function create(callback) { + var t1 = Date.now(); + + while (1) { + var t2 = Date.now(); + + if (t2 - t1 > this._options.timeLimit) { + return null; + } + /* time limit! */ + + + this._map = this._fillMap(1); + this._dug = 0; + this._rooms = []; + this._unconnected = []; + + this._generateRooms(); + + if (this._rooms.length < 2) { + continue; + } + + if (this._generateCorridors()) { + break; + } + } + + if (callback) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + callback(i, j, this._map[i][j]); + } + } + } + + return this; + }; + /** + * Generates a suitable amount of rooms + */ + + + _proto25._generateRooms = function _generateRooms() { + var w = this._width - 2; + var h = this._height - 2; + var room; + + do { + room = this._generateRoom(); + + if (this._dug / (w * h) > this._options.roomDugPercentage) { + break; + } + /* achieved requested amount of free space */ + + } while (room); + /* either enough rooms, or not able to generate more of them :) */ + + }; + /** + * Try to generate one room + */ + + + _proto25._generateRoom = function _generateRoom() { + var count = 0; + + while (count < this._roomAttempts) { + count++; + var room = Room.createRandom(this._width, this._height, this._options); + + if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) { + continue; + } + + room.create(this._digCallback); + + this._rooms.push(room); + + return room; + } + /* no room was generated in a given number of attempts */ + + + return null; + }; + /** + * Generates connectors beween rooms + * @returns {bool} success Was this attempt successfull? + */ + + + _proto25._generateCorridors = function _generateCorridors() { + var cnt = 0; + + while (cnt < this._corridorAttempts) { + cnt++; + this._corridors = []; + /* dig rooms into a clear map */ + + this._map = this._fillMap(1); + + for (var i = 0; i < this._rooms.length; i++) { + var room = this._rooms[i]; + room.clearDoors(); + room.create(this._digCallback); + } + + this._unconnected = RNG$1.shuffle(this._rooms.slice()); + this._connected = []; + + if (this._unconnected.length) { + this._connected.push(this._unconnected.pop()); + } + /* first one is always connected */ + + + while (1) { + /* 1. pick random connected room */ + var connected = RNG$1.getItem(this._connected); + + if (!connected) { + break; + } + /* 2. find closest unconnected */ + + + var room1 = this._closestRoom(this._unconnected, connected); + + if (!room1) { + break; + } + /* 3. connect it to closest connected */ + + + var room2 = this._closestRoom(this._connected, room1); + + if (!room2) { + break; + } + + var ok = this._connectRooms(room1, room2); + + if (!ok) { + break; + } + /* stop connecting, re-shuffle */ + + + if (!this._unconnected.length) { + return true; + } + /* done; no rooms remain */ + + } + } + + return false; + }; + + /** + * For a given room, find the closest one from the list + */ + _proto25._closestRoom = function _closestRoom(rooms, room) { + var dist = Infinity; + var center = room.getCenter(); + var result = null; + + for (var i = 0; i < rooms.length; i++) { + var r = rooms[i]; + var c = r.getCenter(); + var dx = c[0] - center[0]; + var dy = c[1] - center[1]; + var d = dx * dx + dy * dy; + + if (d < dist) { + dist = d; + result = r; + } + } + + return result; + }; + + _proto25._connectRooms = function _connectRooms(room1, room2) { + /* + room1.debug(); + room2.debug(); + */ + var center1 = room1.getCenter(); + var center2 = room2.getCenter(); + var diffX = center2[0] - center1[0]; + var diffY = center2[1] - center1[1]; + var start; + var end; + var dirIndex1, dirIndex2, min, max, index; + + if (Math.abs(diffX) < Math.abs(diffY)) { + /* first try connecting north-south walls */ + dirIndex1 = diffY > 0 ? 2 : 0; + dirIndex2 = (dirIndex1 + 2) % 4; + min = room2.getLeft(); + max = room2.getRight(); + index = 0; + } else { + /* first try connecting east-west walls */ + dirIndex1 = diffX > 0 ? 1 : 3; + dirIndex2 = (dirIndex1 + 2) % 4; + min = room2.getTop(); + max = room2.getBottom(); + index = 1; + } + + start = this._placeInWall(room1, dirIndex1); + /* corridor will start here */ + + if (!start) { + return false; + } + + if (start[index] >= min && start[index] <= max) { + /* possible to connect with straight line (I-like) */ + end = start.slice(); + var value = 0; + + switch (dirIndex2) { + case 0: + value = room2.getTop() - 1; + break; + + case 1: + value = room2.getRight() + 1; + break; + + case 2: + value = room2.getBottom() + 1; + break; + + case 3: + value = room2.getLeft() - 1; + break; + } + + end[(index + 1) % 2] = value; + + this._digLine([start, end]); + } else if (start[index] < min - 1 || start[index] > max + 1) { + /* need to switch target wall (L-like) */ + var diff = start[index] - center2[index]; + var rotation = 0; + + switch (dirIndex2) { + case 0: + case 1: + rotation = diff < 0 ? 3 : 1; + break; + + case 2: + case 3: + rotation = diff < 0 ? 1 : 3; + break; + } + + dirIndex2 = (dirIndex2 + rotation) % 4; + end = this._placeInWall(room2, dirIndex2); + + if (!end) { + return false; + } + + var mid = [0, 0]; + mid[index] = start[index]; + var index2 = (index + 1) % 2; + mid[index2] = end[index2]; + + this._digLine([start, mid, end]); + } else { + /* use current wall pair, but adjust the line in the middle (S-like) */ + var _index4 = (index + 1) % 2; + + end = this._placeInWall(room2, dirIndex2); + + if (!end) { + return false; + } + + var _mid = Math.round((end[_index4] + start[_index4]) / 2); + + var mid1 = [0, 0]; + var mid2 = [0, 0]; + mid1[index] = start[index]; + mid1[_index4] = _mid; + mid2[index] = end[index]; + mid2[_index4] = _mid; + + this._digLine([start, mid1, mid2, end]); + } + + room1.addDoor(start[0], start[1]); + room2.addDoor(end[0], end[1]); + index = this._unconnected.indexOf(room1); + + if (index != -1) { + this._unconnected.splice(index, 1); + + this._connected.push(room1); + } + + index = this._unconnected.indexOf(room2); + + if (index != -1) { + this._unconnected.splice(index, 1); + + this._connected.push(room2); + } + + return true; + }; + + _proto25._placeInWall = function _placeInWall(room, dirIndex) { + var start = [0, 0]; + var dir = [0, 0]; + var length = 0; + + switch (dirIndex) { + case 0: + dir = [1, 0]; + start = [room.getLeft(), room.getTop() - 1]; + length = room.getRight() - room.getLeft() + 1; + break; + + case 1: + dir = [0, 1]; + start = [room.getRight() + 1, room.getTop()]; + length = room.getBottom() - room.getTop() + 1; + break; + + case 2: + dir = [1, 0]; + start = [room.getLeft(), room.getBottom() + 1]; + length = room.getRight() - room.getLeft() + 1; + break; + + case 3: + dir = [0, 1]; + start = [room.getLeft() - 1, room.getTop()]; + length = room.getBottom() - room.getTop() + 1; + break; + } + + var avail = []; + var lastBadIndex = -2; + + for (var i = 0; i < length; i++) { + var x = start[0] + i * dir[0]; + var y = start[1] + i * dir[1]; + avail.push(null); + var isWall = this._map[x][y] == 1; + + if (isWall) { + if (lastBadIndex != i - 1) { + avail[i] = [x, y]; + } + } else { + lastBadIndex = i; + + if (i) { + avail[i - 1] = null; + } + } + } + + for (var _i3 = avail.length - 1; _i3 >= 0; _i3--) { + if (!avail[_i3]) { + avail.splice(_i3, 1); + } + } + + return avail.length ? RNG$1.getItem(avail) : null; + }; + /** + * Dig a polyline. + */ + + + _proto25._digLine = function _digLine(points) { + for (var i = 1; i < points.length; i++) { + var start = points[i - 1]; + var end = points[i]; + var corridor = new Corridor(start[0], start[1], end[0], end[1]); + corridor.create(this._digCallback); + + this._corridors.push(corridor); + } + }; + + _proto25._digCallback = function _digCallback(x, y, value) { + this._map[x][y] = value; + + if (value == 0) { + this._dug++; + } + }; + + _proto25._isWallCallback = function _isWallCallback(x, y) { + if (x < 0 || y < 0 || x >= this._width || y >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + _proto25._canBeDugCallback = function _canBeDugCallback(x, y) { + if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + return Uniform; + }(Dungeon); + /** + * @class Cellular automaton map generator + * @augments ROT.Map + * @param {int} [width=ROT.DEFAULT_WIDTH] + * @param {int} [height=ROT.DEFAULT_HEIGHT] + * @param {object} [options] Options + * @param {int[]} [options.born] List of neighbor counts for a new cell to be born in empty space + * @param {int[]} [options.survive] List of neighbor counts for an existing cell to survive + * @param {int} [options.topology] Topology 4 or 6 or 8 + */ + + + var Cellular = + /*#__PURE__*/ + function (_Map3) { + _inheritsLoose(Cellular, _Map3); + + function Cellular(width, height, options) { + var _this14; + + if (options === void 0) { + options = {}; + } + + _this14 = _Map3.call(this, width, height) || this; + _this14._options = { + born: [5, 6, 7, 8], + survive: [4, 5, 6, 7, 8], + topology: 8 + }; + + _this14.setOptions(options); + + _this14._dirs = DIRS[_this14._options.topology]; + _this14._map = _this14._fillMap(0); + return _this14; + } + /** + * Fill the map with random values + * @param {float} probability Probability for a cell to become alive; 0 = all empty, 1 = all full + */ + + + var _proto26 = Cellular.prototype; + + _proto26.randomize = function randomize(probability) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + this._map[i][j] = RNG$1.getUniform() < probability ? 1 : 0; + } + } + + return this; + }; + /** + * Change options. + * @see ROT.Map.Cellular + */ + + + _proto26.setOptions = function setOptions(options) { + Object.assign(this._options, options); + }; + + _proto26.set = function set(x, y, value) { + this._map[x][y] = value; + }; + + _proto26.create = function create(callback) { + var newMap = this._fillMap(0); + + var born = this._options.born; + var survive = this._options.survive; + + for (var j = 0; j < this._height; j++) { + var widthStep = 1; + var widthStart = 0; + + if (this._options.topology == 6) { + widthStep = 2; + widthStart = j % 2; + } + + for (var i = widthStart; i < this._width; i += widthStep) { + var cur = this._map[i][j]; + + var ncount = this._getNeighbors(i, j); + + if (cur && survive.indexOf(ncount) != -1) { + /* survive */ + newMap[i][j] = 1; + } else if (!cur && born.indexOf(ncount) != -1) { + /* born */ + newMap[i][j] = 1; + } + } + } + + this._map = newMap; + callback && this._serviceCallback(callback); + }; + + _proto26._serviceCallback = function _serviceCallback(callback) { + for (var j = 0; j < this._height; j++) { + var widthStep = 1; + var widthStart = 0; + + if (this._options.topology == 6) { + widthStep = 2; + widthStart = j % 2; + } + + for (var i = widthStart; i < this._width; i += widthStep) { + callback(i, j, this._map[i][j]); + } + } + }; + /** + * Get neighbor count at [i,j] in this._map + */ + + + _proto26._getNeighbors = function _getNeighbors(cx, cy) { + var result = 0; + + for (var i = 0; i < this._dirs.length; i++) { + var dir = this._dirs[i]; + var x = cx + dir[0]; + var y = cy + dir[1]; + + if (x < 0 || x >= this._width || y < 0 || y >= this._height) { + continue; + } + + result += this._map[x][y] == 1 ? 1 : 0; + } + + return result; + }; + /** + * Make sure every non-wall space is accessible. + * @param {function} callback to call to display map when do + * @param {int} value to consider empty space - defaults to 0 + * @param {function} callback to call when a new connection is made + */ + + + _proto26.connect = function connect(callback, value, connectionCallback) { + if (!value) value = 0; + var allFreeSpace = []; + var notConnected = {}; // find all free space + + var widthStep = 1; + var widthStarts = [0, 0]; + + if (this._options.topology == 6) { + widthStep = 2; + widthStarts = [0, 1]; + } + + for (var y = 0; y < this._height; y++) { + for (var x = widthStarts[y % 2]; x < this._width; x += widthStep) { + if (this._freeSpace(x, y, value)) { + var p = [x, y]; + notConnected[this._pointKey(p)] = p; + allFreeSpace.push([x, y]); + } + } + } + + var start = allFreeSpace[RNG$1.getUniformInt(0, allFreeSpace.length - 1)]; + + var key = this._pointKey(start); + + var connected = {}; + connected[key] = start; + delete notConnected[key]; // find what's connected to the starting point + + this._findConnected(connected, notConnected, [start], false, value); + + while (Object.keys(notConnected).length > 0) { + // find two points from notConnected to connected + var _p = this._getFromTo(connected, notConnected); + + var from = _p[0]; // notConnected + + var to = _p[1]; // connected + // find everything connected to the starting point + + var local = {}; + local[this._pointKey(from)] = from; + + this._findConnected(local, notConnected, [from], true, value); // connect to a connected cell + + + var tunnelFn = this._options.topology == 6 ? this._tunnelToConnected6 : this._tunnelToConnected; + tunnelFn.call(this, to, from, connected, notConnected, value, connectionCallback); // now all of local is connected + + for (var k in local) { + var pp = local[k]; + this._map[pp[0]][pp[1]] = value; + connected[k] = pp; + delete notConnected[k]; + } + } + + callback && this._serviceCallback(callback); + }; + /** + * Find random points to connect. Search for the closest point in the larger space. + * This is to minimize the length of the passage while maintaining good performance. + */ + + + _proto26._getFromTo = function _getFromTo(connected, notConnected) { + var from = [0, 0], + to = [0, 0], + d; + var connectedKeys = Object.keys(connected); + var notConnectedKeys = Object.keys(notConnected); + + for (var i = 0; i < 5; i++) { + if (connectedKeys.length < notConnectedKeys.length) { + var keys = connectedKeys; + to = connected[keys[RNG$1.getUniformInt(0, keys.length - 1)]]; + from = this._getClosest(to, notConnected); + } else { + var _keys = notConnectedKeys; + from = notConnected[_keys[RNG$1.getUniformInt(0, _keys.length - 1)]]; + to = this._getClosest(from, connected); + } + + d = (from[0] - to[0]) * (from[0] - to[0]) + (from[1] - to[1]) * (from[1] - to[1]); + + if (d < 64) { + break; + } + } // console.log(">>> connected=" + to + " notConnected=" + from + " dist=" + d); + + + return [from, to]; + }; + + _proto26._getClosest = function _getClosest(point, space) { + var minPoint = null; + var minDist = null; + + for (var k in space) { + var p = space[k]; + var d = (p[0] - point[0]) * (p[0] - point[0]) + (p[1] - point[1]) * (p[1] - point[1]); + + if (minDist == null || d < minDist) { + minDist = d; + minPoint = p; + } + } + + return minPoint; + }; + + _proto26._findConnected = function _findConnected(connected, notConnected, stack, keepNotConnected, value) { + while (stack.length > 0) { + var p = stack.splice(0, 1)[0]; + var tests = void 0; + + if (this._options.topology == 6) { + tests = [[p[0] + 2, p[1]], [p[0] + 1, p[1] - 1], [p[0] - 1, p[1] - 1], [p[0] - 2, p[1]], [p[0] - 1, p[1] + 1], [p[0] + 1, p[1] + 1]]; + } else { + tests = [[p[0] + 1, p[1]], [p[0] - 1, p[1]], [p[0], p[1] + 1], [p[0], p[1] - 1]]; + } + + for (var i = 0; i < tests.length; i++) { + var key = this._pointKey(tests[i]); + + if (connected[key] == null && this._freeSpace(tests[i][0], tests[i][1], value)) { + connected[key] = tests[i]; + + if (!keepNotConnected) { + delete notConnected[key]; + } + + stack.push(tests[i]); + } + } + } + }; + + _proto26._tunnelToConnected = function _tunnelToConnected(to, from, connected, notConnected, value, connectionCallback) { + var a, b; + + if (from[0] < to[0]) { + a = from; + b = to; + } else { + a = to; + b = from; + } + + for (var xx = a[0]; xx <= b[0]; xx++) { + this._map[xx][a[1]] = value; + var p = [xx, a[1]]; + + var pkey = this._pointKey(p); + + connected[pkey] = p; + delete notConnected[pkey]; + } + + if (connectionCallback && a[0] < b[0]) { + connectionCallback(a, [b[0], a[1]]); + } // x is now fixed + + + var x = b[0]; + + if (from[1] < to[1]) { + a = from; + b = to; + } else { + a = to; + b = from; + } + + for (var yy = a[1]; yy < b[1]; yy++) { + this._map[x][yy] = value; + var _p2 = [x, yy]; + + var _pkey = this._pointKey(_p2); + + connected[_pkey] = _p2; + delete notConnected[_pkey]; + } + + if (connectionCallback && a[1] < b[1]) { + connectionCallback([b[0], a[1]], [b[0], b[1]]); + } + }; + + _proto26._tunnelToConnected6 = function _tunnelToConnected6(to, from, connected, notConnected, value, connectionCallback) { + var a, b; + + if (from[0] < to[0]) { + a = from; + b = to; + } else { + a = to; + b = from; + } // tunnel diagonally until horizontally level + + + var xx = a[0]; + var yy = a[1]; + + while (!(xx == b[0] && yy == b[1])) { + var stepWidth = 2; + + if (yy < b[1]) { + yy++; + stepWidth = 1; + } else if (yy > b[1]) { + yy--; + stepWidth = 1; + } + + if (xx < b[0]) { + xx += stepWidth; + } else if (xx > b[0]) { + xx -= stepWidth; + } else if (b[1] % 2) { + // Won't step outside map if destination on is map's right edge + xx -= stepWidth; + } else { + // ditto for left edge + xx += stepWidth; + } + + this._map[xx][yy] = value; + var p = [xx, yy]; + + var pkey = this._pointKey(p); + + connected[pkey] = p; + delete notConnected[pkey]; + } + + if (connectionCallback) { + connectionCallback(from, to); + } + }; + + _proto26._freeSpace = function _freeSpace(x, y, value) { + return x >= 0 && x < this._width && y >= 0 && y < this._height && this._map[x][y] == value; + }; + + _proto26._pointKey = function _pointKey(p) { + return p[0] + "." + p[1]; + }; + + return Cellular; + }(Map); + + var FEATURES = { + "room": Room, + "corridor": Corridor + }; + /** + * Random dungeon generator using human-like digging patterns. + * Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at + * http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm. + */ + + var Digger = + /*#__PURE__*/ + function (_Dungeon2) { + _inheritsLoose(Digger, _Dungeon2); + + function Digger(width, height, options) { + var _this15; + + if (options === void 0) { + options = {}; + } + + _this15 = _Dungeon2.call(this, width, height) || this; + _this15._options = Object.assign({ + roomWidth: [3, 9], + roomHeight: [3, 5], + corridorLength: [3, 10], + dugPercentage: 0.2, + timeLimit: 1000 + /* we stop after this much time has passed (msec) */ + + }, options); + _this15._features = { + "room": 4, + "corridor": 4 + }; + _this15._map = []; + _this15._featureAttempts = 20; + /* how many times do we try to create a feature on a suitable wall */ + + _this15._walls = {}; + /* these are available for digging */ + + _this15._dug = 0; + _this15._digCallback = _this15._digCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + _this15._canBeDugCallback = _this15._canBeDugCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + _this15._isWallCallback = _this15._isWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + _this15._priorityWallCallback = _this15._priorityWallCallback.bind(_assertThisInitialized(_assertThisInitialized(_this15))); + return _this15; + } + + var _proto27 = Digger.prototype; + + _proto27.create = function create(callback) { + this._rooms = []; + this._corridors = []; + this._map = this._fillMap(1); + this._walls = {}; + this._dug = 0; + var area = (this._width - 2) * (this._height - 2); + + this._firstRoom(); + + var t1 = Date.now(); + var priorityWalls; + + do { + priorityWalls = 0; + var t2 = Date.now(); + + if (t2 - t1 > this._options.timeLimit) { + break; + } + /* find a good wall */ + + + var wall = this._findWall(); + + if (!wall) { + break; + } + /* no more walls */ + + + var parts = wall.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + + var dir = this._getDiggingDirection(x, y); + + if (!dir) { + continue; + } + /* this wall is not suitable */ + // console.log("wall", x, y); + + /* try adding a feature */ + + + var featureAttempts = 0; + + do { + featureAttempts++; + + if (this._tryFeature(x, y, dir[0], dir[1])) { + /* feature added */ + //if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */ + this._removeSurroundingWalls(x, y); + + this._removeSurroundingWalls(x - dir[0], y - dir[1]); + + break; + } + } while (featureAttempts < this._featureAttempts); + + for (var id in this._walls) { + if (this._walls[id] > 1) { + priorityWalls++; + } + } + } while (this._dug / area < this._options.dugPercentage || priorityWalls); + /* fixme number of priority walls */ + + + this._addDoors(); + + if (callback) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + callback(i, j, this._map[i][j]); + } + } + } + + this._walls = {}; + this._map = []; + return this; + }; + + _proto27._digCallback = function _digCallback(x, y, value) { + if (value == 0 || value == 2) { + /* empty */ + this._map[x][y] = 0; + this._dug++; + } else { + /* wall */ + this._walls[x + "," + y] = 1; + } + }; + + _proto27._isWallCallback = function _isWallCallback(x, y) { + if (x < 0 || y < 0 || x >= this._width || y >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + _proto27._canBeDugCallback = function _canBeDugCallback(x, y) { + if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) { + return false; + } + + return this._map[x][y] == 1; + }; + + _proto27._priorityWallCallback = function _priorityWallCallback(x, y) { + this._walls[x + "," + y] = 2; + }; + + _proto27._firstRoom = function _firstRoom() { + var cx = Math.floor(this._width / 2); + var cy = Math.floor(this._height / 2); + var room = Room.createRandomCenter(cx, cy, this._options); + + this._rooms.push(room); + + room.create(this._digCallback); + }; + /** + * Get a suitable wall + */ + + + _proto27._findWall = function _findWall() { + var prio1 = []; + var prio2 = []; + + for (var _id2 in this._walls) { + var prio = this._walls[_id2]; + + if (prio == 2) { + prio2.push(_id2); + } else { + prio1.push(_id2); + } + } + + var arr = prio2.length ? prio2 : prio1; + + if (!arr.length) { + return null; + } + /* no walls :/ */ + + + var id = RNG$1.getItem(arr.sort()); // sort to make the order deterministic + + delete this._walls[id]; + return id; + }; + /** + * Tries adding a feature + * @returns {bool} was this a successful try? + */ + + + _proto27._tryFeature = function _tryFeature(x, y, dx, dy) { + var featureName = RNG$1.getWeightedValue(this._features); + var ctor = FEATURES[featureName]; + var feature = ctor.createRandomAt(x, y, dx, dy, this._options); + + if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) { + // console.log("not valid"); + // feature.debug(); + return false; + } + + feature.create(this._digCallback); // feature.debug(); + + if (feature instanceof Room) { + this._rooms.push(feature); + } + + if (feature instanceof Corridor) { + feature.createPriorityWalls(this._priorityWallCallback); + + this._corridors.push(feature); + } + + return true; + }; + + _proto27._removeSurroundingWalls = function _removeSurroundingWalls(cx, cy) { + var deltas = DIRS[4]; + + for (var i = 0; i < deltas.length; i++) { + var delta = deltas[i]; + var x = cx + delta[0]; + var y = cy + delta[1]; + delete this._walls[x + "," + y]; + x = cx + 2 * delta[0]; + y = cy + 2 * delta[1]; + delete this._walls[x + "," + y]; + } + }; + /** + * Returns vector in "digging" direction, or false, if this does not exist (or is not unique) + */ + + + _proto27._getDiggingDirection = function _getDiggingDirection(cx, cy) { + if (cx <= 0 || cy <= 0 || cx >= this._width - 1 || cy >= this._height - 1) { + return null; + } + + var result = null; + var deltas = DIRS[4]; + + for (var i = 0; i < deltas.length; i++) { + var delta = deltas[i]; + var x = cx + delta[0]; + var y = cy + delta[1]; + + if (!this._map[x][y]) { + /* there already is another empty neighbor! */ + if (result) { + return null; + } + + result = delta; + } + } + /* no empty neighbor */ + + + if (!result) { + return null; + } + + return [-result[0], -result[1]]; + }; + /** + * Find empty spaces surrounding rooms, and apply doors. + */ + + + _proto27._addDoors = function _addDoors() { + var data = this._map; + + function isWallCallback(x, y) { + return data[x][y] == 1; + } + + for (var i = 0; i < this._rooms.length; i++) { + var room = this._rooms[i]; + room.clearDoors(); + room.addDoors(isWallCallback); + } + }; + + return Digger; + }(Dungeon); + /** + * Join lists with "i" and "i+1" + */ + + + function addToList(i, L, R) { + R[L[i + 1]] = R[i]; + L[R[i]] = L[i + 1]; + R[i] = i + 1; + L[i + 1] = i; + } + /** + * Remove "i" from its list + */ + + + function removeFromList(i, L, R) { + R[L[i]] = R[i]; + L[R[i]] = L[i]; + R[i] = i; + L[i] = i; + } + /** + * Maze generator - Eller's algorithm + * See http://homepages.cwi.nl/~tromp/maze.html for explanation + */ + + + var EllerMaze = + /*#__PURE__*/ + function (_Map4) { + _inheritsLoose(EllerMaze, _Map4); + + function EllerMaze() { + return _Map4.apply(this, arguments) || this; + } + + var _proto28 = EllerMaze.prototype; + + _proto28.create = function create(callback) { + var map = this._fillMap(1); + + var w = Math.ceil((this._width - 2) / 2); + var rand = 9 / 24; + var L = []; + var R = []; + + for (var i = 0; i < w; i++) { + L.push(i); + R.push(i); + } + + L.push(w - 1); + /* fake stop-block at the right side */ + + var j; + + for (j = 1; j + 3 < this._height; j += 2) { + /* one row */ + for (var _i4 = 0; _i4 < w; _i4++) { + /* cell coords (will be always empty) */ + var x = 2 * _i4 + 1; + var y = j; + map[x][y] = 0; + /* right connection */ + + if (_i4 != L[_i4 + 1] && RNG$1.getUniform() > rand) { + addToList(_i4, L, R); + map[x + 1][y] = 0; + } + /* bottom connection */ + + + if (_i4 != L[_i4] && RNG$1.getUniform() > rand) { + /* remove connection */ + removeFromList(_i4, L, R); + } else { + /* create connection */ + map[x][y + 1] = 0; + } + } + } + /* last row */ + + + for (var _i5 = 0; _i5 < w; _i5++) { + /* cell coords (will be always empty) */ + var _x2 = 2 * _i5 + 1; + + var _y2 = j; + map[_x2][_y2] = 0; + /* right connection */ + + if (_i5 != L[_i5 + 1] && (_i5 == L[_i5] || RNG$1.getUniform() > rand)) { + /* dig right also if the cell is separated, so it gets connected to the rest of maze */ + addToList(_i5, L, R); + map[_x2 + 1][_y2] = 0; + } + + removeFromList(_i5, L, R); + } + + for (var _i6 = 0; _i6 < this._width; _i6++) { + for (var _j = 0; _j < this._height; _j++) { + callback(_i6, _j, map[_i6][_j]); + } + } + + return this; + }; + + return EllerMaze; + }(Map); + /** + * @class Recursively divided maze, http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method + * @augments ROT.Map + */ + + + var DividedMaze = + /*#__PURE__*/ + function (_Map5) { + _inheritsLoose(DividedMaze, _Map5); + + function DividedMaze() { + var _this16; + + _this16 = _Map5.apply(this, arguments) || this; + _this16._stack = []; + _this16._map = []; + return _this16; + } + + var _proto29 = DividedMaze.prototype; + + _proto29.create = function create(callback) { + var w = this._width; + var h = this._height; + this._map = []; + + for (var i = 0; i < w; i++) { + this._map.push([]); + + for (var j = 0; j < h; j++) { + var border = i == 0 || j == 0 || i + 1 == w || j + 1 == h; + + this._map[i].push(border ? 1 : 0); + } + } + + this._stack = [[1, 1, w - 2, h - 2]]; + + this._process(); + + for (var _i7 = 0; _i7 < w; _i7++) { + for (var _j2 = 0; _j2 < h; _j2++) { + callback(_i7, _j2, this._map[_i7][_j2]); + } + } + + this._map = []; + return this; + }; + + _proto29._process = function _process() { + while (this._stack.length) { + var room = this._stack.shift(); + /* [left, top, right, bottom] */ + + + this._partitionRoom(room); + } + }; + + _proto29._partitionRoom = function _partitionRoom(room) { + var availX = []; + var availY = []; + + for (var i = room[0] + 1; i < room[2]; i++) { + var top = this._map[i][room[1] - 1]; + var bottom = this._map[i][room[3] + 1]; + + if (top && bottom && !(i % 2)) { + availX.push(i); + } + } + + for (var j = room[1] + 1; j < room[3]; j++) { + var left = this._map[room[0] - 1][j]; + var right = this._map[room[2] + 1][j]; + + if (left && right && !(j % 2)) { + availY.push(j); + } + } + + if (!availX.length || !availY.length) { + return; + } + + var x = RNG$1.getItem(availX); + var y = RNG$1.getItem(availY); + this._map[x][y] = 1; + var walls = []; + var w = []; + walls.push(w); + /* left part */ + + for (var _i8 = room[0]; _i8 < x; _i8++) { + this._map[_i8][y] = 1; + w.push([_i8, y]); + } + + w = []; + walls.push(w); + /* right part */ + + for (var _i9 = x + 1; _i9 <= room[2]; _i9++) { + this._map[_i9][y] = 1; + w.push([_i9, y]); + } + + w = []; + walls.push(w); + /* top part */ + + for (var _j3 = room[1]; _j3 < y; _j3++) { + this._map[x][_j3] = 1; + w.push([x, _j3]); + } + + w = []; + walls.push(w); + /* bottom part */ + + for (var _j4 = y + 1; _j4 <= room[3]; _j4++) { + this._map[x][_j4] = 1; + w.push([x, _j4]); + } + + var solid = RNG$1.getItem(walls); + + for (var _i10 = 0; _i10 < walls.length; _i10++) { + var _w = walls[_i10]; + + if (_w == solid) { + continue; + } + + var hole = RNG$1.getItem(_w); + this._map[hole[0]][hole[1]] = 0; + } + + this._stack.push([room[0], room[1], x - 1, y - 1]); + /* left top */ + + + this._stack.push([x + 1, room[1], room[2], y - 1]); + /* right top */ + + + this._stack.push([room[0], y + 1, x - 1, room[3]]); + /* left bottom */ + + + this._stack.push([x + 1, y + 1, room[2], room[3]]); + /* right bottom */ + + }; + + return DividedMaze; + }(Map); + /** + * Icey's Maze generator + * See http://www.roguebasin.roguelikedevelopment.org/index.php?title=Simple_maze for explanation + */ + + + var IceyMaze = + /*#__PURE__*/ + function (_Map6) { + _inheritsLoose(IceyMaze, _Map6); + + function IceyMaze(width, height, regularity) { + var _this17; + + if (regularity === void 0) { + regularity = 0; + } + + _this17 = _Map6.call(this, width, height) || this; + _this17._regularity = regularity; + _this17._map = []; + return _this17; + } + + var _proto30 = IceyMaze.prototype; + + _proto30.create = function create(callback) { + var width = this._width; + var height = this._height; + + var map = this._fillMap(1); + + width -= width % 2 ? 1 : 2; + height -= height % 2 ? 1 : 2; + var cx = 0; + var cy = 0; + var nx = 0; + var ny = 0; + var done = 0; + var blocked = false; + var dirs = [[0, 0], [0, 0], [0, 0], [0, 0]]; + + do { + cx = 1 + 2 * Math.floor(RNG$1.getUniform() * (width - 1) / 2); + cy = 1 + 2 * Math.floor(RNG$1.getUniform() * (height - 1) / 2); + + if (!done) { + map[cx][cy] = 0; + } + + if (!map[cx][cy]) { + this._randomize(dirs); + + do { + if (Math.floor(RNG$1.getUniform() * (this._regularity + 1)) == 0) { + this._randomize(dirs); + } + + blocked = true; + + for (var i = 0; i < 4; i++) { + nx = cx + dirs[i][0] * 2; + ny = cy + dirs[i][1] * 2; + + if (this._isFree(map, nx, ny, width, height)) { + map[nx][ny] = 0; + map[cx + dirs[i][0]][cy + dirs[i][1]] = 0; + cx = nx; + cy = ny; + blocked = false; + done++; + break; + } + } + } while (!blocked); + } + } while (done + 1 < width * height / 4); + + for (var _i11 = 0; _i11 < this._width; _i11++) { + for (var j = 0; j < this._height; j++) { + callback(_i11, j, map[_i11][j]); + } + } + + this._map = []; + return this; + }; + + _proto30._randomize = function _randomize(dirs) { + for (var i = 0; i < 4; i++) { + dirs[i][0] = 0; + dirs[i][1] = 0; + } + + switch (Math.floor(RNG$1.getUniform() * 4)) { + case 0: + dirs[0][0] = -1; + dirs[1][0] = 1; + dirs[2][1] = -1; + dirs[3][1] = 1; + break; + + case 1: + dirs[3][0] = -1; + dirs[2][0] = 1; + dirs[1][1] = -1; + dirs[0][1] = 1; + break; + + case 2: + dirs[2][0] = -1; + dirs[3][0] = 1; + dirs[0][1] = -1; + dirs[1][1] = 1; + break; + + case 3: + dirs[1][0] = -1; + dirs[0][0] = 1; + dirs[3][1] = -1; + dirs[2][1] = 1; + break; + } + }; + + _proto30._isFree = function _isFree(map, x, y, width, height) { + if (x < 1 || y < 1 || x >= width || y >= height) { + return false; + } + + return map[x][y]; + }; + + return IceyMaze; + }(Map); + /** + * Dungeon generator which uses the "orginal" Rogue dungeon generation algorithm. See http://kuoi.com/~kamikaze/GameDesign/art07_rogue_dungeon.php + * @author hyakugei + */ + + + var Rogue = + /*#__PURE__*/ + function (_Map7) { + _inheritsLoose(Rogue, _Map7); + + function Rogue(width, height, options) { + var _this18; + + _this18 = _Map7.call(this, width, height) || this; + _this18.map = []; + _this18.rooms = []; + _this18.connectedCells = []; + options = Object.assign({ + cellWidth: 3, + cellHeight: 3 // ie. as an array with min-max values for each direction.... + + }, options); + /* + Set the room sizes according to the over-all width of the map, + and the cell sizes. + */ + + if (!options.hasOwnProperty("roomWidth")) { + options["roomWidth"] = _this18._calculateRoomSize(_this18._width, options["cellWidth"]); + } + + if (!options.hasOwnProperty("roomHeight")) { + options["roomHeight"] = _this18._calculateRoomSize(_this18._height, options["cellHeight"]); + } + + _this18._options = options; + return _this18; + } + + var _proto31 = Rogue.prototype; + + _proto31.create = function create(callback) { + this.map = this._fillMap(1); + this.rooms = []; + this.connectedCells = []; + + this._initRooms(); + + this._connectRooms(); + + this._connectUnconnectedRooms(); + + this._createRandomRoomConnections(); + + this._createRooms(); + + this._createCorridors(); + + if (callback) { + for (var i = 0; i < this._width; i++) { + for (var j = 0; j < this._height; j++) { + callback(i, j, this.map[i][j]); + } + } + } + + return this; + }; + + _proto31._calculateRoomSize = function _calculateRoomSize(size, cell) { + var max = Math.floor(size / cell * 0.8); + var min = Math.floor(size / cell * 0.25); + + if (min < 2) { + min = 2; + } + + if (max < 2) { + max = 2; + } + + return [min, max]; + }; + + _proto31._initRooms = function _initRooms() { + // create rooms array. This is the "grid" list from the algo. + for (var i = 0; i < this._options.cellWidth; i++) { + this.rooms.push([]); + + for (var j = 0; j < this._options.cellHeight; j++) { + this.rooms[i].push({ + "x": 0, + "y": 0, + "width": 0, + "height": 0, + "connections": [], + "cellx": i, + "celly": j + }); + } + } + }; + + _proto31._connectRooms = function _connectRooms() { + //pick random starting grid + var cgx = RNG$1.getUniformInt(0, this._options.cellWidth - 1); + var cgy = RNG$1.getUniformInt(0, this._options.cellHeight - 1); + var idx; + var ncgx; + var ncgy; + var found = false; + var room; + var otherRoom; + var dirToCheck; // find unconnected neighbour cells + + do { + //dirToCheck = [0, 1, 2, 3, 4, 5, 6, 7]; + dirToCheck = [0, 2, 4, 6]; + dirToCheck = RNG$1.shuffle(dirToCheck); + + do { + found = false; + idx = dirToCheck.pop(); + ncgx = cgx + DIRS[8][idx][0]; + ncgy = cgy + DIRS[8][idx][1]; + + if (ncgx < 0 || ncgx >= this._options.cellWidth) { + continue; + } + + if (ncgy < 0 || ncgy >= this._options.cellHeight) { + continue; + } + + room = this.rooms[cgx][cgy]; + + if (room["connections"].length > 0) { + // as long as this room doesn't already coonect to me, we are ok with it. + if (room["connections"][0][0] == ncgx && room["connections"][0][1] == ncgy) { + break; + } + } + + otherRoom = this.rooms[ncgx][ncgy]; + + if (otherRoom["connections"].length == 0) { + otherRoom["connections"].push([cgx, cgy]); + this.connectedCells.push([ncgx, ncgy]); + cgx = ncgx; + cgy = ncgy; + found = true; + } + } while (dirToCheck.length > 0 && found == false); + } while (dirToCheck.length > 0); + }; + + _proto31._connectUnconnectedRooms = function _connectUnconnectedRooms() { + //While there are unconnected rooms, try to connect them to a random connected neighbor + //(if a room has no connected neighbors yet, just keep cycling, you'll fill out to it eventually). + var cw = this._options.cellWidth; + var ch = this._options.cellHeight; + this.connectedCells = RNG$1.shuffle(this.connectedCells); + var room; + var otherRoom; + var validRoom; + + for (var i = 0; i < this._options.cellWidth; i++) { + for (var j = 0; j < this._options.cellHeight; j++) { + room = this.rooms[i][j]; + + if (room["connections"].length == 0) { + var directions = [0, 2, 4, 6]; + directions = RNG$1.shuffle(directions); + validRoom = false; + + do { + var dirIdx = directions.pop(); + var newI = i + DIRS[8][dirIdx][0]; + var newJ = j + DIRS[8][dirIdx][1]; + + if (newI < 0 || newI >= cw || newJ < 0 || newJ >= ch) { + continue; + } + + otherRoom = this.rooms[newI][newJ]; + validRoom = true; + + if (otherRoom["connections"].length == 0) { + break; + } + + for (var k = 0; k < otherRoom["connections"].length; k++) { + if (otherRoom["connections"][k][0] == i && otherRoom["connections"][k][1] == j) { + validRoom = false; + break; + } + } + + if (validRoom) { + break; + } + } while (directions.length); + + if (validRoom) { + room["connections"].push([otherRoom["cellx"], otherRoom["celly"]]); + } else { + console.log("-- Unable to connect room."); + } + } + } + } + }; + + _proto31._createRandomRoomConnections = function _createRandomRoomConnections() {// Empty for now. + }; + + _proto31._createRooms = function _createRooms() { + var w = this._width; + var h = this._height; + var cw = this._options.cellWidth; + var ch = this._options.cellHeight; + var cwp = Math.floor(this._width / cw); + var chp = Math.floor(this._height / ch); + var roomw; + var roomh; + var roomWidth = this._options["roomWidth"]; + var roomHeight = this._options["roomHeight"]; + var sx; + var sy; + var otherRoom; + + for (var i = 0; i < cw; i++) { + for (var j = 0; j < ch; j++) { + sx = cwp * i; + sy = chp * j; + + if (sx == 0) { + sx = 1; + } + + if (sy == 0) { + sy = 1; + } + + roomw = RNG$1.getUniformInt(roomWidth[0], roomWidth[1]); + roomh = RNG$1.getUniformInt(roomHeight[0], roomHeight[1]); + + if (j > 0) { + otherRoom = this.rooms[i][j - 1]; + + while (sy - (otherRoom["y"] + otherRoom["height"]) < 3) { + sy++; + } + } + + if (i > 0) { + otherRoom = this.rooms[i - 1][j]; + + while (sx - (otherRoom["x"] + otherRoom["width"]) < 3) { + sx++; + } + } + + var sxOffset = Math.round(RNG$1.getUniformInt(0, cwp - roomw) / 2); + var syOffset = Math.round(RNG$1.getUniformInt(0, chp - roomh) / 2); + + while (sx + sxOffset + roomw >= w) { + if (sxOffset) { + sxOffset--; + } else { + roomw--; + } + } + + while (sy + syOffset + roomh >= h) { + if (syOffset) { + syOffset--; + } else { + roomh--; + } + } + + sx = sx + sxOffset; + sy = sy + syOffset; + this.rooms[i][j]["x"] = sx; + this.rooms[i][j]["y"] = sy; + this.rooms[i][j]["width"] = roomw; + this.rooms[i][j]["height"] = roomh; + + for (var ii = sx; ii < sx + roomw; ii++) { + for (var jj = sy; jj < sy + roomh; jj++) { + this.map[ii][jj] = 0; + } + } + } + } + }; + + _proto31._getWallPosition = function _getWallPosition(aRoom, aDirection) { + var rx; + var ry; + var door; + + if (aDirection == 1 || aDirection == 3) { + rx = RNG$1.getUniformInt(aRoom["x"] + 1, aRoom["x"] + aRoom["width"] - 2); + + if (aDirection == 1) { + ry = aRoom["y"] - 2; + door = ry + 1; + } else { + ry = aRoom["y"] + aRoom["height"] + 1; + door = ry - 1; + } + + this.map[rx][door] = 0; // i'm not setting a specific 'door' tile value right now, just empty space. + } else { + ry = RNG$1.getUniformInt(aRoom["y"] + 1, aRoom["y"] + aRoom["height"] - 2); + + if (aDirection == 2) { + rx = aRoom["x"] + aRoom["width"] + 1; + door = rx - 1; + } else { + rx = aRoom["x"] - 2; + door = rx + 1; + } + + this.map[door][ry] = 0; // i'm not setting a specific 'door' tile value right now, just empty space. + } + + return [rx, ry]; + }; + + _proto31._drawCorridor = function _drawCorridor(startPosition, endPosition) { + var xOffset = endPosition[0] - startPosition[0]; + var yOffset = endPosition[1] - startPosition[1]; + var xpos = startPosition[0]; + var ypos = startPosition[1]; + var tempDist; + var xDir; + var yDir; + var move; // 2 element array, element 0 is the direction, element 1 is the total value to move. + + var moves = []; // a list of 2 element arrays + + var xAbs = Math.abs(xOffset); + var yAbs = Math.abs(yOffset); + var percent = RNG$1.getUniform(); // used to split the move at different places along the long axis + + var firstHalf = percent; + var secondHalf = 1 - percent; + xDir = xOffset > 0 ? 2 : 6; + yDir = yOffset > 0 ? 4 : 0; + + if (xAbs < yAbs) { + // move firstHalf of the y offset + tempDist = Math.ceil(yAbs * firstHalf); + moves.push([yDir, tempDist]); // move all the x offset + + moves.push([xDir, xAbs]); // move sendHalf of the y offset + + tempDist = Math.floor(yAbs * secondHalf); + moves.push([yDir, tempDist]); + } else { + // move firstHalf of the x offset + tempDist = Math.ceil(xAbs * firstHalf); + moves.push([xDir, tempDist]); // move all the y offset + + moves.push([yDir, yAbs]); // move secondHalf of the x offset. + + tempDist = Math.floor(xAbs * secondHalf); + moves.push([xDir, tempDist]); + } + + this.map[xpos][ypos] = 0; + + while (moves.length > 0) { + move = moves.pop(); + + while (move[1] > 0) { + xpos += DIRS[8][move[0]][0]; + ypos += DIRS[8][move[0]][1]; + this.map[xpos][ypos] = 0; + move[1] = move[1] - 1; + } + } + }; + + _proto31._createCorridors = function _createCorridors() { + // Draw Corridors between connected rooms + var cw = this._options.cellWidth; + var ch = this._options.cellHeight; + var room; + var connection; + var otherRoom; + var wall; + var otherWall; + + for (var i = 0; i < cw; i++) { + for (var j = 0; j < ch; j++) { + room = this.rooms[i][j]; + + for (var k = 0; k < room["connections"].length; k++) { + connection = room["connections"][k]; + otherRoom = this.rooms[connection[0]][connection[1]]; // figure out what wall our corridor will start one. + // figure out what wall our corridor will end on. + + if (otherRoom["cellx"] > room["cellx"]) { + wall = 2; + otherWall = 4; + } else if (otherRoom["cellx"] < room["cellx"]) { + wall = 4; + otherWall = 2; + } else if (otherRoom["celly"] > room["celly"]) { + wall = 3; + otherWall = 1; + } else { + wall = 1; + otherWall = 3; + } + + this._drawCorridor(this._getWallPosition(room, wall), this._getWallPosition(otherRoom, otherWall)); + } + } + } + }; + + return Rogue; + }(Map); + + var index$2 = { + Arena: Arena, + Uniform: Uniform, + Cellular: Cellular, + Digger: Digger, + EllerMaze: EllerMaze, + DividedMaze: DividedMaze, + IceyMaze: IceyMaze, + Rogue: Rogue + }; + /** + * Base noise generator + */ + + var Noise = function Noise() {}; + + var F2 = 0.5 * (Math.sqrt(3) - 1); + var G2 = (3 - Math.sqrt(3)) / 6; + /** + * A simple 2d implementation of simplex noise by Ondrej Zara + * + * Based on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. + * Which is based on example code by Stefan Gustavson (stegu@itn.liu.se). + * With Optimisations by Peter Eastman (peastman@drizzle.stanford.edu). + * Better rank ordering method by Stefan Gustavson in 2012. + */ + + var Simplex = + /*#__PURE__*/ + function (_Noise) { + _inheritsLoose(Simplex, _Noise); + + /** + * @param gradients Random gradients + */ + function Simplex(gradients) { + var _this19; + + if (gradients === void 0) { + gradients = 256; + } + + _this19 = _Noise.call(this) || this; + _this19._gradients = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1]]; + var permutations = []; + + for (var i = 0; i < gradients; i++) { + permutations.push(i); + } + + permutations = RNG$1.shuffle(permutations); + _this19._perms = []; + _this19._indexes = []; + + for (var _i12 = 0; _i12 < 2 * gradients; _i12++) { + _this19._perms.push(permutations[_i12 % gradients]); + + _this19._indexes.push(_this19._perms[_i12] % _this19._gradients.length); + } + + return _this19; + } + + var _proto32 = Simplex.prototype; + + _proto32.get = function get(xin, yin) { + var perms = this._perms; + var indexes = this._indexes; + var count = perms.length / 2; + var n0 = 0, + n1 = 0, + n2 = 0, + gi; // Noise contributions from the three corners + // Skew the input space to determine which simplex cell we're in + + var s = (xin + yin) * F2; // Hairy factor for 2D + + var i = Math.floor(xin + s); + var j = Math.floor(yin + s); + var t = (i + j) * G2; + var X0 = i - t; // Unskew the cell origin back to (x,y) space + + var Y0 = j - t; + var x0 = xin - X0; // The x,y distances from the cell origin + + var y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. + // Determine which simplex we are in. + + var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords + + if (x0 > y0) { + i1 = 1; + j1 = 0; + } else { + // lower triangle, XY order: (0,0)->(1,0)->(1,1) + i1 = 0; + j1 = 1; + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + + + var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + + var y1 = y0 - j1 + G2; + var x2 = x0 - 1 + 2 * G2; // Offsets for last corner in (x,y) unskewed coords + + var y2 = y0 - 1 + 2 * G2; // Work out the hashed gradient indices of the three simplex corners + + var ii = mod(i, count); + var jj = mod(j, count); // Calculate the contribution from the three corners + + var t0 = 0.5 - x0 * x0 - y0 * y0; + + if (t0 >= 0) { + t0 *= t0; + gi = indexes[ii + perms[jj]]; + var grad = this._gradients[gi]; + n0 = t0 * t0 * (grad[0] * x0 + grad[1] * y0); + } + + var t1 = 0.5 - x1 * x1 - y1 * y1; + + if (t1 >= 0) { + t1 *= t1; + gi = indexes[ii + i1 + perms[jj + j1]]; + var _grad = this._gradients[gi]; + n1 = t1 * t1 * (_grad[0] * x1 + _grad[1] * y1); + } + + var t2 = 0.5 - x2 * x2 - y2 * y2; + + if (t2 >= 0) { + t2 *= t2; + gi = indexes[ii + 1 + perms[jj + 1]]; + var _grad2 = this._gradients[gi]; + n2 = t2 * t2 * (_grad2[0] * x2 + _grad2[1] * y2); + } // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + + + return 70 * (n0 + n1 + n2); + }; + + return Simplex; + }(Noise); + + var index$3 = { + Simplex: Simplex + }; + /** + * @class Abstract pathfinder + * @param {int} toX Target X coord + * @param {int} toY Target Y coord + * @param {function} passableCallback Callback to determine map passability + * @param {object} [options] + * @param {int} [options.topology=8] + */ + + var Path = + /*#__PURE__*/ + function () { + function Path(toX, toY, passableCallback, options) { + if (options === void 0) { + options = {}; + } + + this._toX = toX; + this._toY = toY; + this._passableCallback = passableCallback; + this._options = Object.assign({ + topology: 8 + }, options); + this._dirs = DIRS[this._options.topology]; + + if (this._options.topology == 8) { + /* reorder dirs for more aesthetic result (vertical/horizontal first) */ + this._dirs = [this._dirs[0], this._dirs[2], this._dirs[4], this._dirs[6], this._dirs[1], this._dirs[3], this._dirs[5], this._dirs[7]]; + } + } + + var _proto33 = Path.prototype; + + _proto33._getNeighbors = function _getNeighbors(cx, cy) { + var result = []; + + for (var i = 0; i < this._dirs.length; i++) { + var dir = this._dirs[i]; + var x = cx + dir[0]; + var y = cy + dir[1]; + + if (!this._passableCallback(x, y)) { + continue; + } + + result.push([x, y]); + } + + return result; + }; + + return Path; + }(); + /** + * @class Simplified Dijkstra's algorithm: all edges have a value of 1 + * @augments ROT.Path + * @see ROT.Path + */ + + + var Dijkstra = + /*#__PURE__*/ + function (_Path) { + _inheritsLoose(Dijkstra, _Path); + + function Dijkstra(toX, toY, passableCallback, options) { + var _this20; + + _this20 = _Path.call(this, toX, toY, passableCallback, options) || this; + _this20._computed = {}; + _this20._todo = []; + + _this20._add(toX, toY, null); + + return _this20; + } + /** + * Compute a path from a given point + * @see ROT.Path#compute + */ + + + var _proto34 = Dijkstra.prototype; + + _proto34.compute = function compute(fromX, fromY, callback) { + var key = fromX + "," + fromY; + + if (!(key in this._computed)) { + this._compute(fromX, fromY); + } + + if (!(key in this._computed)) { + return; + } + + var item = this._computed[key]; + + while (item) { + callback(item.x, item.y); + item = item.prev; + } + }; + /** + * Compute a non-cached value + */ + + + _proto34._compute = function _compute(fromX, fromY) { + while (this._todo.length) { + var item = this._todo.shift(); + + if (item.x == fromX && item.y == fromY) { + return; + } + + var neighbors = this._getNeighbors(item.x, item.y); + + for (var i = 0; i < neighbors.length; i++) { + var neighbor = neighbors[i]; + var x = neighbor[0]; + var y = neighbor[1]; + var id = x + "," + y; + + if (id in this._computed) { + continue; + } + /* already done */ + + + this._add(x, y, item); + } + } + }; + + _proto34._add = function _add(x, y, prev) { + var obj = { + x: x, + y: y, + prev: prev + }; + this._computed[x + "," + y] = obj; + + this._todo.push(obj); + }; + + return Dijkstra; + }(Path); + /** + * @class Simplified A* algorithm: all edges have a value of 1 + * @augments ROT.Path + * @see ROT.Path + */ + + + var AStar = + /*#__PURE__*/ + function (_Path2) { + _inheritsLoose(AStar, _Path2); + + function AStar(toX, toY, passableCallback, options) { + var _this21; + + if (options === void 0) { + options = {}; + } + + _this21 = _Path2.call(this, toX, toY, passableCallback, options) || this; + _this21._todo = []; + _this21._done = {}; + return _this21; + } + /** + * Compute a path from a given point + * @see ROT.Path#compute + */ + + + var _proto35 = AStar.prototype; + + _proto35.compute = function compute(fromX, fromY, callback) { + this._todo = []; + this._done = {}; + this._fromX = fromX; + this._fromY = fromY; + + this._add(this._toX, this._toY, null); + + while (this._todo.length) { + var _item = this._todo.shift(); + + var id = _item.x + "," + _item.y; + + if (id in this._done) { + continue; + } + + this._done[id] = _item; + + if (_item.x == fromX && _item.y == fromY) { + break; + } + + var neighbors = this._getNeighbors(_item.x, _item.y); + + for (var i = 0; i < neighbors.length; i++) { + var neighbor = neighbors[i]; + var x = neighbor[0]; + var y = neighbor[1]; + + var _id3 = x + "," + y; + + if (_id3 in this._done) { + continue; + } + + this._add(x, y, _item); + } + } + + var item = this._done[fromX + "," + fromY]; + + if (!item) { + return; + } + + while (item) { + callback(item.x, item.y); + item = item.prev; + } + }; + + _proto35._add = function _add(x, y, prev) { + var h = this._distance(x, y); + + var obj = { + x: x, + y: y, + prev: prev, + g: prev ? prev.g + 1 : 0, + h: h + }; + /* insert into priority queue */ + + var f = obj.g + obj.h; + + for (var i = 0; i < this._todo.length; i++) { + var item = this._todo[i]; + var itemF = item.g + item.h; + + if (f < itemF || f == itemF && h < item.h) { + this._todo.splice(i, 0, obj); + + return; + } + } + + this._todo.push(obj); + }; + + _proto35._distance = function _distance(x, y) { + switch (this._options.topology) { + case 4: + return Math.abs(x - this._fromX) + Math.abs(y - this._fromY); + break; + + case 6: + var dx = Math.abs(x - this._fromX); + var dy = Math.abs(y - this._fromY); + return dy + Math.max(0, (dx - dy) / 2); + break; + + case 8: + return Math.max(Math.abs(x - this._fromX), Math.abs(y - this._fromY)); + break; + } + }; + + return AStar; + }(Path); + + var index$4 = { + Dijkstra: Dijkstra, + AStar: AStar + }; + /** + * @class Asynchronous main loop + * @param {ROT.Scheduler} scheduler + */ + + var Engine = + /*#__PURE__*/ + function () { + function Engine(scheduler) { + this._scheduler = scheduler; + this._lock = 1; + } + /** + * Start the main loop. When this call returns, the loop is locked. + */ + + + var _proto36 = Engine.prototype; + + _proto36.start = function start() { + return this.unlock(); + }; + /** + * Interrupt the engine by an asynchronous action + */ + + + _proto36.lock = function lock() { + this._lock++; + return this; + }; + /** + * Resume execution (paused by a previous lock) + */ + + + _proto36.unlock = function unlock() { + if (!this._lock) { + throw new Error("Cannot unlock unlocked engine"); + } + + this._lock--; + + while (!this._lock) { + var actor = this._scheduler.next(); + + if (!actor) { + return this.lock(); + } + /* no actors */ + + + var result = actor.act(); + + if (result && result.then) { + /* actor returned a "thenable", looks like a Promise */ + this.lock(); + result.then(this.unlock.bind(this)); + } + } + + return this; + }; + + return Engine; + }(); + /** + * Lighting computation, based on a traditional FOV for multiple light sources and multiple passes. + */ + + + var Lighting = + /*#__PURE__*/ + function () { + function Lighting(reflectivityCallback, options) { + if (options === void 0) { + options = {}; + } + + this._reflectivityCallback = reflectivityCallback; + this._options = {}; + options = Object.assign({ + passes: 1, + emissionThreshold: 100, + range: 10 + }, options); + this._lights = {}; + this._reflectivityCache = {}; + this._fovCache = {}; + this.setOptions(options); + } + /** + * Adjust options at runtime + */ + + + var _proto37 = Lighting.prototype; + + _proto37.setOptions = function setOptions(options) { + Object.assign(this._options, options); + + if (options && options.range) { + this.reset(); + } + + return this; + }; + /** + * Set the used Field-Of-View algo + */ + + + _proto37.setFOV = function setFOV(fov) { + this._fov = fov; + this._fovCache = {}; + return this; + }; + /** + * Set (or remove) a light source + */ + + + _proto37.setLight = function setLight(x, y, color) { + var key = x + "," + y; + + if (color) { + this._lights[key] = typeof color == "string" ? fromString(color) : color; + } else { + delete this._lights[key]; + } + + return this; + }; + /** + * Remove all light sources + */ + + + _proto37.clearLights = function clearLights() { + this._lights = {}; + }; + /** + * Reset the pre-computed topology values. Call whenever the underlying map changes its light-passability. + */ + + + _proto37.reset = function reset() { + this._reflectivityCache = {}; + this._fovCache = {}; + return this; + }; + /** + * Compute the lighting + */ + + + _proto37.compute = function compute(lightingCallback) { + var doneCells = {}; + var emittingCells = {}; + var litCells = {}; + + for (var key in this._lights) { + /* prepare emitters for first pass */ + var light = this._lights[key]; + emittingCells[key] = [0, 0, 0]; + add_(emittingCells[key], light); + } + + for (var i = 0; i < this._options.passes; i++) { + /* main loop */ + this._emitLight(emittingCells, litCells, doneCells); + + if (i + 1 == this._options.passes) { + continue; + } + /* not for the last pass */ + + + emittingCells = this._computeEmitters(litCells, doneCells); + } + + for (var litKey in litCells) { + /* let the user know what and how is lit */ + var parts = litKey.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + lightingCallback(x, y, litCells[litKey]); + } + + return this; + }; + /** + * Compute one iteration from all emitting cells + * @param emittingCells These emit light + * @param litCells Add projected light to these + * @param doneCells These already emitted, forbid them from further calculations + */ + + + _proto37._emitLight = function _emitLight(emittingCells, litCells, doneCells) { + for (var key in emittingCells) { + var parts = key.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + + this._emitLightFromCell(x, y, emittingCells[key], litCells); + + doneCells[key] = 1; + } + + return this; + }; + /** + * Prepare a list of emitters for next pass + */ + + + _proto37._computeEmitters = function _computeEmitters(litCells, doneCells) { + var result = {}; + + for (var key in litCells) { + if (key in doneCells) { + continue; + } + /* already emitted */ + + + var _color = litCells[key]; + var reflectivity = void 0; + + if (key in this._reflectivityCache) { + reflectivity = this._reflectivityCache[key]; + } else { + var parts = key.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + reflectivity = this._reflectivityCallback(x, y); + this._reflectivityCache[key] = reflectivity; + } + + if (reflectivity == 0) { + continue; + } + /* will not reflect at all */ + + /* compute emission color */ + + + var emission = [0, 0, 0]; + var intensity = 0; + + for (var i = 0; i < 3; i++) { + var part = Math.round(_color[i] * reflectivity); + emission[i] = part; + intensity += part; + } + + if (intensity > this._options.emissionThreshold) { + result[key] = emission; + } + } + + return result; + }; + /** + * Compute one iteration from one cell + */ + + + _proto37._emitLightFromCell = function _emitLightFromCell(x, y, color, litCells) { + var key = x + "," + y; + var fov; + + if (key in this._fovCache) { + fov = this._fovCache[key]; + } else { + fov = this._updateFOV(x, y); + } + + for (var fovKey in fov) { + var formFactor = fov[fovKey]; + var result = void 0; + + if (fovKey in litCells) { + /* already lit */ + result = litCells[fovKey]; + } else { + /* newly lit */ + result = [0, 0, 0]; + litCells[fovKey] = result; + } + + for (var i = 0; i < 3; i++) { + result[i] += Math.round(color[i] * formFactor); + } + /* add light color */ + + } + + return this; + }; + /** + * Compute FOV ("form factor") for a potential light source at [x,y] + */ + + + _proto37._updateFOV = function _updateFOV(x, y) { + var key1 = x + "," + y; + var cache = {}; + this._fovCache[key1] = cache; + var range = this._options.range; + + function cb(x, y, r, vis) { + var key2 = x + "," + y; + var formFactor = vis * (1 - r / range); + + if (formFactor == 0) { + return; + } + + cache[key2] = formFactor; + } + + this._fov.compute(x, y, range, cb.bind(this)); + + return cache; + }; + + return Lighting; + }(); + + var Util = util; + var Color = color; + var Text = text; + exports.Util = Util; + exports.Color = Color; + exports.Text = Text; + exports.RNG = RNG$1; + exports.Display = Display; + exports.StringGenerator = StringGenerator; + exports.EventQueue = EventQueue; + exports.Scheduler = index; + exports.FOV = index$1; + exports.Map = index$2; + exports.Noise = index$3; + exports.Path = index$4; + exports.Engine = Engine; + exports.Lighting = Lighting; + exports.DEFAULT_WIDTH = DEFAULT_WIDTH; + exports.DEFAULT_HEIGHT = DEFAULT_HEIGHT; + exports.DIRS = DIRS; + exports.KEYS = KEYS; + Object.defineProperty(exports, '__esModule', { + value: true + }); +}); + diff --git a/rot.min.js b/rot.min.js new file mode 100644 index 0000000..c8d1f38 --- /dev/null +++ b/rot.min.js @@ -0,0 +1,138 @@ +var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(g,p,r){g!=Array.prototype&&g!=Object.prototype&&(g[p]=r.value)};$jscomp.getGlobal=function(g){return"undefined"!=typeof window&&window===g?g:"undefined"!=typeof global&&null!=global?global:g};$jscomp.global=$jscomp.getGlobal(this); +$jscomp.polyfill=function(g,p,r,t){if(p){r=$jscomp.global;g=g.split(".");for(t=0;tr&&(r=Math.max(0,p+r));if(null==t||t>p)t=p;t=Number(t);0>t&&(t=Math.max(0,p+t));for(r=Number(r||0);rg||1342177279>>=1)p+=p;return t}},"es6","es3");$jscomp.stringPadding=function(g,p){g=void 0!==g?String(g):" ";return 0a?a:d}function t(d){return d.charAt(0).toUpperCase()+d.substring(1)}function w(d){for(var c=arguments.length,a=Array(1c;c++)a[c+1]+=16*a[c],a.splice(c,1);else a=(c=d.match(/rgb\(([0-9, ]+)\)/i))? +c[1].split(/\s*,\s*/).map(function(b){return parseInt(b)}):[0,0,0];Q[d]=a}return a.slice()}function Y(d){for(var c=arguments.length,a=Array(1c;c++)for(b=0;be;e++)b[e]=Math.round(b[e]+a*(c[e]-d[e]));return b}function aa(d,c,a){void 0===a&&(a=.5);d=R(d);c=R(c);for(var b=0;3>b;b++)d[b]+=a*(c[b]-d[b]);return ba(d)}function R(d){var c=d[0]/255,a=d[1]/255; +d=d[2]/255;var b=Math.max(c,a,d),e=Math.min(c,a,d),f=0,m=(b+e)/2;if(b==e)e=0;else{var k=b-e;e=.5a&&(a+=1);1a?c:a<2/3?d+(c-d)*(2/3-a)*6:d}function ba(d){var c=d[2];if(0==d[1])return c=Math.round(255*c),[c,c,c];var a=d[1];a=.5>c?c*(1+a):c+a-c*a;var b=2*c-a;c=S(b,a,d[0]+1/3);var e=S(b,a,d[0]);d=S(b,a,d[0]-1/3);return[Math.round(255* +c),Math.round(255*e),Math.round(255*d)]}function fa(d,c,a){var b=d.createShader(d.VERTEX_SHADER);d.shaderSource(b,c);d.compileShader(b);if(!d.getShaderParameter(b,d.COMPILE_STATUS))throw Error(d.getShaderInfoLog(b)||"");c=d.createShader(d.FRAGMENT_SHADER);d.shaderSource(c,a);d.compileShader(c);if(!d.getShaderParameter(c,d.COMPILE_STATUS))throw Error(d.getShaderInfoLog(c)||"");a=d.createProgram();d.attachShader(a,b);d.attachShader(a,c);d.linkProgram(a);if(!d.getProgramParameter(a,d.LINK_STATUS))throw Error(d.getProgramInfoLog(a)|| +"");return a}function ha(d){var c=new Float32Array([0,0,1,0,0,1,1,1]),a=d.createBuffer();d.bindBuffer(d.ARRAY_BUFFER,a);d.bufferData(d.ARRAY_BUFFER,c,d.STATIC_DRAW);d.enableVertexAttribArray(0);d.vertexAttribPointer(0,2,d.FLOAT,!1,0,0)}function M(d){if(!(d in T)){if("transparent"==d)var c=[0,0,0,0];else if(-1a;a++)c[a]/=255}else c=L(d).map(function(b){return b/255}),c.push(1);T[d]=c}return T[d]}function U(d){d=L(d);return 36* +Math.floor(.0234375*d[0])+6*Math.floor(.0234375*d[1])+1*Math.floor(.0234375*d[2])+16}function V(d,c){var a=[],b=0;d.replace(ia,function(e,m,k,h){var f=d.substring(b,h);f.length&&a.push({type:0,value:f});a.push({type:"c"==m?2:3,value:k.trim()});b=h+e.length;return""});var e=d.substring(b);e.length&&a.push({type:0,value:e});return ja(a,c)}function ja(d,c){c||(c=Infinity);for(var a=0,b=0,e=-1;ac){for(m=-1;;){var k=f.value.indexOf(" ",m+1);if(-1==k)break;if(b+k>c)break;m=k}-1!=m?f.value=N(d,a,m,!0):-1!=e?(a=d[e],f=a.value.lastIndexOf(" "),a.value=N(d,e,f,!0),a=e):f.value=N(d,a,c-b,!1)}else b+=f.value.length,-1!=f.value.indexOf(" ")&&(e=a);a++}else d.splice(a,1)}}d.push({type:1});c=null;for(b= +0;ba?1/a:a;this._s0=2.3283064365386963E-10*(a>>>0);a=69069*a+1>>>0;this._s1=2.3283064365386963E-10*a;this._s2=2.3283064365386963E-10*(69069*a+1>>>0);this._c=1;return this};c.getUniform=function(){var a=2091639*this._s0+2.3283064365386963E-10*this._c;this._s0=this._s1;this._s1=this._s2;this._c=a|0;return this._s2=a-this._c};c.getUniformInt=function(a,b){var e=Math.max(a,b);a=Math.min(a,b);return Math.floor(this.getUniform()* +(e-a+1))+a};c.getNormal=function(a,b){void 0===a&&(a=0);void 0===b&&(b=1);do{var e=2*this.getUniform()-1;var f=2*this.getUniform()-1;f=e*e+f*f}while(1b||0>e||b>=f.width||e>=f.height?[-1,-1]:this._normalizedEventToPosition(b,e)};return c}(I);w.map={s:"toString"};var ka=Object.freeze({mod:p,clamp:r,capitalize:t,format:w}),O=function(d){function c(){var b=d.call(this)||this; +b._spacingX=0;b._spacingY=0;b._hexSize=0;return b}_inheritsLoose(c,d);var a=c.prototype;a.draw=function(b,e){var f=b[2],a=b[3],k=b[4];b=[(b[0]+1)*this._spacingX,b[1]*this._spacingY+this._hexSize];this._options.transpose&&b.reverse();e&&(this._ctx.fillStyle=k,this._fill(b[0],b[1]));if(f)for(this._ctx.fillStyle=a,e=[].concat(f),f=0;fa;a++)for(e=0;ea;a++){for(e=0;e< +b.length;e++)c[a]*=b[e][a]/255;c[a]=Math.round(c[a])}return c},multiply_:function(d){for(var c=arguments.length,a=Array(1c;c++){for(b=0;ba;a++)d[a]+=c instanceof Array?Math.round(q.getNormal(0,c[a])):c;return d},rgb2hsl:R,hsl2rgb:ba, +toRGB:function(d){return"rgb("+d.map(function(c){return r(c,0,255)}).join(",")+")"},toHex:function(d){return"#"+d.map(function(c){return r(c,0,255).toString(16).padStart(2,"0")}).join("")}});var x=function(d){function c(){var b=d.call(this)||this;b._uniforms={};try{b._gl=b._initWebGL()}catch(e){alert(e.message)}return b}_inheritsLoose(c,d);c.isSupported=function(){return!!document.createElement("canvas").getContext("webgl2",{preserveDrawingBuffer:!0})};var a=c.prototype;a.schedule=function(b){requestAnimationFrame(b)}; +a.getContainer=function(){return this._gl.canvas};a.setOptions=function(b){var e=this;d.prototype.setOptions.call(this,b);this._updateSize();var f=this._options.tileSet;f&&"complete"in f&&!f.complete?f.addEventListener("load",function(){return e._updateTexture(f)}):this._updateTexture(f)};a.draw=function(b,e){var f=this._gl,a=this._options,k=b[0],h=b[1],c=b[2],d=b[3];b=b[4];f.scissor(k*a.tileWidth,f.canvas.height-(h+1)*a.tileHeight,a.tileWidth,a.tileHeight);e&&(a.tileColorize?f.clearColor(0,0,0,0): +f.clearColor.apply(f,M(b)),f.clear(f.COLOR_BUFFER_BIT));if(c)for(e=[].concat(c),c=[].concat(b),d=[].concat(d),f.uniform2fv(this._uniforms.targetPosRel,[k,h]),k=0;k +b||0>e||b>=f.width||e>=f.height?[-1,-1]:this._normalizedEventToPosition(b,e)};a._initWebGL=function(){var b=this,e=document.createElement("canvas").getContext("webgl2",{preserveDrawingBuffer:!0});window.gl=e;var f=fa(e,la,ma);e.useProgram(f);ha(e);na.forEach(function(a){return b._uniforms[a]=e.getUniformLocation(f,a)});this._program=f;e.enable(e.BLEND);e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);e.enable(e.SCISSOR_TEST);return e};a._normalizedEventToPosition= +function(b,e){return[Math.floor(b/this._options.tileWidth),Math.floor(e/this._options.tileHeight)]};a._updateSize=function(){var b=this._gl,e=this._options,a=[e.width*e.tileWidth,e.height*e.tileHeight];b.canvas.width=a[0];b.canvas.height=a[1];b.viewport(0,0,a[0],a[1]);b.uniform2fv(this._uniforms.tileSize,[e.tileWidth,e.tileHeight]);b.uniform2fv(this._uniforms.targetSize,a)};a._updateTexture=function(b){var e=this._gl,a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER, +e.NEAREST);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT);e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,b)};return c}(I),na="targetPosRel tilesetPosAbs tileSize targetSize colorize bg tint".split(" "),la="#version 300 es\n\nin vec2 tilePosRel;\nout vec2 tilesetPosPx;\n\nuniform vec2 tilesetPosAbs;\nuniform vec2 tileSize;\nuniform vec2 targetSize;\nuniform vec2 targetPosRel;\n\nvoid main() {\n\tvec2 targetPosPx = (targetPosRel + tilePosRel) * tileSize;\n\tvec2 targetPosNdc = ((targetPosPx / targetSize)-0.5)*2.0;\n\ttargetPosNdc.y *= -1.0;\n\n\tgl_Position = vec4(targetPosNdc, 0.0, 1.0);\n\ttilesetPosPx = tilesetPosAbs + tilePosRel * tileSize;\n}", +ma="#version 300 es\nprecision highp float;\n\nin vec2 tilesetPosPx;\nout vec4 fragColor;\nuniform sampler2D image;\nuniform bool colorize;\nuniform vec4 bg;\nuniform vec4 tint;\n\nvoid main() {\n\tfragColor = vec4(0, 0, 0, 1);\n\n\tvec4 texel = texelFetch(image, ivec2(tilesetPosPx), 0);\n\n\tif (colorize) {\n\t\ttexel.rgb = tint.a * tint.rgb + (1.0-tint.a) * texel.rgb;\n\t\tfragColor.rgb = texel.a*texel.rgb + (1.0-texel.a)*bg.rgb;\n\t\tfragColor.a = texel.a + (1.0-texel.a)*bg.a;\n\t} else {\n\t\tfragColor = texel;\n\t}\n}", +T={},u=function(d){function c(){var b=d.call(this)||this;b._offset=[0,0];b._cursor=[-1,-1];b._lastColor="";return b}_inheritsLoose(c,d);var a=c.prototype;a.schedule=function(b){setTimeout(b,1E3/60)};a.setOptions=function(b){d.prototype.setOptions.call(this,b);var e=[b.width,b.height];this._offset=this.computeSize().map(function(b,a){return Math.floor((b-e[a])/2)})};a.clear=function(){process.stdout.write("\u001b[0;48;5;"+U(this._options.bg)+"m\u001b[2J")};a.draw=function(b,e){var a=b[2],m=b[3],k= +b[4],c=this._offset[0]+b[0],d=this._offset[1]+b[1];b=this.computeSize();if(!(0>c||c>=b[0]||0>d||d>=b[1])){if(c!==this._cursor[0]||d!==this._cursor[1])process.stdout.write("\u001b["+(d+1)+";"+(c+1)+"H"),this._cursor[0]=c,this._cursor[1]=d;e&&(a||(a=" "));a&&(e="\u001b[0;38;5;"+U(m)+";48;5;"+U(k)+"m",e!==this._lastColor&&(process.stdout.write(e),this._lastColor=e),a=[].concat(a),process.stdout.write(a[0]),this._cursor[0]++,this._cursor[0]>=b[0]&&(this._cursor[0]=0,this._cursor[1]++))}};a.computeFontSize= +function(){throw Error("Terminal backend has no notion of font size");};a.eventToPosition=function(b,e){return[b,e]};a.computeSize=function(){return[process.stdout.columns,process.stdout.rows]};return c}(I),ia=/%([bc]){([^}]*)}/g;I=Object.freeze({TYPE_TEXT:0,TYPE_NEWLINE:1,TYPE_FG:2,TYPE_BG:3,measure:function(d,c){var a={width:0,height:1};d=V(d,c);for(var b=c=0;bl||65500l||65518this._options.order?a=a.slice(-this._options.order):a.lengthb){e=f;break}this._events.splice(e,0,a);this._eventTimes.splice(e,0,b)};c.get=function(){if(!this._events.length)return null;var a=this._eventTimes.splice(0,1)[0];if(0b)return e=this._visibleCoords(0,e,a,m),b=this._visibleCoords(360+b,360,a,m),e||b;for(var f=0;fe[0])return b=this._checkVisibility(b,[b[1],b[1]],a,c),e=this._checkVisibility([0,1],e,a,c),(b+e)/2;for(var f=0,m=!1;fd&&f%2&&(g=!1);if(!g)return 0;m=d-f+1;if(m%2)f%2?(d=c[f],d=(e[0]*d[1]-d[0]*e[1])/(d[1]*e[1]),a&&c.splice(f,m,e)):(d=c[d],d=(d[0]*b[1]-b[0]*d[1])/(b[1]*d[1]),a&&c.splice(f,m,b));else if(f%2)l=c[f],d=c[d],d=(d[0]*l[1]-l[0]*d[1])/(l[1]*d[1]),a&&c.splice(f,m);else return a&&c.splice(f,m,b,e),1;return d/((e[0]*b[1]-b[0]*e[1])/(b[1]*e[1]))};return c}(u);var C=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1, +0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]];u=function(d){function c(){return d.apply(this,arguments)||this}_inheritsLoose(c,d);var a=c.prototype;a.compute=function(b,e,a,c){c(b,e,0,1);for(var f=0;f=f;){f+=1;var z=b+f*n+m*l,y=e+f*g+m*q,r=(f-.5)/(m+.5),t=(f+.5)/(m-.5);if(!(t>c)){if(rthis._options.timeLimit)return null;this._map=this._fillMap(1);this._dug=0;this._rooms=[];this._unconnected=[];this._generateRooms();if(!(2>this._rooms.length)&&this._generateCorridors())break}if(b)for(a=0;athis._options.roomDugPercentage)break}while(f)};a._generateRoom=function(){for(var b=0;b=n&&d[e]<=l){c=d.slice();n=0;switch(h){case 0:n=a.getTop()- +1;break;case 1:n=a.getRight()+1;break;case 2:n=a.getBottom()+1;break;case 3:n=a.getLeft()-1}c[(e+1)%2]=n;this._digLine([d,c])}else if(d[e]l+1){c=d[e]-c[e];n=0;switch(h){case 0:case 1:n=0>c?3:1;break;case 2:case 3:n=0>c?1:3}c=this._placeInWall(a,(h+n)%4);if(!c)return!1;h=[0,0];h[e]=d[e];e=(e+1)%2;h[e]=c[e];this._digLine([d,h,c])}else{n=(e+1)%2;c=this._placeInWall(a,h);if(!c)return!1;h=Math.round((c[n]+d[n])/2);l=[0,0];var g=[0,0];l[e]=d[e];l[n]=h;g[e]=c[e];g[n]=h;this._digLine([d,l,g,c])}b.addDoor(d[0], +d[1]);a.addDoor(c[0],c[1]);e=this._unconnected.indexOf(b);-1!=e&&(this._unconnected.splice(e,1),this._connected.push(b));e=this._unconnected.indexOf(a);-1!=e&&(this._unconnected.splice(e,1),this._connected.push(a));return!0};a._placeInWall=function(b,a){var e=[0,0],c=[0,0],d=0;switch(a){case 0:c=[1,0];e=[b.getLeft(),b.getTop()-1];d=b.getRight()-b.getLeft()+1;break;case 1:c=[0,1];e=[b.getRight()+1,b.getTop()];d=b.getBottom()-b.getTop()+1;break;case 2:c=[1,0];e=[b.getLeft(),b.getBottom()+1];d=b.getRight()- +b.getLeft()+1;break;case 3:c=[0,1],e=[b.getLeft()-1,b.getTop()],d=b.getBottom()-b.getTop()+1}b=[];a=-2;for(var h=0;hb||0>a||b>=this._width||a>=this._height?!1:1==this._map[b][a]};a._canBeDugCallback=function(b,a){return 1>b||1>a||b+1>=this._width||a+1>=this._height?!1:1==this._map[b][a]};return c}(H);var E=function(d){function c(b,a,f){void 0===f&&(f={});b=d.call(this,b,a)||this;b._options={born:[5,6,7,8],survive:[4,5,6,7,8],topology:8};b.setOptions(f);b._dirs=v[b._options.topology];b._map=b._fillMap(0);return b}_inheritsLoose(c,d);var a=c.prototype; +a.randomize=function(b){for(var a=0;ah||h>=this._width||0>d||d>=this._height||(e+=1==this._map[h][d]?1:0)}return e};a.connect=function(b,a,f){a||(a=0);var e=[],c={},d=1,n=[0,0];6==this._options.topology&& +(d=2,n=[0,1]);for(var l=0;ll&&!(h.lengthd);l++);return[e,c]};a._getClosest=function(b,a){var e=null,c=null,d;for(d in a){var h=a[d],n=(h[0]-b[0])*(h[0]-b[0])+(h[1]- +b[1])*(h[1]-b[1]);if(null==c||nf[1]&&(e--, +g=1);m=mf[0]?m-g:f[1]%2?m-g:m+g;this._map[m][e]=k;g=[m,e];var q=this._pointKey(g);c[q]=g;delete d[q]}h&&h(a,b)};a._freeSpace=function(b,a,f){return 0<=b&&bthis._options.timeLimit)break;var d=this._findWall();if(!d)break;var h=d.split(",");d=parseInt(h[0]);h=parseInt(h[1]);var g=this._getDiggingDirection(d,h);if(g){var l=0;do if(l++,this._tryFeature(d,h,g[0],g[1])){this._removeSurroundingWalls(d,h);this._removeSurroundingWalls(d-g[0],h-g[1]);break}while(l< +this._featureAttempts);for(var q in this._walls)1b||0>a||b>=this._width||a>=this._height?!1:1==this._map[b][a]};a._canBeDugCallback=function(b,a){return 1> +b||1>a||b+1>=this._width||a+1>=this._height?!1:1==this._map[b][a]};a._priorityWallCallback=function(b,a){this._walls[b+","+a]=2};a._firstRoom=function(){var b=P.createRandomCenter(Math.floor(this._width/2),Math.floor(this._height/2),this._options);this._rooms.push(b);b.create(this._digCallback)};a._findWall=function(){var b=[],a=[],f;for(f in this._walls)2==this._walls[f]?a.push(f):b.push(f);b=a.length?a:b;if(!b.length)return null;b=q.getItem(b.sort());delete this._walls[b];return b};a._tryFeature= +function(b,a,f,c){var e=q.getWeightedValue(this._features);b=qa[e].createRandomAt(b,a,f,c,this._options);if(!b.isValid(this._isWallCallback,this._canBeDugCallback))return!1;b.create(this._digCallback);b instanceof P&&this._rooms.push(b);b instanceof X&&(b.createPriorityWalls(this._priorityWallCallback),this._corridors.push(b));return!0};a._removeSurroundingWalls=function(b,a){for(var e=v[4],c=0;c=b||0>=a||b>=this._width-1||a>=this._height-1)return null;for(var e=null,c=v[4],d=0;dr;r++){var t=g+2*h[r][0];var A=l+2*h[r][1];if(this._isFree(d,t,A,a,c)){d[t][A]=0;d[g+h[r][0]][l+h[r][1]]=0;g=t;l= +A;p=!1;k++;break}}}while(!p)}}while(k+1a;a++)b[a][0]=0,b[a][1]=0;switch(Math.floor(4*q.getUniform())){case 0:b[0][0]=-1;b[1][0]=1;b[2][1]=-1;b[3][1]=1;break;case 1:b[3][0]=-1;b[2][0]=1;b[1][1]=-1;b[0][1]=1;break;case 2:b[2][0]=-1;b[3][0]=1;b[0][1]=-1;b[1][1]=1;break;case 3:b[1][0]=-1,b[0][0]=1,b[3][1]=-1,b[2][1]=1}};a._isFree=function(b,a,c,d,k){return 1>a|| +1>c||a>=d||c>=k?!1:b[a][c]};return c}(u);u=function(d){function c(b,a,c){b=d.call(this,b,a)||this;b.map=[];b.rooms=[];b.connectedCells=[];c=Object.assign({cellWidth:3,cellHeight:3},c);c.hasOwnProperty("roomWidth")||(c.roomWidth=b._calculateRoomSize(b._width,c.cellWidth));c.hasOwnProperty("roomHeight")||(c.roomHeight=b._calculateRoomSize(b._height,c.cellHeight));b._options=c;return b}_inheritsLoose(c,d);var a=c.prototype;a.create=function(b){this.map=this._fillMap(1);this.rooms=[];this.connectedCells= +[];this._initRooms();this._connectRooms();this._connectUnconnectedRooms();this._createRandomRoomConnections();this._createRooms();this._createCorridors();if(b)for(var a=0;ab&&(b=2);2>c&&(c=2);return[b,c]};a._initRooms=function(){for(var b=0;bh||h>=this._options.cellWidth||0>k||k>=this._options.cellHeight)){var g=this.rooms[b][a];if(0r||r>=b||0>p||p>=a)){d=this.rooms[r][p]; +k=!0;if(0==d.connections.length)break;for(r=0;rA-(u.y+u.height);)A++;if(0t-(u.x+u.width);)t++;u=Math.round(q.getUniformInt(0,k-g)/2);for(var x=Math.round(q.getUniformInt(0,h-l)/2);t+u+g>=b;)u?u--:g--;for(;A+x+l>=a;)x?x--:l--;t+=u;A+=x;this.rooms[v][w].x=t;this.rooms[v][w].y=A;this.rooms[v][w].width=g;this.rooms[v][w].height=l;for(u=t;ud.cellx? +(k=2,h=4):g.cellxd.celly?(k=3,h=1):(k=1,h=3),this._drawCorridor(this._getWallPosition(d,k),this._getWallPosition(g,h))}};return c}(u);x={Arena:x,Uniform:D,Cellular:E,Digger:H,EllerMaze:ra,DividedMaze:sa,IceyMaze:ta,Rogue:u};var ua=.5*(Math.sqrt(3)-1),K=(3-Math.sqrt(3))/6;u={Simplex:function(d){function c(a){void 0===a&&(a=256);var b=d.call(this)||this;b._gradients=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(var c=[],f=0;fu){var v=1;var w=0}else v=0,w=1;t=l-v+K;var x=u-w+K;b=l-1+2*K;a=u-1+2*K;q=p(q,g);g=p(r,g);var B=.5-l*l-u*u;0<=B&&(B*=B,r=d[q+c[g]],k=this._gradients[r],k=B*B*(k[0]*l+k[1]*u));l=.5-t*t- +x*x;0<=l&&(l*=l,r=d[q+v+c[g+w]],h=this._gradients[r],h=l*l*(h[0]*t+h[1]*x));l=.5-b*b-a*a;0<=l&&(l*=l,r=d[q+1+c[g+1]],c=this._gradients[r],n=l*l*(c[0]*b+c[1]*a));return 70*(k+h+n)};return c}(function(){})};E=function(){function d(c,a,b,d){void 0===d&&(d={});this._toX=c;this._toY=a;this._passableCallback=b;this._options=Object.assign({topology:8},d);this._dirs=v[this._options.topology];8==this._options.topology&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3], +this._dirs[5],this._dirs[7]])}d.prototype._getNeighbors=function(c,a){for(var b=[],d=0;dl;l++){var p=Math.round(g[l]*k);h[l]=p;n+=p}n>this._options.emissionThreshold&&(c[d]=h)}}return c};c._emitLightFromCell=function(a,b,c,d){var e=a+","+b;a=e in this._fovCache?this._fovCache[e]:this._updateFOV(a,b);for(var f in a){b=a[f];f in +d?e=d[f]:(e=[0,0,0],d[f]=e);for(var g=0;3>g;g++)e[g]+=Math.round(c[g]*b)}return this};c._updateFOV=function(a,b){var c={};this._fovCache[a+","+b]=c;var d=this._options.range;this._fov.compute(a,b,d,function(a,b,e,f){e=f*(1-e/d);0!=e&&(c[a+","+b]=e)}.bind(this));return c};return d}();g.Util=ka;g.Color=J;g.Text=I;g.RNG=q;g.Display=G;g.StringGenerator=O;g.EventQueue=ea;g.Scheduler=F;g.FOV=B;g.Map=x;g.Noise=u;g.Path=D;g.Engine=E;g.Lighting=H;g.DEFAULT_WIDTH=80;g.DEFAULT_HEIGHT=25;g.DIRS=v;g.KEYS={VK_CANCEL:3, +VK_HELP:6,VK_BACK_SPACE:8,VK_TAB:9,VK_CLEAR:12,VK_RETURN:13,VK_ENTER:14,VK_SHIFT:16,VK_CONTROL:17,VK_ALT:18,VK_PAUSE:19,VK_CAPS_LOCK:20,VK_ESCAPE:27,VK_SPACE:32,VK_PAGE_UP:33,VK_PAGE_DOWN:34,VK_END:35,VK_HOME:36,VK_LEFT:37,VK_UP:38,VK_RIGHT:39,VK_DOWN:40,VK_PRINTSCREEN:44,VK_INSERT:45,VK_DELETE:46,VK_0:48,VK_1:49,VK_2:50,VK_3:51,VK_4:52,VK_5:53,VK_6:54,VK_7:55,VK_8:56,VK_9:57,VK_COLON:58,VK_SEMICOLON:59,VK_LESS_THAN:60,VK_EQUALS:61,VK_GREATER_THAN:62,VK_QUESTION_MARK:63,VK_AT:64,VK_A:65,VK_B:66,VK_C:67, +VK_D:68,VK_E:69,VK_F:70,VK_G:71,VK_H:72,VK_I:73,VK_J:74,VK_K:75,VK_L:76,VK_M:77,VK_N:78,VK_O:79,VK_P:80,VK_Q:81,VK_R:82,VK_S:83,VK_T:84,VK_U:85,VK_V:86,VK_W:87,VK_X:88,VK_Y:89,VK_Z:90,VK_CONTEXT_MENU:93,VK_NUMPAD0:96,VK_NUMPAD1:97,VK_NUMPAD2:98,VK_NUMPAD3:99,VK_NUMPAD4:100,VK_NUMPAD5:101,VK_NUMPAD6:102,VK_NUMPAD7:103,VK_NUMPAD8:104,VK_NUMPAD9:105,VK_MULTIPLY:106,VK_ADD:107,VK_SEPARATOR:108,VK_SUBTRACT:109,VK_DECIMAL:110,VK_DIVIDE:111,VK_F1:112,VK_F2:113,VK_F3:114,VK_F4:115,VK_F5:116,VK_F6:117,VK_F7:118, +VK_F8:119,VK_F9:120,VK_F10:121,VK_F11:122,VK_F12:123,VK_F13:124,VK_F14:125,VK_F15:126,VK_F16:127,VK_F17:128,VK_F18:129,VK_F19:130,VK_F20:131,VK_F21:132,VK_F22:133,VK_F23:134,VK_F24:135,VK_NUM_LOCK:144,VK_SCROLL_LOCK:145,VK_CIRCUMFLEX:160,VK_EXCLAMATION:161,VK_DOUBLE_QUOTE:162,VK_HASH:163,VK_DOLLAR:164,VK_PERCENT:165,VK_AMPERSAND:166,VK_UNDERSCORE:167,VK_OPEN_PAREN:168,VK_CLOSE_PAREN:169,VK_ASTERISK:170,VK_PLUS:171,VK_PIPE:172,VK_HYPHEN_MINUS:173,VK_OPEN_CURLY_BRACKET:174,VK_CLOSE_CURLY_BRACKET:175, +VK_TILDE:176,VK_COMMA:188,VK_PERIOD:190,VK_SLASH:191,VK_BACK_QUOTE:192,VK_OPEN_BRACKET:219,VK_BACK_SLASH:220,VK_CLOSE_BRACKET:221,VK_QUOTE:222,VK_META:224,VK_ALTGR:225,VK_WIN:91,VK_KANA:21,VK_HANGUL:21,VK_EISU:22,VK_JUNJA:23,VK_FINAL:24,VK_HANJA:25,VK_KANJI:25,VK_CONVERT:28,VK_NONCONVERT:29,VK_ACCEPT:30,VK_MODECHANGE:31,VK_SELECT:41,VK_PRINT:42,VK_EXECUTE:43,VK_SLEEP:95};Object.defineProperty(g,"__esModule",{value:!0})}); diff --git a/rpccalls.js b/rpccalls.js new file mode 100644 index 0000000..af721bb --- /dev/null +++ b/rpccalls.js @@ -0,0 +1,57 @@ +var axios = require('axios'); +var request = require('request'); + +/*List of RPC calls +Daemon - +Get blockheight: "get_block_count" +*/ + +function constructCall(method, params) { + var body = { + "jsonrpc": "2.0", + "id": "0", + "method": method, + "params": params + } + return body; +} + +var lastBlock = { + height: 0, + hash: 0, + setHeight: function(newHeight) {this.height = newHeight} +} +var daemonURL = 'http://localhost:34568/json_rpc'; + +function daemonCall(method, params, callback, io) { + // Real blockchain call (now used for all cases) + var body = constructCall(method, params); + request({ + url: daemonURL, + method: 'POST', + headers: {"content-type": "application/json"}, + json: body + }, function (error, res, body) { + if (error) { + console.log("Daemon connection error:", error.message); + callback(null); + return; + } + callback(body); + }); +} + +function getBlockHeight(body) { + if (body == null || body.result == null || body.result.count == null) { + return null; + } + return body.result.count; +} + + +// Export the functions +module.exports = { + daemonCall: daemonCall, + getBlockHeight: getBlockHeight, + lastBlock: lastBlock, +}; diff --git a/user.js b/user.js new file mode 100644 index 0000000..b4e13d9 --- /dev/null +++ b/user.js @@ -0,0 +1,45 @@ +function User(socketid, ip) { + this.id = null; + this.socketid = socketid; + this.ip = ip; + this.nick = null; + this.receiveAddy = ""; + this.payoutAddy = ""; + this.blockRec = null; + this.map = null; + this.player = false; + this.won = false; + this.game = null; // Reference to current game + this.paymentAmount = 0; + this.paymentVerified = false; +} + +User.prototype.startGame = function(mapWidth, mapHeight) { + const Game = require('./game'); + this.game = new Game(this.socketid, mapWidth, mapHeight); + return this.game; +}; + +User.prototype.verifyPayment = function(amount) { + this.paymentAmount = amount; + this.paymentVerified = true; + return true; +}; + +User.prototype.calculateReward = function() { + if (!this.game || this.game.gameState !== 'won') return 0; + + // Base reward is 2x the entrance fee + let reward = this.paymentAmount * 2; + + // Bonus for finding treasure + if (this.game.player.hasTreasure) { + reward = this.paymentAmount * 5; + } + + return reward; +}; + +module.exports = { + User: User +};