Борьба за то, как создать уникальный идентификатор для элементов div - PullRequest
0 голосов
/ 30 апреля 2020

У меня есть функция с именем generateUniqueCard(isEasy), которая возвращает элемент div с COUNT количеством элементов img (параметр isEasy возвращает стиль карты solid, если он равен true). Основываясь на существующих картах в #board, я пытаюсь убедиться, что все divCards, которые я возвращаю из функции, имеют уникальный идентификатор в виде STYLE-SHAPE-COLOR-COUNT.

Мой текущий подход, который сейчас не работает для меня, заключается в попытке использовать querySelectorAll для создания элементов div в #board, а затем запустить некоторое время l oop с условием для создания randomAttributes (generateRandomAttributes(isEasy) для создания уникального идентификатора, если идентификатор параметра querySelector равен нулю (потому что, если он равен нулю, тогда идентификатор еще не существует на доске, что гарантирует, что следующий сгенерированный идентификатор будет уникальным).

Прямо сейчас проблема, с которой я сталкиваюсь, состоит в том, что все сгенерированные идентификаторы в созданных элементах div - это * [object NodeList], а не randomAttributes, сгенерированные из generateRandomAttributes(isEasy)

Фрагмент кода

  let timerId;
  let remainingSeconds;

  let totalCards;
  let easyDifficulty;

  const STYLE = ["solid", "outline", "striped"];
  const SHAPE = ["diamond", "oval", "squiggle"];
  const COLOR = ["green", "purple", "red"];
  const COUNT = [1, 2, 3];

  /**
   * Add a function that will be called when the window is loaded.
   */
  window.addEventListener("load", init);

  /**
   * CHANGE: Describe what your init function does here.
   */
  function init() {
    let startButton = document.getElementById("start-btn");
    let backButton = document.getElementById("back-btn");
    startButton.addEventListener("click", startGame);
    backButton.addEventListener("click", exitGame);
  }

  function startGame() {
    toggleViews();

    if (qs("input[type = \"radio\"]:checked").value === "easy") {
      easyDifficulty = true;
      totalCards = 9;
    } else {
      easyDifficulty = false
      totalCards = 12;
    }

    generateSetDeck(easyDifficulty, totalCards);
  }

  function generateSetDeck(easyDifficulty, totalCards) {
    for (let i = 0; i < totalCards; i++) {
      id("board").appendChild(generateUniqueCard(easyDifficulty));
    }
  }

  function toggleViews() {
    id("game-view").classList.toggle("hidden");
    id("menu-view").classList.toggle("hidden");
  }

  function exitGame() {
    clearInterval(timerId);
    toggleViews();
  }

  function generateRandomAttributes(isEasy) {
    let randStyle;
    if (isEasy === true) {
      randStyle = STYLE[0];
    } else {
      randStyle = STYLE[Math.floor(Math.random() * STYLE.length)];
    }
    var randShape = SHAPE[Math.floor(Math.random() * SHAPE.length)];
    var randColor = COLOR[Math.floor(Math.random() * COLOR.length)];
    var randCount = COUNT[Math.floor(Math.random() * COUNT.length)];
    var randAttributes = [randStyle, randShape, randColor, randCount];
    return randAttributes;
  }

  function generateUniqueCard(isEasy) {
    let divCards = gen('div');

    let randAttributesArray = generateRandomAttributes(isEasy);

    for (let i = 0; i < randAttributesArray[3]; i++) {
      let imgCards = gen('img');
      divCards.appendChild(imgCards);
      let imgFilePath = randAttributesArray[0] + "-" + randAttributesArray[1] + "-" +
        randAttributesArray[2];
      imgCards.src = "img/" + imgFilePath + ".png";
      imgCards.alt = randAttributesArray.join("-");
    }

    //let cardID = randAttributesArray.join("-");
    let boardChildren = qsa("#board div");

    while (id(boardChildren) == null && boardChildren.length > 0) {
      boardChildren = generateRandomAttributes(isEasy);
    }

    divCards.id = boardChildren;
    divCards.classList.add("card");
    divCards.addEventListener("click", cardSelected);

    return divCards;
  }
  
  function cardSelected() {
    console.log("selected");
    qsa(".card").classList.toggle(".selected")
  }
  
   /**
   * Returns the element that has the ID attribute with the specified value.
   * @param {string} idName - element ID
   * @returns {object} DOM object associated with id.
   */
  function id(idName) {
    return document.getElementById(idName);
  }

  /**
   * Returns the first element that matches the given CSS selector.
   * @param {string} selector - CSS query selector.
   * @returns {object} The first DOM object matching the query.
   */
  function qs(selector) {
    return document.querySelector(selector);
  }

  /**
   * Returns the array of elements that match the given CSS selector.
   * @param {string} selector - CSS query selector
   * @returns {object[]} array of DOM objects matching the query.
   */
  function qsa(selector) {
    return document.querySelectorAll(selector);
  }

  /**
   * Returns a new element with the given tag name.
   * @param {string} tagName - HTML tag name for new DOM element.
   * @returns {object} New DOM object for given HTML tag.
   */
  function gen(tagName) {
    return document.createElement(tagName);
  }
body, button, select, input {
  font-family: "Helvetica", "Verdana", sans-serif;
  text-align: center;
  font-size: 12pt;
}

main {
  width: 80%;
  margin: auto;
}

button, select {
  padding: 8px;
  background-color: white;
  border: 2pt solid black;
}

h2 {
  text-decoration: underline;
}

#start-btn {
  width: 100px;
  margin-top: 10px;
  margin-bottom: 20px;
}

#menu-view > article {
  background-color: #6F77ED;
  border-radius: 0.35em;
  border: 5pt solid black;
}

#menu-view > article, #details-bar {
  color: white;
}

.card, #details-bar, #board {
  display: flex;
  justify-content: space-evenly;
}

.card, #details-bar {
  align-items: center;
}

#details-bar {
  border-top-left-radius: 0.5em;
  border-top-right-radius: 0.5em;
  background-color: black;
  font-size: 14pt;
}

.card {
  width: 220px;
  height: 95px;
  border: 0.35em solid black;
  border-radius: 1em;
  cursor: pointer;
  margin-top: 5px;
  margin-bottom: 5px;
}

.card img {
  height: 85%;
}

.card p {
  font-weight: bold;
}

h2, .card p {
  font-size: 16pt;
}

.selected {
  box-shadow: #636363 6px 6px;
}

#board {
  border-right: black solid 5pt;
  border-left: black solid 5pt;
  border-bottom: black solid 5pt;
  padding: 20px;
  flex-wrap: wrap;
}

.hidden, .hide-imgs > img {
  display: none;
}
<html lang="en">

  <head>
    <meta charset="utf-8">
    <title>Set!</title>
    <link rel="stylesheet" href="set.css">
    <script src="set.js"></script>
  </head>

  <body>
    <header>
      <h1>Set!</h1>
    </header>

    <main>
      <section id="menu-view">
        <article>
          <h2>Choose a Timing Option:</h2>
          <select>
            <option value="60">1 Minute</option>
            <option value="180" selected>3 Minutes</option>
            <option value="300">5 Minutes</option>
          </select>

          <h2>Choose a Difficulty:</h2>
          <p>
            <label><input type="radio" name="diff" value="easy" checked> Easy</label>
            <label><input type="radio" name="diff" value="standard"> Standard</label>
          </p>

          <button id="start-btn">Start</button>
        </article>

        <section>
          <header>
            <h2>Rules</h2>
          </header>
          <p>
            Originally created by Marsha Jean Falco of Set Enterprises, Inc.,
            Set is a card game with a board of non-duplicate cards. There are two levels
            of difficulty for this game.
            In Standard
            Difficulty there are 4 different attributes (style, color, shape, and count) -
            each attribute can have one of three values. For example, shape can have 3
            values: "diamond", "oval", or "squiggle". In Easy Difficulty, all cards share a
            "solid" style attribute, so only the other 3 attributes can be different.
          </p>
          <p>
            A Set is a selection of 3 cards such that for each of attributes, all
            three cards have the same value or none of the cards have the same value.
            Your goal is to find as many Sets as you can on the board!
          </p>
          <p>Have fun!</p>
        </section>
      </section>

      <section id="game-view" class="hidden">
        <div id="details-bar">
          <button id="back-btn">Back to Main</button>
          <p><strong>Sets Found: </strong><span id="set-count">0</span></p>
          <p><strong>Time: </strong><span id="time">00:00</span></p>
          <button id="refresh-btn">Refresh Board</button>
        </div>
        <div id="board"></div>
      </section>
    </main>
  </body>

</html>

1 Ответ

0 голосов
/ 30 апреля 2020
let boardChildren = qsa("#board div");

while (id(boardChildren) == null && boardChildren.length > 0) {
  boardChildren = generateRandomAttributes(isEasy);
}

divCards.id = boardChildren;
divCards.classList.add("card");
divCards.addEventListener("click", cardSelected);

вы присваиваете значение boardChildren непосредственно id, который является объектом, а не строкой

let boardChildren = qsa("#board div");

, он вернет массив всех выбранных элементов, а также

boardChildren = generateRandomAttributes(isEasy);

это вернет массив типа объекта.

...