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 discrepancies exist between running npm install on Windows versus Linux operating systems?

Just have a quick question to ask. I've been searching online with no luck. If I were to run npm install on a Windows machine to set up my dependencies, would it be viable to transfer the node_modules directory to a Linux machine and execute my nodej ...

Is there a way to retrieve a comprehensive list of all anchors that contain the data-ng-click attribute

I am currently working on a web application built with asp.net and angularjs. My goal is to specifically retrieve all anchor tags that have the attribute data-ng-click assigned to them. Is there a way to achieve this? If so, how can it be done? I a ...

Exploring the retrieval of stored information from $localStorage within an AngularJS framework

I have been working on a MEAN app, and after a user successfully logs in, I want to save the returned user data in the localStorage of the browser for future use. I am using the ngStorage module for this purpose. Below is the code snippet from my LoginCont ...

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

MERN stack does not have a defined onClick function

I am developing a website for college registration, and I encountered an issue while trying to create a feature that allows students to select a major and view all the associated courses. I made a list of majors with buttons next to them, but whenever I at ...

Transforming Json data into an Object using Angular 6

https://i.stack.imgur.com/JKUpL.png This is the current format of data I am receiving from the server, but I would like it to be in the form of an Object. public getOrder(): Observable < ORDERS > { return this._http.get < ORDERS > (`${thi ...

Struggling to separate a section of the array

Check out this array: [ '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a171319121b1f163a1f1915080a54191517">[email protected]</a>:qnyynf', '<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Ways to obtain the coordinates that surround a particular x, y location

I am trying to figure out how to generate an array of coordinates around a specific x, y point. For instance: xxxxx xxoxx xxxxx In this case, "o" is located at coordinates 3, 2. Now I aim to produce: xxx xox xxx as the set of coordinates surrounding "o ...

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

Fetching Information From Database Using PHP

I am encountering an issue while attempting to transfer data from my HTML table to my modal (without using bootstrap). In the image below, you can see that I have successfully displayed data from MySQL database in the table. The problem arises when I clic ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

What is the best way to collect and store data from various sources in an HTML interface to a Google Spreadsheet?

Currently, I have a spreadsheet with a button that is supposed to link to a function in my Google Apps Script called openInputDialog. The goal is for this button to open an HTML UI where users can input text into five fields. This input should then be adde ...

Is there a way to calculate the total of three input values and display it within a span using either JavaScript or jQuery?

I have a unique challenge where I need to only deal with positive values as input. var input = $('[name="1"],[name="2"],[name="3"]'), input1 = $('[name="1"]'), input2 = $('[name="2"]'), input3 = $('[name=" ...

Maintaining personalized variable values for individual connected clients in Node.js: What's the best approach?

I have recently started working with Node.js and I am using Visual Studio 2015 with the Basic Node.js Express 4 app template. After setting some values through a post request from the client, I noticed that when I open another tab and send another post re ...

Generating requests using ExpressJS

Is it possible to send a POST request using a GET action? Although everything seems to be working fine, the "TOKEN" does not appear after the post. I am puzzled as to why this is happening. const request = require('request'); exports.g ...

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

Is it possible that the passing of Form Serialize and list to the controller is not functioning properly?

i am struggling with the following code in my controller: public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry) { //something } here is my model : public class DTO_WorkOrder { public string Id { get; set; ...