summaryrefslogtreecommitdiff
path: root/public/main.js
diff options
context:
space:
mode:
Diffstat (limited to 'public/main.js')
-rw-r--r--public/main.js67
1 files changed, 61 insertions, 6 deletions
diff --git a/public/main.js b/public/main.js
index 3f7031b..13d83e7 100644
--- a/public/main.js
+++ b/public/main.js
@@ -4,21 +4,73 @@ const $ = (s,c) => (c||document).querySelector(s);
function $$(x,y,z,a){a=(z||document).querySelectorAll(x);if(typeof y=="function")[].forEach.call(a,y);return a}
function m(a,b,c){c=document;b=c.createElement(b||"p");b.innerHTML=a.trim();for(a=c.createDocumentFragment();c=b.firstChild;)a.appendChild(c);return a.firstChild}
+const board = [];
const boardEl = document.createElement("table");
$("#board").appendChild(boardEl);
for (let i=0;i<6;i++) {
let o = "<tr>";
- for (let j=0;j<6;j++) {
- o += `<td>&nbsp;</td>`
- }
- o = m(o, "table");
+ for (let j=0;j<6;j++) o += `<td>&nbsp;</td>`;
+ o = m(o, "tbody");
boardEl.appendChild(o);
+ board.push(o);
+}
+
+function setRow(r, s) {
+ s = s.toUpperCase();
+ $$("td", (e,i) => e.innerHTML = s.charAt(i)||"&nbsp;", r);
+}
+
+function setRowState(r, s) {
+ $$("td", (e,i) => {
+ e.classList.add({
+ "=":"found",
+ "-":"present",
+ " ":"absent"
+ }[s.charAt(i)]);
+ }, r);
}
+let done = false;
+let currentRow = 0;
+let currentStr = "";
function processKey(key) {
- if (!/^([a-z]|enter|bspc)$/.test(key)) return;
- console.log(key);
+ if (done || !/^([a-z]|enter|bspc)$/.test(key)) return;
+
+ if (key === "enter") {
+ return tryWord();
+
+ } else if (key === "bspc") {
+ currentStr = currentStr.slice(0,-1);
+
+ } else {
+ currentStr += key;
+ currentStr = currentStr.slice(0,6);
+ }
+
+ setRow(board[currentRow], currentStr);
+}
+
+async function tryWord() {
+ if (currentStr.length !== 6) return alert("Guesses must use all six letters!");
+
+ const r = await fetch("/guess/"+currentStr).then(r => r.json());
+ if (r.result === false) return alert("Not in word list!");
+
+ setRowState(board[currentRow], r.result);
+ if (r.result === "======") {
+ setTimeout(() => alert("Congratulations!"));
+ done = true;
+ return;
+ }
+
+ currentStr = "";
+ currentRow++;
+
+ if (currentRow === 6) {
+ setTimeout(() => alert("Better luck next time!"));
+ done = true;
+ }
}
document.addEventListener("keydown", e =>
@@ -26,6 +78,9 @@ document.addEventListener("keydown", e =>
processKey(e.key.toLowerCase()
.replace("backspace", "bspc")));
+$$("td[data-key]", k => k.addEventListener("click",
+ () => processKey(k.dataset.key)));
+
//if ("serviceWorker" in navigator) {
// navigator.serviceWorker.register("sw.js")
// .then(() => console.log("Service worker registered"));