игра собери по порядку
Борис К,
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600&display=swap'); .color { background-color: var(--color); width: 200px; height: 100px; text-align: center; line-height: 100px; } .color:after { display: block; content: var(--txt); color: #FFFFFF; font-size: 48px; font-family: 'Playfair Display', serif; } </style> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function() { let temp = []; let form = document.querySelector(".game"); let tds = Array.from(form.querySelectorAll(".color")); let colors = "#FF0000|#008000|#0000CD".split("|"); let txts = "Hello|Java|script".split("|"); let win; function show() { tds.forEach(td => { let i = td.dataset.id; td.style.setProperty("--color", colors[i]); td.style.setProperty("--txt", `"${txts[i]}"`); }); } function randomId() { win = false; temp = []; let length = colors.length; let ids = Array.from({ length }, (v, i) => i); ids.forEach((_, i) => { let a = Math.trunc(Math.random() * length); [ids[i], ids[a]] = [ids[a], ids[i]]; }); tds.forEach(({ dataset }, i) => dataset.id = ids[i]); show(); } randomId() function exch(event) { if (win) return; let td = event.target.closest(".color"); if (td) { let cellIndex = td.cellIndex; let rowIndex = td.closest("tr").rowIndex; if (temp.length) { let x = Math.abs(cellIndex - temp[1]); let y = Math.abs(rowIndex - temp[2]); if ((x == 0 && y == 1) || (x == 1 && y == 0) || td === temp[0]) { [td.dataset.id, temp[0].dataset.id] = [temp[0].dataset.id, td.dataset.id]; show(); temp = []; } } else { temp = [td, cellIndex, rowIndex]; } win = tds.every(({ dataset: { id } }, i) => id == i); if (win) alert("Hello JavaScript!"); } } form.addEventListener("click", exch); }); </script> </head> <body> <div class="block"> <form class="game"> <table align="center" cellspacing="0" cellpadding="0"> <tr> <td class="color"></td> <td class="color"></td> <td class="color"></td> </tr> </table> </form> </div> </body> </html> |
Огромная благодарность за понимание, гениальный Рони!
Круто... очень круто!!! С наступающим Старым Новым годом, Профессионал!))) P.S. Уже есть по коду вопросы, но я ещё не решаюсь их задать... пока поэкспериментирую самостоятельно. :write: |
:help:
Рони, а вообще возможно реализовать так, чтобы кроме 30-ой строки (let txts = "Hello|Java|script".split("|");) в вашем последнем коде, была бы, например, ещё такая - let txts = "Good|morning|forum".split("|");... ну, и соответственно, чтобы под это было alert("Good morning forum!");? И чтобы кнопкой можно было менять текстовые сообщения с их обновлением без перезагрузки страницы... P.S. Я самостоятельно за четверо суток не справился. :cray: |
Борис К,
не понимаю. |
Рони, если бы была не одна фраза для сборки, а несколько, которые сменялись бы рандомно кнопкой, и, соответственно, alert был бы каждый раз другой под свою фразу...
|
Борис К,
кнопку, массив фраз, элемент для вывода сообщения, набросайте, пожалуйста...:( |
Цитата:
Цитата:
Цитата:
Good morning forum Roney good luck)) Цитата:
для out.append("Hello Java script"); out.append("Good morning forum"); out.append("Roney good luck"); P.S. Надеюсь, правильно Вас понял. |
Борис К,
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600&display=swap'); body { background-color: #D3D3D3 } .block { background-color: var(--color); text-align: center; line-height: 100px; margin: var(--rip); flex-basis: calc(100% / var(--cols) - var(--rip) * 2); font-family: 'Playfair Display', serif; color: #FFFFFF; font-size: 48px; } .out:after { content: var(--snippet); } .btn:after { content: "init"; } .game { display: flex; flex-wrap: wrap; --cols: 3; --gap: 2px; --rip: calc(var(--gap) - 1px); padding: var(--gap); } .game { width: 700px; margin: 40px auto; } .win .block { background-image: linear-gradient(45deg, rgba(255, 255, 255, .0) 50%, rgba(255, 255, 255, .8), rgba(255, 255, 255, .0) 70%), radial-gradient(190% 100% at 50% 0%, rgba(255, 255, 255, .7) 0%, rgba(255, 255, 255, .5) 50%, rgba(0, 0, 0, 0) 50%); box-sizing: border-box; background-position: 200% 0, 0 0; box-shadow: rgba(0, 0, 0, .3) 0 2px 5px; background-repeat: no-repeat; background-size: 200% 100%, auto; animation: anim 3s linear infinite; } @keyframes anim { from { background-position: 200% 0, 0 0; } to { background-position: -200% 0, 0 0; } } </style> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function() { let snippets = `Hello Java script ! 1 2 3 4 5 6 7 8 9 10 11 12 Good morning forum Roney good luck`.split(/\n/); let colors = [ '#0000FF', //blue '#FFFF00', //yellow '#008000', //green '#FFA500', // orange '#FF0000', //red '#800080', //purple '#808000', //olive '#00FF00', //lime '#800000', //maroon '#00FFFF', //aqua '#008080', //team '#000080', //navy '#FF00FF', //fushua '#808080' //gray ]; let out = document.querySelector(".out"); let btn = document.querySelector(".btn") let game = document.querySelector(".game"); let win = _ => true; let temp = []; let cols = 3; function shuffle(array, elem) { let length = array.length, arr = array.slice(0); const randomIndex = _ => Math.trunc(Math.random() * length); let k = randomIndex(); if (elem) return arr[k]; arr.forEach((_, i) => { k = randomIndex(); [arr[i], arr[k]] = [arr[k], arr[i]]; }); return arr; } // rule let [a, b] = [0, 1]; function rule(x, y) { return a == x && b == y } function exch(event) { if (win()) return; let block = event.target.closest(".block"); if (block) { let i = block.style.order; let [c, d] = [i % cols, i / cols | 0]; if (temp.length) { let x = Math.abs(c - temp[1]); let y = Math.abs(d - temp[2]); if (x > y)[x, y] = [y, x]; let move = rule(x, y); if (move || block === temp[0]) { [block.style.order, temp[0].style.order] = [temp[0].style.order, block.style.order]; temp = []; } } else { temp = [block, c, d]; }; win() } } game.addEventListener("click", exch); function createContent() { if (!win()) return; temp = []; let snippet = shuffle(snippets, true).trim(); let words = snippet.split(/\s+/); let len = words.length; cols = len > 5 ? 3 : len; let bgColor = shuffle(colors); out.style.setProperty("--snippet", `"collect ${snippet}"`); let div = document.createElement('div'); div.classList.add('block'); let content = words.map((word, i) => { let elem = div.cloneNode(); elem.textContent = word; elem.style.setProperty("--color", bgColor[i % bgColor.length]); return elem; }); shuffle(content).forEach(({ style }, i) => style.order = i); game.classList.remove("win") game.innerHTML = ""; game.style.setProperty("--cols", cols); game.append(...content); win = _ => { let validate = content .every(({ style: { order } }, i) => order == i); if (validate) { out.style.setProperty("--snippet", `"${snippet} right!!! More? click init"`); game.classList.add("win") } return validate } } btn.addEventListener("click", createContent); createContent() }); </script> <title></title> </head> <body> <p class="out"></p> <div class="game"></div> <button class="btn"></button> </body> </html> |
"Я влюбился в программиста
За его талант - так быстро Рони создал чудо-код, Аж душа моя поёт!" © Борис К. :dance: |
Рони, сдаюсь!(((
Возможно ли сделать так, чтобы ячейки располагались просто одна под другой? А чтобы текст в одной ячейке состоял из двух слов, например, "turn on"? P.S. Я самостоятельно за несколько суток решение так и не нашёл((((( |
Часовой пояс GMT +3, время: 01:13. |