Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Задача с цветами (https://javascript.ru/forum/events/77547-zadacha-s-cvetami.html)

fillika 18.05.2019 17:47

Задача с цветами
 
Ребята привет! Есть идеи, как решить такую задачу: есть поле, 4х4, есть кнопка начала игры. Когда мы нажимаем на кнопку старт, то у нас запускается таймер и генерируется 8 пар случайных цветов, но мы их пока не видим. Нажимая на клетку, цвет отображается. Нажав на вторую клетку мы получаем еще один цвет. Если они совпадают - то они остаются, если нет - скрываются. Задача: найти все цвета. Как только все цвета будут найдены, выходит alert с отображением времени(сколько потратили, чтобы найти все цвета).
Сам новичок, застрял на этой задаче. Смог только составить цикл, который присваивает цвета (присваивал по rgb, чтобы палитра больше была).
Не могу сообразить, как связать ячейки и задать ограничение по цветам, чтобы они: Во-первых, получить 8 пар одинаковых, во-вторых, в случайных ячейках, в третьих, чтобы по клику они отображались и исчезали, если не угадал (с исчезанием думал сделать через opacity, но опять же, не знаю, как связать ячейки)
Буду благодарен за подсказки

рони 18.05.2019 18:58

fillika,
игра открыть пару

fillika 20.05.2019 19:47

Спасибо. Нашел похожее, там не совсем то, что мне нужно было, но Я разберусь.)

рони 25.05.2019 00:19

игра открыть пару
 
fillika,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
   .show div{
      width: 60px;
      height: 60px;
      border: 1px solid #6e6d70;
      box-sizing: border-box;
      text-align: center;
      line-height: 60px;
      transition: .8s;
   }
   .show {
       display: flex;
       flex-wrap: wrap;
       width: 240px;
   }
   .show.end div{
       color: transparent;
       border-radius: 50%;
   }

  </style>

</head>

<body>
<div class="show"></div>
<button>new</button>
<script>
class field {
    constructor(pair, parentCls) {
        this.cls = parentCls;
        this.parent = document.querySelector(this.cls);
        this.pair = pair;
        this.elems = this.createElems(this.pair * 2);
        this.color = this.createColor(this.pair);
        this.parent.append(...this.elems);
        this.shuffleArray(this.elems);
        this.parent.addEventListener("pointerdown", this.eventHandler.bind(this));
        this.timer = null;
        this.current = null;
        this.duration = 1000;
        this.init.bind(this);
    }
    createElems(length) {
        let elems = Array.from({length}, () => document.createElement("div"));
        return elems
    }
    createColor(length) {
        let color = Array.from({length}, (v, k) => `hsl(${360 * Math.random()|0}, 100%, 50%)`)
        return color
    }
    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    eventHandler(event) {
        event.preventDefault();
        const target = event.target.closest(this.cls + ">div");
        if (!target || target.classList.contains("ok")) return;
        let index = (this.elems.indexOf(target) / 2) | 0;
        target.style.backgroundColor = this.color[index];
        target.textContent = index;
        window.clearTimeout(this.timer);
        target.classList.add("ok");
        if (this.current) {
            if (this.current.textContent == target.textContent) {
                this.current = null;
                --this.pair || this.parent.classList.add("end");

            } else {
                this.clearItem(this.current);
                this.current = target;
            }
        } else this.current = target;
        if (this.current) this.timer = window.setTimeout(() => {
            this.clearItem(this.current);
            this.current = null;
        }, this.duration);
    }
    clearItem(item){
      item.classList.remove("ok");
      item.style.backgroundColor = "";
      item.textContent = "";
      return item
    }

    init(){
       this.pair = this.color.length;
       this.color = this.createColor(this.pair);
       this.shuffleArray(this.elems);
       this.elems.forEach(this.clearItem);
       this.parent.classList.remove("end");
    };


}
const game = new field(8, ".show");
document.querySelector("button").addEventListener("click", () => game.init())
</script>
</body>
</html>


Часовой пояс GMT +3, время: 20:49.