What is the purpose of the Condition being executed in the screep tutorial?

Lately, I've been heavily focused on Python programming but recently delved into the realm of Screeps and Javascript.

As part of a tutorial, there is this code snippet that moves a creep towards an energy source to harvest it:

if(creep.store.getFreeCapacity() > 0) {
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
            creep.moveTo(sources[0]);
        }
    }

This code works as intended, with the creep moving to the resource and harvesting it. However, my initial thought was that the creep would not start harvesting unless explicitly commanded to do so. Is this behavior specific to how objects are defined in Screeps, or am I missing something fundamental about JavaScript?

I also conducted a test by simply instructing the creep to move to the source without any conditionals to see if it would begin harvesting automatically, but it did not.

Answer №1

Breaking down the harvest code into smaller parts instead of keeping it in one line can help with clarity.

if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
    creep.moveTo(sources[0]);
}

This section instructs the creep to start harvesting first and then assess the outcome of that action. According to the documentation, this method returns a constant result that can be examined.

If we break down the code further, it appears like this:

let harvestResult = creep.harvest(sources[0]);
if (harvestResult == ERR_NOT_IN_RANGE) {
    creep.moveTo(sources[0]);
}

By dissecting the code in this way, it becomes more evident that the method is consistently called and assessed afterwards.

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

The getInitialProps function in Next.js is not functioning properly in mobile browser environments

My app runs perfectly on desktop without any errors. However, when I switch to a mobile device, I noticed that the pages fail to trigger the getInitialProps method on the client side, only if I navigate through the Link component. This is my code: return( ...

Issue with font selection in Fabric.js

I am currently working with fabric js version 1.7.22 alongside angular 7 to create a text editor. I have encountered an issue when trying to add text to the canvas using a custom font as shown in the code snippet below. var canvas= new fabric.Canvas(&apos ...

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

Using JavaScript to implement form authorization in ASP.NET Web API

I am looking to revamp a business application by utilizing asp.net web api as the service layer and implementing JavaScript to interact with the web api for retrieving and displaying data. While I have a good grasp on how all the scenarios will function s ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Node.js and Angular.js communication: from requests to responses

Efforts are being made to solicit data from a node.js server through angular.js. However, an unexpected challenge persists: post-data response, a stark white browser screen shows up with the JSON object in plain sight. The goal is for angular.js to acknowl ...

Dealing with JSON Stringify and parsing errors in AJAX

I've been troubleshooting this issue for hours, trying various suggestions found online, but I'm still encountering a problem. Whenever I encode function parameters using JSON.stringify and send them to my PHP handler through AJAX, I receive a pa ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...

Remove console.log and alert statements from minified files using uglifyjs-folder

Currently, I am minifying multiple files in a directory using the uglifyjs-folder feature within my npm configuration in the package.json file as shown below: "uglifyjs": "uglifyjs-folder js -eyo build/js" The process is effectively minifying all the fil ...

Eliminating the use of undefined values in JavaScript output

When the following script is run in a JavaScript environment like Node.js, the output is as follows: undefined 0 1 2 3 4 The Script: for(var i=0;i<5;i++){ var a = function (i) { setTimeout(function () { console.log(i); ...

Is it possible to consolidate React and React-DOM into a unified library instead of having them separate?

Is it possible to combine React.JS and React-DOM.JS into a single library? In all the web applications I've encountered, we always have to import both libraries separately. Have there been any cases where either of these libraries can be used on its ...

Incorporate the use of OpenLayers into a Vue.js application

Can anyone share their insights on incorporating Openlayers into a Vuejs project? I'm looking to showcase various layers within my Vue app. Thanks in advance! ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

delay in displaying options when toggling visibility in a dropdown menu

When you first click on the select, it displays incorrectly https://i.sstatic.net/Ax9T7j8J.png But when you click on it a second time, it displays correctly https://i.sstatic.net/UpW4krED.png $(document).on("click", "#edit_afpDetalle_mes&q ...

What is the best way to send data to an API controller using AJAX in an MVC framework?

I am facing an issue with POSTing a string data to the api controller in mvc using ajax. Despite my efforts, the data does not seem to reach the api controller. Here is what I have attempted: This is the JavaScript code I have used: ...

window.onresize = function() { // code here

Here's an example of code I've been working on: $(document).ready(function (e) { adjustSize(); $(window).resize(adjustSize); function adjustSize() { var windowWidth = parseInt($(window).width()); if (windowWidth > ...

A guide to implementing the map function on Objects in Stencil

Passing data to a stencil component in index.html <app-root data="{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d7d6f5d2d8d4dcd99bd6dad8">[email protected]</a>, <a href="/cdn-cgi/l/email-pro ...

Slow execution of Bootstrap v4 modal display

It has come to my attention that the modals in Bootstrap show slower as the page's content increases. When the page is empty, it only takes less than 100ms to show. However, the time it takes significantly increases as more content is added to the pa ...

Getting data from an API using a Bearer Token with React Hooks

I am currently developing a React application that is responsible for fetching data from an API. This API requires Bearer Token Authorization. To handle this, I have implemented useState() hooks for both the token and the requested object. Additionally, th ...