随机元素在再次播放按钮中不起作用

问题描述 投票:0回答:1

这是一个更高或更低的游戏,用户根据难度猜测哪个车手的统计数据更高或更低。再次播放按钮是问题所在。我想要的是,当用户在游戏结束时再次按下播放按钮时,它应该选择 2 个随机驱动程序,而不是像我的代码那样从上一场游戏中选择相同的两个驱动程序。我想这只是一个小问题,但我看不出有什么问题。

// Define F1 driver data
const f1Drivers = [{
    name: 'Lewis Hamilton',
    wins: 103,
    podiums: 192,
    points: 4443.5
  },
  {
    name: 'Michael Schumacher',
    wins: 91,
    podiums: 155,
    points: 1566
  },
  {
    name: 'Sebastian Vettel',
    wins: 53,
    podiums: 122,
    points: 3098
  },
  {
    name: 'Alain Prost',
    wins: 51,
    podiums: 106,
    points: 798.5
  },
  {
    name: 'Ayrton Senna',
    wins: 41,
    podiums: 80,
    points: 614
  },
  {
    name: 'Nigel Mansell',
    wins: 31,
    podiums: 59,
    points: 482
  },
  {
    name: 'Jim Clark',
    wins: 25,
    podiums: 32,
    points: 274.5
  },
  {
    name: 'Juan Manuel Fangio',
    wins: 24,
    podiums: 35,
    points: 277.64
  },
  {
    name: 'Niki Lauda',
    wins: 25,
    podiums: 54,
    points: 420.5
  },
  {
    name: 'Jack Brabham',
    wins: 14,
    podiums: 31,
    points: 261
  },
  {
    name: 'Fernando Alonso',
    wins: 32,
    podiums: 101,
    points: 2106
  },
  {
    name: 'Max Verstappen',
    wins: 37,
    podiums: 80,
    points: 2080.5
  },
  {
    name: 'Nico Rosberg',
    wins: 23,
    podiums: 57,
    points: 1594.5
  },
  {
    name: 'Kimi Raikkonen',
    wins: 21,
    podiums: 103,
    points: 1873
  },
  {
    name: 'Mika Hakkinen',
    wins: 20,
    podiums: 51,
    points: 420
  },
  {
    name: 'Jenson Button',
    wins: 15,
    podiums: 50,
    points: 1235
  },
  {
    name: 'Jackie Stewart',
    wins: 27,
    podiums: 43,
    points: 359
  },
  {
    name: 'Damon Hill',
    wins: 22,
    podiums: 42,
    points: 360
  },
  {
    name: 'Felipe Massa',
    wins: 11,
    podiums: 41,
    points: 1167
  },
  {
    name: 'Valtteri Bottas',
    wins: 10,
    podiums: 67,
    points: 1791
  },
  {
    name: 'Mark Webber',
    wins: 9,
    podiums: 50,
    points: 1235
  },
  {
    name: 'Daniel Ricciardo',
    wins: 8,
    podiums: 32,
    points: 1311
  },
  {
    name: 'Charles Leclerc',
    wins: 5,
    podiums: 24,
    points: 874
  },
  {
    name: 'Sergio Perez',
    wins: 5,
    podiums: 28,
    points: 1255
  },
];

// Get HTML elements
const difficultySelect = document.getElementById('difficulty-select');
const startGameButton = document.querySelector('button');
const gameContainer = document.getElementById('game-container');
const higherButton = document.getElementById('higher-button');
const lowerButton = document.getElementById('lower-button');
const resultContainer = document.getElementById('result-container');
const playAgainButton = document.getElementById('play-again-button');
const frontImage = document.getElementById('bikar');
const easy = document.getElementById('easy_level');
const normal = document.getElementById('normal_level');
const hard = document.getElementById('hard_level');
const diff = document.getElementById('diff-text');



let currentDriverIndex;
let previousDriverIndex;
let currentDifficulty;
let score;


// Add event listener to the "Start Game" button
startGameButton.addEventListener('click', startGame);

function startGame() {
  startGameButton.style.display = 'none'
  frontImage.style.display = 'none';
  easy.style.display = 'none';
  normal.style.display = 'none';
  hard.style.display = 'none';
  difficultySelect.style.display = 'none'
  diff.style.display = 'none'


  currentDifficulty = difficultySelect.value;

  // Show the type of data to be guessed by the user
  const dataTypeElement = document.getElementById('data-type');
  if (currentDifficulty === 'easy') {
    dataTypeElement.textContent = 'Guess the driver with more wins';
  } else if (currentDifficulty === 'normal') {
    dataTypeElement.textContent = 'Guess the driver with more podiums';
  } else if (currentDifficulty === 'hard') {
    dataTypeElement.textContent = 'Guess the driver with more points';
  }

  higherButton.addEventListener('click', onHigherButtonClicked);
  lowerButton.addEventListener('click', onLowerButtonClicked);

  score = 0;

  // Hide the result container and play again button
  resultContainer.textContent = '';
  playAgainButton.style.display = 'none';

  // Show the first driver
  showNextDriver();
}


function onHigherButtonClicked() {
  checkAnswer('higher');
}

function onLowerButtonClicked() {
  checkAnswer('lower');
}

let lastDriverIndex;

function showNextDriver() {
  // Clear the previous driver's data
  gameContainer.innerHTML = '';

  // Pick two random drivers from the list
  if (!currentDriverIndex) {
    currentDriverIndex = getRandomDriverIndex();
  }

  if (!previousDriverIndex) {
    previousDriverIndex = getRandomDriverIndex(currentDriverIndex);
  }

  // Create and append elements to display the two drivers and their data
  const currentDriverElement = document.createElement('div');
  const previousDriverElement = document.createElement('div');
  const currentDriverDataElement = document.createElement('ul');
  const previousDriverDataElement = document.createElement('ul');
  const vsElement = document.createElement('div');

  currentDriverElement.classList.add('driver');
  previousDriverElement.classList.add('driver');
  vsElement.textContent = "Vs";

  currentDriverElement.innerHTML = `
          <h2>${f1Drivers[currentDriverIndex].name}</h2>
          <img src="driver-images/${f1Drivers[currentDriverIndex].name.toLowerCase().replace(' ', '-')}.png">
        `;
  previousDriverElement.innerHTML = `
          <h2>${f1Drivers[previousDriverIndex].name}</h2>
          <img src="driver-images/${f1Drivers[previousDriverIndex].name.toLowerCase().replace(' ', '-')}.png">
        `;

  currentDriverElement.appendChild(currentDriverDataElement);
  previousDriverElement.appendChild(previousDriverDataElement);
  gameContainer.appendChild(currentDriverElement);
  gameContainer.appendChild(vsElement);
  gameContainer.appendChild(previousDriverElement);

  // Show the "Higher or Lower" buttons
  const buttonContainer = document.getElementById('button-container');
  buttonContainer.style.display = 'block';
}

function getRandomDriverIndex(excludeIndex) {
  let index;
  do {
    index = Math.floor(Math.random() * f1Drivers.length);
  } while (index === excludeIndex);
  return index;
}


function checkAnswer(guess) {
  const previousDriver = f1Drivers[previousDriverIndex];
  const currentDriver = f1Drivers[currentDriverIndex];
  let previousData, currentData;
  if (currentDifficulty === 'easy') {
    previousData = previousDriver.wins;
    currentData = currentDriver.wins;
  } else if (currentDifficulty === 'normal') {
    previousData = previousDriver.podiums;
    currentData = currentDriver.podiums;
  } else if (currentDifficulty === 'hard') {
    previousData = previousDriver.points;
    currentData = currentDriver.points;
  }

  const answerIsCorrect =
    (guess === 'higher' && currentData <= previousData) ||
    (guess === 'lower' && currentData >= previousData);


  if (answerIsCorrect) {
    score++;
    currentDriverIndex = previousDriverIndex;
    previousDriverIndex = null;
    showNextDriver();
  } else {
    endGame();
  }
}


function endGame() {
  // Remove event listeners from the buttons
  higherButton.removeEventListener('click', onHigherButtonClicked);
  lowerButton.removeEventListener('click', onLowerButtonClicked);

  let message = "";
  if (score <= 1) {
    const messages = [
      "You may need to get a new pit crew - they're clearly not feeding you the right information!",
      "That answer is a bit like a car stuck in the gravel trap - not quite what we were hoping for!",
      "Looks like you need to spend less time watching the races and more time studying the history books!",
      "Looks like you need some more practice laps before you get the hang of this."
    ];
    const randomIndex = Math.floor(Math.random() * messages.length);
    message = `${messages[randomIndex]} ${message}`;
  } else if (score <= 4) {
    const messages = [
      "Let's just say, if you were driving in the F1, you'd be lapped by now.",
      "Very Bad - You might want to stick to bumper cars!",
      "Don't worry, even the best drivers have their off days. Maybe you'll do better next time.",
      "Well, that answer was definitely not pole position material."
    ];
    const randomIndex = Math.floor(Math.random() * messages.length);
    message = `${messages[randomIndex]} ${message}`;
  } else if (score <= 10) {
    const messages = [
      "You're like a midfield driver - solid, but not quite podium material.",
      "You're doing okay, but maybe you should watch a few more races before playing again.",
      "You're not exactly setting the track on fire, but you're not stalling out either.",
      "Not bad, not bad at all! You're definitely on the right track to becoming an F1 expert."
    ];
    const randomIndex = Math.floor(Math.random() * messages.length);
    message = `${messages[randomIndex]} ${message}`;
  } else {
    const messages = [
      "I think we need to do a doping test on you because that score is unreal!",
      "Congratulations! You just set a new lap record for F1 trivia. Absolutely amazing!",
      "Wow, you're like the Lewis Hamilton of F1 trivia! Impressive!",
      "Hold on, let me check if you're not secretly connected to the FIA. Your knowledge is on another level!"
    ];
    const randomIndex = Math.floor(Math.random() * messages.length);
    message = `${messages[randomIndex]} ${message}`;
  }

  // Display the user's score and message
  resultContainer.textContent = `Game over! You got ${score} correct. ${message}`;
  playAgainButton.style.display = 'block';
  playAgainButton.addEventListener('click', startGame);
}
.home {
  color: black;
  /* Change the color to black */
  text-decoration: none;
  /* Remove the underline */
}

body {
  background-color: #adadad;
}

#difficulty-select {
  width: 120px;
  height: 30px;
  border: 1px solid #999;
  font-size: 18px;
  color: #1c87c9;
  background-color: #eee;
  border-radius: 5px;
  box-shadow: 4px 4px #ccc;
}

title {
  text-align: center;
}

.info {
  display: none;
  text-align: center;
  top: 5;
}

.icon:hover~.info {
  display: block;
}

#info-hover {
  width: 4%;
  position: absolute;
  top: 4;
  right: 1;
}


/* Style the header */

header {
  background-color: #fff;
  color: rgb(0, 0, 0);
  padding: 10px;
  display: flex;
  justify-content: space-between;
}


/* Style the game container */

#game-container {
  margin: 20px;
  font-size: 24px;
  text-align: center;
}


/* Style the button container */

#button-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}


/* Style the result container */

#result-container {
  font-size: 24px;
  text-align: center;
}

#start-game-button {
  margin: 0;
  position: absolute;
  top: 15%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}


/* Style the footer */

footer {
  background-color: #333;
  color: white;
  padding: 10px;
  text-align: center;
  position: fixed;
  bottom: 0;
  width: 100%;
}


/* Style the "Higher" and "Lower" buttons */

button {
  font-size: 24px;
  margin: 0 10px;
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #005eff;
  color: white;
  cursor: pointer;
}

#button-container {
  margin: 0;
  position: absolute;
  top: 70%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#play-again-button {
  margin: 0;
  position: absolute;
  top: 90%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#resault-container {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}


/* Style the selected difficulty option */

#difficulty option:checked {
  background-color: #4CAF50;
  color: white;
}

.home {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}

.title {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
  font-size: 4em;
}

#easy_level {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
  font-size: 3em;
}

#normal_level {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
  font-size: 3em;
}

#hard_level {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
  font-size: 3em;
}

#data-type {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}

#bikar {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 40%;
}

#higher-button {
  background-color: #4CAF50;
}

#lower-button {
  background-color: #ff0000;
}

#game-container {
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}

* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 62.5%;
}

.wrapper {
  width: 100%;
  height: 10vh;
  background-color: #262626;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}

.follow,
.menu-link {
  font-size: 2rem;
  font-weight: 600;
  color: #fff;
  text-transform: uppercase;
  letter-spacing: 0.1rem;
  margin-right: 4rem;
}

.follow {
  pointer-events: auto;
}

.menu {
  display: flex;
  align-items: center;
  cursor: pointer;
  pointer-events: none;
}

.menu:hover {
  pointer-events: auto;
}

.car {
  width: 10rem;
  height: 7rem;
  margin-right: 5rem;
  position: relative;
  animation-name: drive;
  animation-duration: 2s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.car::after {
  content: "";
  position: absolute;
  width: 0;
  height: 100%;
  background-color: #fff;
  transition: width 1s;
}

.menu:hover .car::after {
  width: 100%;
}

.nav-menu {
  display: flex;
}

.menu-link {
  text-decoration: none;
  position: relative;
  top: 5rem;
  opacity: 0;
  padding: 0.5rem;
  border-radius: 0.5rem;
}

.menu:hover .menu-link {
  top: 0;
  opacity: 1;
}

.menu-link:nth-child(1) {
  transition: top 0.5s 0.1s, opacity 0.5s 0.1s, background-color 0.3s;
}

.menu-link:nth-child(2) {
  transition: top 0.5s 0.2s, opacity 0.5s 0.2s, background-color 0.3s;
}

.menu-link:nth-child(3) {
  transition: top 0.5s 0.3s, opacity 0.5s 0.3s, background-color 0.3s;
}

.menu-link:nth-child(4) {
  transition: top 0.5s 0.4s, opacity 0.5s 0.4s, background-color 0.3s;
}

.menu-link:nth-child(5) {
  transition: top 0.5s 0.5s, opacity 0.5s 0.5s, background-color 0.3s;
}

.menu-link:nth-child(1):hover {
  background-color: #000000;
}

.menu-link:nth-child(2):hover {
  background-color: #000000;
}

.menu-link:nth-child(3):hover {
  background-color: #000000;
}

.menu-link:nth-child(4):hover {
  background-color: #000000;
}

.menu-link:nth-child(5):hover {
  background-color: #cd201f;
}

.car-move {
  animation-name: move-car;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-fill-mode: forwards;
}

.car {
  width: 10rem;
  height: 7rem;
  margin-right: 5rem;
  position: relative;
  animation-name: drive;
  animation-duration: 2s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

@keyframes drive {
  0% {
    transform: translateX(100);
  }
  50% {
    transform: translateX(50px);
  }
  51% {
    transform: translateX(50px);
  }
  100% {
    transform: translateX(0);
  }
}

.follow:hover+.car {
  animation-name: move-car;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-fill-mode: forwards;
}

.car {
  opacity: 0;
  transition: opacity 0.5s;
}

.menu:hover .car {
  opacity: 1;
}

.home {
  color: white;
  /* Change the color to black */
  text-decoration: none;
  /* Remove the underline */
  align-items: left;
}

.follow {
  font-size: 5em !important;
}

header {
  width: 100%;
  padding: 0;
}

.contact {
  display: flex;
  justify-content: center;
  background-color: #262626;
  padding: 10px 0;
  position: fixed;
  bottom: 0;
  width: 100%;
}

#contact {
  color: #fff;
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}

#privacy {
  color: #fff;
  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}
<header>
  <div class="wrapper">
    <h1>
      <a style="justify-content: left; font-size: 2em;" class="home" href="index.html">
        &nbsp;  &nbsp; Formula1
        </a>
    </h1>
    <div class="menu">
      <div class="nav-menu">
        <a href="higher_or_lower.html" class="menu-link">Higher or Lower</a>
        <a href="guess_driver_path.html" class="menu-link">Guess Drivers Path</a>
        <a href="rankings.html" class="menu-link">Standings</a>
        <a href="chat.html" class="menu-link">Chat</a>
      </div>
      <img src="rotate.png" class="car" />
      <div class="follow">
        &equiv;
      </div>
    </div>
  </div>
</header>

<head>
  <title>Higher or Lower F1 Game</title>
  <link rel="stylesheet" type="text/css" href="higher_or_lower.css">
</head>

<body>
  <header>
    <h1 class="title">Higher or Lower F1 Game</h1>

    <button id="start-game-button">Start Game</button>
  </header>
  <label id="diff-text" for="difficulty-select" style="text-align: center;  font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif; font-size: 3em;">Choose difficulty level:</label>
  <select id="difficulty-select">
    <option value="easy">Easy</option>
    <option value="normal">Normal</option>
    <option value="hard">Hard</option>
  </select>
  <div class="icon"><img id="info-hover" src="info.png"></div>
  <div class="info" style="font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif; font-size: 3em;">Guess if the driver below has more wins/podiums/points</div>
  <h2 id="easy_level" style="text-align:center">Easy: Higher or Lower Wins</h2>
  <h2 id="normal_level" style="text-align:center">Normal: Higher or Lower Podiums</h2>
  <h2 id="hard_level" style="text-align:center">Hard: Higher or Lower Points</h2>
  <img id="bikar" src="bikar.png">
  <main>
    <div id="data-type" style="text-align:center; font-size: 3em;"></div>
    <div id="game-container" style="font-size: 4em;">
      <!--<img id="driver-images" src="driver-images">-->
      <!-- Display F1 driver data here -->
    </div>
    <div id="button-container" style="display: none;">
      <button id="higher-button">Higher</button>
      <button id="lower-button">Lower</button>
    </div>
    <div id="result-container" style="font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;  position: relative; top: 150px;">
      <!-- Display game result here -->
    </div>
    <button id="play-again-button" style="display:none">Play Again</button>
  </main>
  <!--<footer>
      <p>Created by Kristjan Jakob</p>
    </footer>-->
  <div class="contact">
    <h1><a id="contact" href="mailto:">Contact</a></h1>
    &nbsp; &nbsp; &nbsp;
    <h1><a id="privacy" href="...">Privacy</a></h1>
  </div>

javascript
1个回答
0
投票

问题是当

currentDriverIndex
previousDriverIndex
为空时,您只选择新的驱动程序。
startGame()
需要在调用之前重置这些变量
showNextDriver()
.

function startGame() {
  startGameButton.style.display = 'none'
  frontImage.style.display = 'none';
  easy.style.display = 'none';
  normal.style.display = 'none';
  hard.style.display = 'none';
  difficultySelect.style.display = 'none'
  diff.style.display = 'none'


  currentDifficulty = difficultySelect.value;

  // Show the type of data to be guessed by the user
  const dataTypeElement = document.getElementById('data-type');
  if (currentDifficulty === 'easy') {
    dataTypeElement.textContent = 'Guess the driver with more wins';
  } else if (currentDifficulty === 'normal') {
    dataTypeElement.textContent = 'Guess the driver with more podiums';
  } else if (currentDifficulty === 'hard') {
    dataTypeElement.textContent = 'Guess the driver with more points';
  }

  higherButton.addEventListener('click', onHigherButtonClicked);
  lowerButton.addEventListener('click', onLowerButtonClicked);

  score = 0;

  // Hide the result container and play again button
  resultContainer.textContent = '';
  playAgainButton.style.display = 'none';

  // Show the first driver
  currentDriverIndex = previousDriverIndex = null;
  showNextDriver();
}

此外,您的测试

if (!currentDriverIndex)
不是测试变量是否未设置的好方法。
0
是一个有效的数组索引,但这是错误的,所以它会选择一个不同的驱动程序。将其更改为
if (currentDriverIndex === null)
(并对
previousDriverIndex
测试执行相同的操作)。

© www.soinside.com 2019 - 2024. All rights reserved.