What methods can I use to prevent a number from becoming negative?

I am currently developing a game where players collect resources, spend them to create more resources, and engage in various activities. However, I'm facing an issue where the resource count goes into negative numbers when too much of a certain item is purchased. I need assistance in disabling the button to prevent this from happening.

In addition, I'm looking for a way to display the percentage of total trees in the game. Any help on how to achieve this would be greatly appreciated.

For reference, here is the code snippet:

<!DOCTYPE html>
<html>

<head>
  <title>Game</title>
  <script>
    function collectSeeds() {
      document.getElementById("Seeds").stepUp(1);
    }

    function plantTree() {
      document.getElementById("Seeds").stepDown(10);
      document.getElementById("Trees").stepUp(1);
    }

    function plantTrees10() {
      document.getElementById("Seeds").stepDown(100);
      document.getElementById("Trees").stepUp(10);
    }
  </script>
</head>

<body>
  <button onclick="collectSeeds()">Collect Seeds</button>
  <button type="button" id="plantTree" 
    onClick="myTimer = setInterval(collectSeeds, 1000); plantTree();">Plant Tree</button>
  <button 
    onClick="plantTrees10(); myTimer = setInterval(collectSeeds,100);">Plant Trees (10)</button>
  <p>Seeds
    <br/>
    <input type="number" id="Seeds" disabled></input>
    <p>Trees
      <br/>
      <input type="number" id="Trees" disabled></input>
      <div style="position: fixed; bottom: 0; right: 0;">Progress:</div>
</body>

</html>

Answer №1

  1. Include min and max values in the field according to the provided guidelines

  2. Consider adding a message display as well.

  3. Remember to clear the interval before reusing it - I modified the script for better efficiency and flexibility.

var myTimer; // declare globally
function collectSeeds() {
  document.getElementById("Seeds").stepUp(1);
}

function plantTree(button) {
  var numOfSeeds = parseInt(button.getAttribute("data-nofseeds"), 10),
    availableSeeds = parseInt(document.getElementById("Seeds").value, 10);
  if (availableSeeds < numOfSeeds) {
    console.log(availableSeeds + " not sufficient, " + numOfSeeds + " required"); // add a message display
    return;
  }
  console.log(numOfSeeds)
  document.getElementById("Seeds").stepDown(10 * numOfSeeds);
  document.getElementById("Trees").stepUp(numOfSeeds);
}

window.onload = function() {
  var plantButtons = document.querySelectorAll(".plantTree");
  for (var i = 0; i < plantButtons.length; i++) {
    plantButtons[i].onclick = function() {
      clearInterval(myTimer); // ensure only one timer is active
      myTimer = setInterval(collectSeeds, 1000);
      plantTree(this);
    }
  }
}
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" class="plantTree" data-nofseeds="1">Plant Tree</button>
<button type="button" class="plantTree" data-nofseeds="10">Plant Trees (10)</button>
<p>Seeds
  <br/>
  <input type="number" min="0" max="1000" id="Seeds" disabled />
</p>
<p>Trees
  <br/>
  <input type="number" id="Trees" disabled />
</p>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>

Answer №2

If you want it to function properly, simply include the following code...

function growGarden() {
  if (document.getElementById("Seeds").value < 10) {
    alert("Insufficient resources available")
  } else {
    document.getElementById("Seeds").stepDown(10);
    document.getElementById("Plants").stepUp(1);
  }
}
function growGardenInBulk() {
      if (document.getElementById("Seeds").value < 100) {
        alert("Not enough resources to complete operation")
      } else {
      document.getElementById("Seeds").stepDown(100);
      document.getElementById("Plants").stepUp(10);
    }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the potential of $scope within $timeout in AngularJS

I am attempting to display a default message on a textarea using AngularJS. Some of the values I want to include require the use of $timeout to retrieve the values. The message does not appear to show up with the following code: <textarea class="t ...

Stop accidental form submissions on iOS devices by disabling the return button

In my Ionic 3 application running on iOS, I encountered a bug that allows users to submit a form even when the submit button is disabled. Despite trying different solutions from this source, I have not been successful in resolving it. To prevent accidenta ...

Datatables: Concealing Column According to Database Content

I am currently working on displaying or hiding a column based on values from my database. My approach involves utilizing Jquery, PHP, and MySQL. Initially, I attempted to retrieve the data using ajax and hide the column, but encountered an issue where onl ...

A guide to utilizing CSS to showcase the content of all four div elements in HTML body simultaneously

Is there a way to use CSS to display the content of all 4 divs in the same place on the HTML body, based on the URL clicked? Only one div should be displayed at a time in the center of the page. For example, if URL #1 is clicked, it should show the conten ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

How can I use JavaScript to access my templates directory in Django 3?

Perhaps I am taking the wrong approach here. My goal is to dynamically replace the content within the <nav> element using jQuery.load() when a specific <div> is clicked by the user. However, I am encountering difficulty in accessing the HTML fi ...

Encountering a hiccup while trying to retrieve information from a JSON

I am currently working on a Jquery Drop Upload form and everything is functioning well. However, I am encountering an error when trying to retrieve data from the database using JSON. I'm not sure why this error is occurring, so please see below for mo ...

Can custom HTML elements be designed to function similarly to standard ones?

What is the best way to create a custom HTML element that functions as a link without relying on inline Javascript? For instance: <x-button href="...">...</x-button> Can I develop an element like <x-button> that can accept an attribute ...

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

Tips for creating a curved shape using fabric.js

I am encountering an issue while trying to draw an arc using a circle with a start and end angle in my code. Here is the snippet I am working with: var circle = new fabric.Circle({ radius: 30, left: 20, top: 20, fill: " ...

Is the package downloaded through NPM identical to the local file in my particular situation?

In my current project, the previous developers included jQuery in the local environment, and a minified version 3.1.1 has been maintained for the past two years. I am now attempting to manage it using NPM. However, more experienced developers are cautionin ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

AngularJS 2 - error when trying to bind inner properties: ERROR: Unable to access property value due to undefined variable

I have been troubleshooting a problem with my AngularJS 2 app using Typescript. The issue arises when I attempt to access a property from the Typescript class in the HTML page using data binding. I have provided the relevant files below for reference. If t ...

"Vanishing act: The mysterious disappearance of an empty JSON

After defining a JSON object and posting it to the backend (Node.js), there appears to be an issue. var imj = {}; imj.images = []; $.post("/image/uploadImages", imj, function(feedback){ ..... Unfortunately, when the backend received the data, the "images ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

Tips for increasing the height of a Kendo-UI grid to 100% within an AngularJS 1.x environment

Encountering an issue, I needed a Kendo UI Grid widget with its height set to 100% of the surrounding <div>. Attempting basic CSS styling on the grid proved unsuccessful: html, body { height:100%; } .expand-vertical { height: 100%; min-h ...

The text is not rendering properly, with some characters being replaced by different ones

RESOLUTION: To fix the issue, eliminate font-family, font-size, and color properties from the parent div. UPDATE: The problem only occurs when I press CTRL + F5. UPDATE 2: After investigating, I found that the culprit is .site-footer with a position:abso ...

Tips for troubleshooting JavaScript errors in Internet Explorer 7 & 6 using Dreamweaver CS3

Is there a way to track and debug JavaScript errors in Internet Explorer 7 & 6 on web pages using Dreamweaver CS3? I am experienced with debugging in Visual Studio, but unsure how to do it in Dreamweaver CS3. ...

Is it possible to store dat.gui presets for controls that are dynamically added?

I have a dynamic dat.gui interface where I add controls, but the "save settings" feature doesn't seem to recognize them. var mygui = new dat.GUI(); mygui.remember(mygui); // Example of adding a control in the standard way mygui.control1 = 0.0; var c ...