Home  >  Article  >  Web Front-end  >  JavaScript implements 24 o'clock

JavaScript implements 24 o'clock

王林
王林Original
2023-05-09 10:32:07788browse

Blackjack is a fun card game designed to count 4 cards to the number 24. In this article, we will introduce how to implement the 24-point game in JavaScript.

Step 1: Set up the game interface

First, we need to set up the game interface. Here is the required HTML and CSS code:

<!DOCTYPE html>
<html>
  <head>
    <title>24点游戏</title>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        text-align: center;
      }
      h1 {
        margin-top: 50px;
        margin-bottom: 30px;
      }
      #card {
        font-size: 100px;
        margin: 50px 0;
      }
      button {
        padding: 10px 20px;
        font-size: 20px;
        margin-left: 10px;
      }
    </style>
  </head>
  <body>
    <h1>欢迎来玩24点游戏</h1>
    <div id="card"></div>
    <button onclick="generateCards()">发牌</button>
    <button onclick="check24()">验证</button>
    <script src="game.js"></script>
  </body>
</html>

In this code, we define the page title, styles, and game interface elements. In the card block we will display 4 random playing cards in text form.

Step 2: Generate random cards

Now, we need to write a function to generate 4 random playing cards. To achieve this, we need to create an array containing all playing cards and select 4 from them. Here is the required JavaScript code:

const suits = ["spades", "hearts", "diamonds", "clubs"];
const values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

function generateCards() {
  let cards = "";
  for (let i = 0; i < 4; i++) {
    let suit = suits[Math.floor(Math.random() * suits.length)];
    let value = values[Math.floor(Math.random() * values.length)];
    cards += `<span class="${suit}">${value}</span>`;
  }
  document.getElementById("card").innerHTML = cards;
}

In the above code, we have created two arrays, one containing all the suits and the other containing all the denominations. We then use the Math.random() function and the array length to select a random suit and denomination. Finally, we create a card using these values ​​in an HTML string. This function executes the above 4 loops to generate 4 random cards.

Step 3: Verify compliance

Now, we need to write a function to check if 24 can be calculated using 4 cards. This function requires us to use recursion to simulate the rules of the 24-point game. Here is the required JavaScript code:

function check24(nums) {
  if (!nums) {
    nums = Array.from(document.querySelectorAll("#card span")).map(span => span.innerHTML);
  }
  if (nums.length === 1) {
    return nums[0] === "24";
  }
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      let a = nums[i], b = nums[j], c = "";
      for (let k = 0; k < nums.length; k++) {
        if (k !== i && k !== j) {
          c += nums[k] + ",";
        }
      }
      for (let k = 0; k < 4; k++) {
        let newNums = c.split(",");
        newNums.splice(k, 0, eval(`${a}${operators[k]}${b}`));
        if (check24(newNums)) {
          return true;
        }
      }
    }
  }
  return false;
}

The function takes a num array as parameter. If no array is provided, the function will get a random array from the block of cards. If the array length is 1, the function returns true if its value is equal to 24, otherwise it returns false.

Otherwise, the function will loop over the two numbers and simulate each operation and call itself recursively until a solution is found or there is no feasible solution. Returns true if a solution is found, false otherwise.

Step 4: Processing Operators

Now, we need to create an array of operators and combine it with numbers. The following is the required JavaScript code:

const operators = ["+", "-", "*", "/"];
const operatorFunctions = [
  (a, b) => a + b,
  (a, b) => a - b,
  (a, b) => a * b,
  (a, b) => a / b,
];

function check24(nums) {
  // ...
  for (let k = 0; k < 4; k++) {
    let newNums = c.split(",");
    newNums.splice(k, 0, operatorFunctions[k](parseFloat(a), parseFloat(b)).toString());
    if (check24(newNums)) {
      return true;
    }
  }
  // ...
}

In the above code, we create an array of operators and a corresponding array of operator functions. We then use the parseFloat() function to convert the string number to a number and calculate the result using the corresponding operator function. Finally, we append the result as a string to a new array and call itself recursively to try the solution.

Step 5: Present the results to the player

Finally, we need to present the results to the player. The following is the required JavaScript code:

function check24() {
  // ...
  if (check24(nums)) {
    alert("恭喜你,成功啦!");
  } else {
    alert("很抱歉,再试一次吧...");
  }
}

In the above code, if a feasible solution is found, the "Congratulations, it worked!" message box will be displayed, otherwise it will be displayed "Sorry, try again Let's..." message box.

Summary

Now, we have provided a complete solution for JavaScript to implement the 24-point game. By using the above techniques, you can create a simple and fun game that allows users to test their math skills. Additionally, you can use such techniques to create other interesting games, such as text adventures and puzzle games.

The above is the detailed content of JavaScript implements 24 o'clock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:css flip toggleNext article:css flip toggle