JavaScript игра в пары, добавление кнопки после завершения игры и ее перезапуск
Подскажите пожалуйста как обновить и запустиь корректно функцию гейм старт при условии если все пары открыты и нажата кнопка? В моем примере кода, при нажатии кнопки все дублируется как и дом дерево так и элементы:
(function () {
let cardsCount = 2;
// let cardsCount = prompt("Введите количество пар", 2);
const cardsNumberArray = []
// const game = document.getElementById("game");
let firstCard = null;
let seconCard = null;
//создание массива
function createNumbersArray(count) {
for (let i = 1; i <= count; i++) {
cardsNumberArray.push(i, i);
}
}
function shuffle(arr) {
for (let i = 0; i < arr.length; i++) {
let randomIndex = Math.floor(Math.random() * arr.length);
let temp = arr[i];
arr[i] = arr[randomIndex];
arr[randomIndex] = temp;
}
return arr;
}
function addTitle() {
const title = document.createElement("h1");
title.classList.add("mb-5");
title.style.textAlign = "center";
title.textContent = "Игра в пары";
return title;
}
function startGame(container, count) {
createNumbersArray(count);
shuffle(cardsNumberArray);
const body = document.getElementById("title");
const title = addTitle();
body.append(title);
for (const cardNumber of cardsNumberArray) {
const card = document.createElement("div");
card.textContent = cardNumber;
card.classList.add("card");
container.append(card);
card.addEventListener("click", function () {
if (card.classList.contains("open") || card.classList.contains("success")) {
return
}
if (firstCard !== null && seconCard !== null) {
firstCard.classList.remove("open");
seconCard.classList.remove("open");
firstCard = null;
seconCard = null;
}
// console.log(card);
card.classList.add("open");
if (firstCard === null) {
firstCard = card;
} else {
seconCard = card;
}
if (firstCard !== null && seconCard !== null) {
let firstCardNumber = firstCard.textContent
let secondCardNumber = seconCard.textContent
if (firstCardNumber === secondCardNumber) {
firstCard.classList.add("success");
seconCard.classList.add("success");
}
}
if (cardsNumberArray.length === document.querySelectorAll(".success").length) {
// setTimeout(function () {
// alert("Игра завершена, вы выйграли!")
// }, 400);
const gameButton = document.querySelector(".game-button");
const button = document.createElement("button");
button.textContent = "Сыграть еще раз";
gameButton.append(button);
button.addEventListener('click', (e) => {
e.preventDefault();
// document.querySelectorAll('.card').remove(card);
let cardsNumberArray = [];
// while (document.body.firstChild) {
// document.body.removeChild(document.body.firstChild);
// }
startGame(document.getElementById('game'), 2);
console.log(cardsNumberArray);
});
}
});
}
}
document.addEventListener("DOMContentLoaded", function () {
startGame(document.getElementById('game'), cardsCount);
});
})();
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
a {
color: inherit;
text-decoration: none;
}
img {
max-width: 100%;
}
body {
min-width: 320px;
font-family: "Roboto", sans-serif;
font-weight: 400;
line-height: normal;
}
/* glob */
.list-reset {
margin-block-start: 0;
margin-block-end: 0;
padding-inline-start: 0;
list-style: none;
}
.btn-reset {
padding: 0;
border: none;
background-color: transparent;
cursor: pointer;
}
.flex {
display: flex;
}
/* Начало */
.game {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
gap: 10px;
padding: 40px 15px;
max-width: 500px;
margin: 0 auto;
}
.card {
display: flex;
justify-content: center;
align-items: center;
padding: 30px;
height: 100px;
width: 100px;
border-radius: 15px;
background-color: rgb(226, 187, 137);
font-size: 0px;
color: transparent;
cursor: pointer;
transition: background-color .3s;
}
.card:hover {
background-color: rgb(241, 213, 176);
}
.card:active {
background-color: rgb(204, 159, 100);
}
.open {
font-size: 48px;
color: #fff;
background-color: #2b18d6;
transition: background-color .1s;
cursor: default;
}
.open:hover {
background-color: #2b18d6;
}
.open:active {
background-color: #2b18d6;
}
.success {
font-size: 48px;
color: #fff;
background-color: #25d618;
transition: background-color .1s;
cursor: default;
}
.success:hover {
background-color: #25d618;
}
.success:active {
background-color: #25d618;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/normalize.css">
<link rel="stylesheet" href="./css/style.css">
<title>Игра в пары</title>
<script defer src="main.js"></script>
<script>
// let cardsCount = Number(prompt("Введите количество пар", 8));
// const cardsCount = 2;
// document.addEventListener("DOMContentLoaded", function () {
// startGame(document.getElementById('game'), cardsCount);
// });
</script>
</head>
<body>
<div id="title"></div>
<div id="game" class="container game"></div>
<div class="game-button"></div>
</body>
</html>