E
E
Eugene4542020-06-17 17:41:26
JavaScript
Eugene454, 2020-06-17 17:41:26

How to display a letter in the place where it stands?

Decided to make Hangman with an interface! I display the hidden word in the canvas in the form of the number "_". The problem is that when I click on the button, I get the letter to the very beginning. How can you insert it where its place is in the word?

// *Инициализируем канвас
const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");
// *Переменные
const words = ["dog", "pizza"];
const lettersArray = [
  "q",
  "w",
  "e",
  "r",
  "t",
  "y",
  "u",
  "i",
  "o",
  "p",
  "a",
  "s",
  "d",
  "f",
  "g",
  "h",
  "j",
  "k",
  "l",
  "z",
  "x",
  "c",
  "v",
  "b",
  "n",
  "m",
];
const buttonsField = document.querySelector(".buttons");
let attempts = 9;
let remainingLetters;

// *Создаем кнопки
lettersArray.forEach((letter) => {
  const button = document.createElement("button");
  button.innerText = letter;
  button.classList.add("letter-btn");
  buttonsField.append(button);
});
// *При нажатии делаем кнопки недоступными
const letterBtnsArray = document.querySelectorAll(".letter-btn");
letterBtnsArray.forEach((letterBtn) => {
  letterBtn.addEventListener("click", function (e) {
    btn = e.target;
    btn.classList.add("pressed");
    btn.setAttribute("disabled", true);
  });
});

// *Выбираем рандомное слово
function chooseRandomWord(word) {
  return word[Math.floor(Math.random() * word.length)];
}

// *Создаем массив, в котором вместо букв будут "_"
function setupArray(word) {
  let answerArray = [];
  for (let i = 0; i < word.length; i++) {
    answerArray[i] = "_";
  }
  return answerArray;
}

// *Рисуем на канвасе слово
function drawWord(answerArray) {
  x = 100;
  for (let i = 0; i < answerArray.length; i++) {
    ctx.fillRect(x, 200, 50, 3);
    x += 75;
  }
}
let lastLetter;
letterBtnsArray.forEach((letterBtn) => {
  letterBtn.addEventListener("click", function (e) {
    lastLetter = e.target.innerText.toLowerCase();
    checkAnswer(lastLetter, word, answerArray);
  });
});
function checkAnswer(guess, word, answerArray) {
  x = 115;
  for (let i = 0; i < word.length; i++) {
    if (guess === word[i]) {
      if (guess !== answerArray[i]) {
        answerArray[i] = guess;
        ctx.font = "48px serif";
        ctx.fillText(answerArray[i], x, 200);
      }
    }
  }
}

const word = chooseRandomWord(words);
const answerArray = setupArray(word);
remainingLetters = word.length;
drawWord(answerArray);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
szanislo, 2020-06-17
@szanislo

It is necessary to add the response index multiplied by the length of the character in the response check

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question