【每日一练】212—掷骰子模拟器

每日一练8个月前发布 admin
819 0

第212练的最终效果如下:

【每日一练】212—掷骰子模拟器

实现代码:

HTML:

<!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″ />
    <title>212练-掷骰子模拟器</title>
    <link rel=”stylesheet” href=”index.css” />
  </head>
  <body>
    <h1>掷骰子模拟器</h1>
    <div class=”dice” id=”dice”>&#9860;</div>
    <button id=”roll-button”>掷骰子</button>
    <ul id=”roll-history”>
    </ul>
    <script src=”index.js”></script>
  </body>
</html>

CSS:

body {
    font-family: “Open Sans”, sans-serif;
    text-align: center;
    margin: 0;
  }
  h1 {
    font-size: 3rem;
    margin-top: 2rem;
  }
  .dice {
    font-size: 7rem;
    margin: 5px;
    animation-duration: 1s;
    animation-fill-mode: forwards;
  }
  .roll-animation {
    animation-name: roll;
  }
  @keyframes roll {
    0% {
      transform: rotateY(0deg) rotateX(0deg);
    }
    100% {
      transform: rotateY(720deg) rotateX(720deg);
    }
  }
  button {
    background-color: #47a5c4;
    color: white;
    font-size: 1.5rem;
    padding: 1rem 2rem;
    border: none;
    border-radius: 1rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  button:hover {
    background-color: #2e8baf;
  }
  ul {
    list-style: none;
    padding: 0;
    max-width: 600px;
    margin: 2rem auto;
  }
  li {
    font-size: 1.5rem;
    padding: 0.5rem;
    margin: 0.5rem;
    background-color: #f2f2f2;
    border-radius: 0.5rem;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  li span {
    font-size: 3rem;
    margin-right: 1rem;
  }

JS:

const buttonEl = document.getElementById(“roll-button”);
const diceEl = document.getElementById(“dice”);
const rollHistoryEl = document.getElementById(“roll-history”);
let historyList = [];
function rollDice() {
  const rollResult = Math.floor(Math.random() * 6) + 1;
  const diceFace = getDiceFace(rollResult);
  diceEl.innerHTML = diceFace;
  historyList.push(rollResult);
  updateRollHistory();
}
function updateRollHistory() {
  rollHistoryEl.innerHTML = “”;
  for (let i = 0; i < historyList.length; i++) {
    const listItem = document.createElement(“li”);
    listItem.innerHTML = `掷 ${i + 1}: <span>${getDiceFace(
      historyList[i]
    )}</span>`;
    rollHistoryEl.appendChild(listItem);
  }
}
function getDiceFace(rollResult) {
  switch (rollResult) {
    case 1:
      return “&#9856;”;
    case 2:
      return “&#9857;”;
    case 3:
      return “&#9858;”;
    case 4:
      return “&#9859;”;
    case 5:
      return “&#9860;”;
    case 6:
      return “&#9861;”;
    default:
      return “”;
  }
}
buttonEl.addEventListener(“click”, () => {
  diceEl.classList.add(“roll-animation”);
  setTimeout(() => {
    diceEl.classList.remove(“roll-animation”);
    rollDice();
  }, 1000);
});
© 版权声明

相关文章

暂无评论

暂无评论...