81 lines
2.3 KiB
JavaScript
81 lines
2.3 KiB
JavaScript
|
import { Controller } from "https://unpkg.com/@hotwired/stimulus@v3.2.2/dist/stimulus.js"
|
||
|
|
||
|
import { MARKERS, GameController } from "../models/gamecontroller.js";
|
||
|
|
||
|
export default class extends Controller {
|
||
|
static targets = ["row"];
|
||
|
|
||
|
connect() {
|
||
|
this._gameController = new GameController();
|
||
|
|
||
|
this._activeRowIndex = 0;
|
||
|
this._activeLetter = 0;
|
||
|
|
||
|
this._buildPlayfield(this._gameController.guesses(), this._gameController.wordLength());
|
||
|
}
|
||
|
|
||
|
tappedKey(key) {
|
||
|
console.log(`Key ${key} was tapped via outliet`);
|
||
|
|
||
|
this._addLetter(key);
|
||
|
}
|
||
|
|
||
|
_addLetter(letter) {
|
||
|
let rowElem = this.rowTargets[this._activeRowIndex];
|
||
|
let colElem = rowElem.querySelectorAll("span")[this._activeLetter];
|
||
|
|
||
|
colElem.innerText = letter.toUpperCase();
|
||
|
|
||
|
this._activeLetter += 1;
|
||
|
if (this._activeLetter >= this._gameController.wordLength()) {
|
||
|
this._colorizeRow(rowElem);
|
||
|
|
||
|
this._activeRowIndex += 1;
|
||
|
this._activeLetter = 0;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
_buildPlayfield(rows, wordLength) {
|
||
|
let newRows = [];
|
||
|
for (let r = 0; r < rows; r++) {
|
||
|
let divElem = document.createElement("div");
|
||
|
divElem.classList.add("row");
|
||
|
divElem.setAttribute("data-playfield-target", "row");
|
||
|
|
||
|
for (let c = 0; c < wordLength; c++) {
|
||
|
let letterSpan = document.createElement("span");
|
||
|
divElem.appendChild(letterSpan);
|
||
|
}
|
||
|
|
||
|
newRows.push(divElem);
|
||
|
}
|
||
|
|
||
|
this.element.replaceChildren.apply(this.element, newRows);
|
||
|
}
|
||
|
|
||
|
_colorizeRow(row) {
|
||
|
let guessedWord = Array.from(row.querySelectorAll("span")).map((x) => x.innerText).join("");
|
||
|
console.log("The guessed word is: " + guessedWord);
|
||
|
|
||
|
let results = this._gameController.checkGuess(guessedWord);
|
||
|
let markers = results.markers;
|
||
|
|
||
|
for (let i = 0; i < this._gameController.wordLength(); i++) {
|
||
|
switch (markers[i]) {
|
||
|
case MARKERS.RIGHT_POS:
|
||
|
row.children[i].classList.add("right-pos");
|
||
|
break;
|
||
|
case MARKERS.RIGHT_CHAR:
|
||
|
row.children[i].classList.add("right-char");
|
||
|
break;
|
||
|
case MARKERS.MISS:
|
||
|
row.children[i].classList.add("miss");
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
window.dispatchEvent(new CustomEvent("guessResults", {
|
||
|
detail: results
|
||
|
}));
|
||
|
}
|
||
|
}
|