Игра "Цвета"
Всем привет. Хочу сделать игру, суть которой такова:
Есть таблица 3х3. В первый раз в ней рандомно загораются два цвета и через секунду погасают (например в 1 и 5 ячейке). Потом человек нажимает на эти два цвета, после чего загорается еще одна ячейка(например седьмая) другим цветом и человеку уже надо нажать на 1, 5 и 7 ячейки. И так далее. Так вот, пока еще и не начал ничего, но столкнулся с проблемой: не знаю, как получить рандомную ячейку и вывести в неё цвет. Вот код: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> <style type="text/css"> table td { background-color: #fff; border: 2px solid #000; width: 10vmin; height: 10vmin; } </style> </head> <body> <div class="zone"> <div id="time">0.000</div> <table> <tbody> <tr> <td id="n1"></td> <td id="n2"></td> <td id="n3"></td> </tr> <tr> <td id="n4"></td> <td id="n5"></td> <td id="n6"></td> </tr> <tr> <td id="n7"></td> <td id="n8"></td> <td id="n9"></td> </tr> </tbody> </table> </div> <script> class Timer { constructor(node, updateDelay) { this.node = node; this.updateDelay = updateDelay; } start() { this.startTime = Date.now(); this.timer = setInterval(() => { this.node.innerText = this._getFormatTime(Date.now() - this.startTime); }, this.updateDelay); this.started = true; } stop() { clearInterval(this.timer); this.started = false; return this._getFormatTime(Date.now() - this.startTime); } _getFormatTime(time) { return (time / 1000 + '').padEnd((time + '').length + 1, '0'); } } const colors = ['red','blue','green', 'yellow']; const cells = document.querySelectorAll('.zone td'); function changeCellColor{ var rand = Math.floor(Math.random() * color.length); cell.style.background=color[rand] var used += color[rand] } </script> </body> </html> Решил присвоить всем ячейкам иды от n1 до n9, и через рандом от 1 до 9 выбирать ячейки, но думаю, что у меня получится слишком много if'ов, и есть способ полегче. Не могли бы помочь? |
Цитата:
|
s4meone,
let randomIndex = Math.floor(Math.random() * cellNodeList.length); let randomCell = cellNodeList.item(randomIndex); cellNodeList.forEach(cell => cell.addEventListener('click', onClick)); function onClick() { let clickedСell = this; // ... } |
Часовой пояс GMT +3, время: 05:51. |