You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS新手求助:如何让RPG全局变量每次点击Travel按钮更新值?

Fixing Global Variable Updates for Your Text RPG

Hey there! I see the issue you're running into—your global variables are only getting set once, instead of updating every time you click the Travel button. Let's break down how to fix this while keeping your HP (and other needed values) accessible to both travel() and attack().

The Root Problem

When you declare variables like happened or enemie outside the travel() function but don't reassign them inside the function, they only get their initial random value once. Every subsequent click just uses that original value instead of generating a new one.

Step-by-Step Solution

  1. Declare global variables (without initializing them) outside all functions. This lets both travel() and attack() access them.
  2. Reassign these variables inside travel() every time the button is clicked. This ensures fresh random values on each Travel action.
  3. Tweak the pickEnemie() function to only generate an enemy when an attack event occurs (no need for enemies when nothing happens!).
  4. Fix the enemieData() return value—it's currently returning an array, but we just need the raw number for HP.

Full Corrected Code

JavaScript

// Global variables - accessible to travel() and attack()
let happened;
let enemie;
let enemyHP;

function travel() {
  // Reassign global variables with fresh values on every click
  happened = pickEvent();
  enemie = pickEnemie(happened);
  
  console.log("______---------You traveled 3 miles---------______");
  console.log(happened);

  if (happened === "You are under attack:") {
    console.log(enemie);
    // Get raw HP value instead of array
    enemyHP = enemieData(enemie, "hp");
    console.log(`Enemy HP: ${enemyHP}`);
    
    // Toggle button visibility
    document.getElementById("travel").style.display = "none";
    document.getElementById("attack").style.display = "inline";
  } else {
    // Reset buttons if no attack, so Travel is usable again
    document.getElementById("travel").style.display = "inline";
    document.getElementById("attack").style.display = "none";
  }
}

function pickEvent() {
  return ["Nothing happened...", "You are under attack:", "Someone should have dropped this:", "You see a structure here:"][Math.floor(Math.random() * 4)];
}

// Only generate enemy if attack event occurs
function pickEnemie(event) {
  if (event === "You are under attack:") {
    return ["Dire Wolf", "Goblin", "Snake", "Skeleton"][Math.floor(Math.random() * 4)];
  }
  return null; // No enemy for non-attack events
}

function enemieData(monster, stat) {
  const monsters = {
    "Dire Wolf": { "hp": 7, "attack": Math.floor(Math.random() * 4 + 1) },
    "Goblin": { "hp": 5, "attack": Math.floor(Math.random() * 4 + 1) },
    "Snake": { "hp": 4, "attack": Math.floor(Math.random() * 4 + 2) },
    "Skeleton": { "hp": 6, "attack": Math.floor(Math.random() * 4 + 1) }
  };
  // Return the stat directly, not an array
  return monsters[monster][stat];
}

// Example attack function using global enemyHP
function attack() {
  if (enemyHP > 0) {
    // Player attacks (example damage value)
    const playerDamage = Math.floor(Math.random() * 3 + 1);
    enemyHP -= playerDamage;
    console.log(`You attack for ${playerDamage} damage! Enemy HP: ${enemyHP}`);
    
    if (enemyHP <= 0) {
      console.log("You defeated the enemy!");
      // Bring back Travel button
      document.getElementById("travel").style.display = "inline";
      document.getElementById("attack").style.display = "none";
    }
  }
}

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Text RPG</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <div class="container-1">
    <button id="travel" class="btn-danger" onclick="travel()">Travel</button>
    <button id="attack" class="btn-danger" onclick="attack()" style="display:none;">Attack</button>
  </div>
  <script src="script.js"></script>
</body>
</html>

Key Changes Explained

  • Global Variables: happened, enemie, and enemyHP are declared at the top, so both travel() and attack() can read/write them.
  • Reassignment in travel(): Every click runs pickEvent() and pickEnemie() again, updating the global variables with new random values.
  • Enemy Generation Logic: pickEnemie() now checks if the event is an attack before generating an enemy, which makes more sense for your RPG flow.
  • HP Value Fix: enemieData() returns a number instead of an array, so enemyHP is easy to use in the attack() function.
  • Button Reset: Added logic to show the Travel button again after defeating an enemy or when no attack occurs.

Now every time you click Travel, you'll get a fresh random event, and your attack() function can access the current enemy's HP without issues!

内容的提问来源于stack exchange,提问作者Abuzer DAG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:52:38