Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function.

var takeSword = function() {
        if (currentRoom.hasSword) {
            $("<p>You picked up a sword.</p>").properDisplay();

        }
        else {
            $("<p>The sword is not here.</p>").properDisplay();
        }
    };

The issue I'm facing is that it's possible to repeatedly pick up the sword while remaining in the same room. How can I modify the function so that once the sword is collected, it cannot be picked up again?

Initially, my approach was to use a variable like var sword = false; and then update it to sword = true; within the function, but this did not prove effective.

This code snippet doesn't cover the entire script; there's an object defined earlier that sets 'hasSword = true;', allowing the sword to be obtained initially but preventing it from being picked up in other areas of the game.

Answer №1

Maybe something along these lines?

let GameConditions = {
    hasKey: true,
    playerHasKey: false,
    obtainKey: function() {
        if( this.hasKey ) {
            this.hasKey = false;
            this.playerHasKey = true;
            $("<p>You found a key!</p>").displayMessage();
        }
        else {
            $("<p>No key here.</p>").displayMessage();
        }
    }
}

GameConditions.obtainKey();

Answer №2

To improve your code, consider encapsulating your original function within another function that ensures it is only executed once. This wrapper function can be applied to any other parts of your code where you require a similar functionality:

function runOnce(fn, context) { 
    var result;

    return function() { 
        if(fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        }

        return result;
    };
}

After defining the above function, you can use it like this:

var performTaskOnce = runOnce(performTask);

By using performTaskOnce, you ensure that the specified task runs only once in your script. Alternatively, you can directly modify the original function like so:

performTask = runOnce(performTask);

You may find additional insights on the runOnce function by reading this article.

Answer №3

@Kenney really helped me see things from a different perspective. After some tinkering, I managed to resolve the issue without having to completely overhaul the function:

var takeSword = function() {
        if (currentRoom.hasSword) {
            $("<p>You grabbed the sword.</p>").properDisplay();
            currentRoom.hasSword = false;
        }
        else {
            $("<p>There is no sword here.</p>").properDisplay();
        }
    };

My initial error was assuming "hasSword" was simply a standalone variable. It wasn't until I incorporated the currentRoom object that everything fell into place. I've run tests and even tried it in rooms sans sword, and it appears to be functioning properly.

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

What is the best way to send information back to an AJAX script that has made a

Can someone explain to me how the response section of an AJAX call is processed and formatted using plain, native JavaScript (no jQuery or other frameworks)? I have searched extensively but have not found a clear answer. I am looking for an example that ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Tips for creating a cohesive group of HTML elements within an editable area

Imagine having a contenteditable area with some existing content: <div contenteditable="true"> <p>first paragraph</p> <p> <img width='63' src='https://developer.cdn.mozilla.net/media/img/mdn-logo-s ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

Using Node.js to create a RESTful API that pulls information from MongoDB

I am currently working on creating a REST API using Node.js to retrieve the last N rows from a MongoDB collection. Here is my current code snippet: var express = require("express"); var app = express(); var bodyParser = require("body-pa ...

Generating parameters on the fly from an array using jQuery

After implementing a successful plugin on my website, I am now looking to enhance it further by defining state-specific styles dynamically. The current setup allows for passing parameters for specific states, as shown below: $('#map').usmap({ ...

Dealing with problematic hover behaviors in Cypress: A guide

I encountered an issue with Cypress hover functionality while trying to access a sub menu that appears after hovering over a main menu item. The error message I received was This element is not visible because it has CSS property: position: fixed and it&ap ...

Retrieve an array from JSON encoding using AJAX

I have been attempting to retrieve 4 JSON arrays stored in a separate file and include them in my main file using an AJAX request. However, I'm facing difficulties storing these arrays into variables and logging them in the console. Here are the resul ...

Transferring data from local storage to a PHP server using AJAX

My attempt to transfer data from local storage to PHP using AJAX resulted in an error mentioning 'undefined index data'. chart.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="t ...

retrieve data for chart from an AJAX request

I am looking to create a chart using amCharts and I have received some values from the server through an ajax call. Now, I need help in utilizing this data for my chart. Can anyone guide me on how to achieve this? var chart = am4core.create("chartdiv& ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...

Achieving a consistent scroll value using RxJs

I have a block with a mat-table inside, which has an initial scroll value of 0. I am trying to achieve a scenario where the scroll value changes automatically to 2 or more when you reach a height of 0 and again changes back to 2 when scrolled to the final ...

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

Trouble with parseJSON when handling form POST in Python

I'm struggling with a javascript HTML page that has an action POST to a python file, expecting a JSON response back. Despite my efforts, I can't figure out how to catch and parse the JSON data. The HTML and python code excerpts below should show ...

Several dropdown menus within the same container, working independently of each other

I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open ...

Implement pagination for an array in JavaScript

I am seeking a solution involving displaying a JavaScript object in a paged format. For instance, given the sample object below, I aim to present it as pages based on the value stored in the perPage variable. { "fruits":[ { "from":"Shanghai ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

Steps for displaying a post's image when hovering over its link in WordPress

One section of my website displays the latest 6 posts, and here is the HTML code for it: <div class="latest-posts"> <div id="latest-posts-title"> <p>Latest Posts</p> </div> <div id="latest-posts-pictures" ...