HTML I'M LOSING MY MIND

OldSailor

Newbie
Sep 11, 2021
60
21
Help me, I'm losing my mind.


I'm coding an HTML-based game using Tweego on a SugarCube framework. I wanted to create a simple inventory-store and buy-sell system for my game. What should have been a very basic feature turned into a huge mess, and even though I spent the entire day on this damn code, I still couldn't make a properly working buy-sell system.


The best I managed to do was a messy piece of code that allowed the user to buy and sell items from the store. But guess what happened? No matter which item you bought from the damn store, the code always assumed it was the last item. So basically, you could only buy one single item from the store. The more I tried to fix it, the messier it got, and in the end, I had to trash the entire code and revert back to my original backup.


I'm asking for help from the generous developers here. What I need from you is a buy-sell system that works seamlessly with my inventory system. I need to be able to buy products from the store and sell items from my inventory. If you can do this, I will be REALLY GRATEFUL and I will add credits for you in my game and let you know.


P.S. My inventory system seems to be working fine for now.

Inventory passage:
Code:
:: Inventory

<h2>Inventory</h2>

<<if $inventory.length > 0>>
  <div style="display:flex; flex-wrap:wrap; gap:15px;">
    <<for _item range $inventory>>
      <div style="width:180px; border:1px solid #555; border-radius:10px; padding:10px; text-align:center; background-color:#1a1a1a; color:white;">
        <<= '<img src="' + _item.image + '" style="width:128px; height:128px; object-fit:contain; border-radius:5px; border:1px solid #444;">' >>
        <h3><<=_item.name>></h3>
        <p><<=_item.desc>></p>
        <p><b>Quantity:</b> <<=_item.quantity>></p>
      </div>
    <</for>>
  </div>
<<else>>
  <p>Your inventory is empty.</p>
<</if>>




<<script>>
window.setTimeout(() => {
  for(let i = 0; i < State.variables.inventory.length; i++) {
    var img = document.createElement('img');
    img.style.width = '128px';
    img.style.height = '128px';
    img.style.objectFit = 'contain';
    img.style.borderRadius = '5px';
    img.style.border = '1px solid #444';
    img.src = State.variables.inventory[i].image;
    var container = document.getElementById("img-container-" + i);
    if(container) {
      container.appendChild(img);
    }
  }
}, 0);
<</script>>
StoryInit:
Code:
<<script>>
/* Inventory system variable */
if (!State.variables.inventory) {
    State.variables.inventory = [];
}

/* Item adding function */
setup.addItem = function(name, image, desc, quantity = 1) {
    const inv = State.variables.inventory;
    const existingItem = inv.find(it => it.name === name);
    if (existingItem) {
        existingItem.quantity += quantity;
    } else {
        inv.push({
            name: name,
            image: image,
            desc: desc,
            quantity: quantity
        });
    }
};

/* Item delete function */
setup.removeItem = function(name, quantity = 1) {
    const inv = State.variables.inventory;
    const index = inv.findIndex(it => it.name === name);
    if (index !== -1) {
        inv[index].quantity -= quantity;
        if (inv[index].quantity <= 0) {
            inv.splice(index, 1);
        }
    }
};

/* Starting items for testing purposes */
setup.addItem("Gun", "images/items/gun.png", "A fucking gun.", 1);
setup.addItem("Water Bottle", "images/items/water.png", "Yeah. Usual, water.", 3);
setup.addItem("Radio", "images/items/radio.png", "Bzzt. Bzzt.", 1);
<</script>>
 

Winterfire

Conversation Conqueror
Respected User
Game Developer
Sep 27, 2018
6,167
8,898
It has been ages since I tried html and never made a game with sugar, but you can display the inventory and have a removeitem function that works already, right? So a shop would just be a window that displays your inventory's content, with a button next to it that [x] of said item.

You'd just need to add two variables: An integer for the price of said item (price to buy, price*0.5 to sell) and a boolean to know if it's a key item (so cannot be sold).

If you don't want to fuck up your code, use github and push every small change, then test it throughly. Don't do too much at once.
 

Alcahest

Forum Fanatic
Donor
Game Developer
Jul 28, 2017
4,054
4,881
But guess what happened? No matter which item you bought from the damn store, the code always assumed it was the last item.
It might be better if you show the code that didn't work and maybe someone can help. Now I can only guess, and based on what you say, it sounds like you may have forgotten to "capture" the value of the variable you used to iterate through the items in the store, causing you to end up with the last value of the variable for all the buy actions. As a simple example, consider this:
Code:
<<set $storeinventory = [ "gun", "water", "radio"]>>
<<for _i=0; _i < $storeinventory.length; _i++>>
    <<button _i>><<replace "#storeinfo">>You bought _i<</replace>><</button>>
<</for>>
<div id="storeinfo">Do you want to buy something?</div>
No matter what button you click, it will show "You bought 3".
Obviously, you would want to display $storeinventory[_i] instead of _i but I'm using _i here to show the value of _i (which in this case ends up 3 even though the buttons only go from 0 to 2).

But if you capture the value of _i, it will show the correct value for each button.
Code:
<<set $storeinventory = [ "gun", "water", "radio"]>>
<<for _i=0; _i < $storeinventory.length; _i++>>
    <<capture _i>>
        <<button _i>><<replace "#storeinfo">>You bought _i<</replace>><</button>>
    <</capture>>
<</for>>
<div id="storeinfo">Do you want to buy something?</div>
 
Last edited:

papel

Member
Game Developer
Sep 2, 2018
484
684
I'm not familiar with either framework, but some important things we need to know:

What variable contains the player's inventory? State.variables.inventory? If you haven't set up all the player variables properly in an easy to find/remember varname, you should.

A recommendation is to also define the items that will be used through the game as objects, like so:
JavaScript:
<<set $gun = {
  name = "Gun",
  image = "images/items/gun.png",
  description = "A fucking gun",
  quantity = 1,
  buyprice = 10,
  sellprice = 5,
}>>
// other items defined...
//-------------------
// Doing so allows you to simply push the object into the player inventory, 
// instead of passing all the data into the function - 
<button onClick="buyItem($gun, 10);">Buy gun</button>
// the above is a typical html button.
// below is what should work as a sugarcube button
<<button "Buy gun">><<script>>setup.buyItem($gun);<</script>><</button>>

<<script>>
setup.buyItem = function(item){
//checks if the player has the item, stores the index value
invindex = player.inventory.items.findIndex( e => e.name === item.name);
// Checks if the player has money to buy the item
// The item's price is defined on its own <<set $gun>>
  if (player.money >= item.buyprice) {
    player.money -= price;
    // the array.some() function checks if an object with that value exists
    // if the player's inventory has "some" of the item, just add the quantity
    if (invindex > -1) {
       player.inventory.items[invindex].quantity += 1;
       //as invindex returns the position of the item in the array, we are safe to assume
       // that its position is the right one
    }
  } else {
    //show a message about no money
  }
}
<</script>>
// Above, clicking the button will automatically buy 1 gun 
// I'm also assuming that the inventory is within the player variable
The reason for setting objects like that is that, if/when you decide to update anything about a specific item, you'll only need to look for that one specific definition, instead of every place where it might show up.

Also, looking at the code you posted, I'm not sure your removeItem function is removing from the player's variable. You define the const inv = State.variables.inventory; within the function and also removes the item from that const, instead of the State.variables.inventory.

Assuming you can get my suggested code above working, a sell function would look like this:
JavaScript:
<<button "Sell gun">><<script>>setup.sellItem($gun);<</script>><</button>>

setup.sellItem = function(item) {
  invindex = player.inventory.items.findIndex( e => e.name === item.name);
  //greater than -1 is 0 and above. Arrays start at 0.
  if (invindex > -1) {
    player.inventory.items[invindex].quantity -= 1;
    player.money += item.sellprice; //defined all the way above in the proper object
    // If the last item was sold, remove the item from the inventory array
    // splice removes the array item at the index position. 1 indicates to remove only 1 item
    if (player.inventory.items[invindex].quantity < 1) { player.inventory.items.splice(invindex, 1); }
  }
}
 
  • Like
Reactions: osanaiko

OldSailor

Newbie
Sep 11, 2021
60
21
I'm not familiar with either framework, but some important things we need to know:

What variable contains the player's inventory? State.variables.inventory? If you haven't set up all the player variables properly in an easy to find/remember varname, you should.

A recommendation is to also define the items that will be used through the game as objects, like so:
JavaScript:
<<set $gun = {
  name = "Gun",
  image = "images/items/gun.png",
  description = "A fucking gun",
  quantity = 1,
  buyprice = 10,
  sellprice = 5,
}>>
// other items defined...
//-------------------
// Doing so allows you to simply push the object into the player inventory,
// instead of passing all the data into the function -
<button onClick="buyItem($gun, 10);">Buy gun</button>
// the above is a typical html button.
// below is what should work as a sugarcube button
<<button "Buy gun">><<script>>setup.buyItem($gun);<</script>><</button>>

<<script>>
setup.buyItem = function(item){
//checks if the player has the item, stores the index value
invindex = player.inventory.items.findIndex( e => e.name === item.name);
// Checks if the player has money to buy the item
// The item's price is defined on its own <<set $gun>>
  if (player.money >= item.buyprice) {
    player.money -= price;
    // the array.some() function checks if an object with that value exists
    // if the player's inventory has "some" of the item, just add the quantity
    if (invindex > -1) {
       player.inventory.items[invindex].quantity += 1;
       //as invindex returns the position of the item in the array, we are safe to assume
       // that its position is the right one
    }
  } else {
    //show a message about no money
  }
}
<</script>>
// Above, clicking the button will automatically buy 1 gun
// I'm also assuming that the inventory is within the player variable
The reason for setting objects like that is that, if/when you decide to update anything about a specific item, you'll only need to look for that one specific definition, instead of every place where it might show up.

Also, looking at the code you posted, I'm not sure your removeItem function is removing from the player's variable. You define the const inv = State.variables.inventory; within the function and also removes the item from that const, instead of the State.variables.inventory.

Assuming you can get my suggested code above working, a sell function would look like this:
JavaScript:
<<button "Sell gun">><<script>>setup.sellItem($gun);<</script>><</button>>

setup.sellItem = function(item) {
  invindex = player.inventory.items.findIndex( e => e.name === item.name);
  //greater than -1 is 0 and above. Arrays start at 0.
  if (invindex > -1) {
    player.inventory.items[invindex].quantity -= 1;
    player.money += item.sellprice; //defined all the way above in the proper object
    // If the last item was sold, remove the item from the inventory array
    // splice removes the array item at the index position. 1 indicates to remove only 1 item
    if (player.inventory.items[invindex].quantity < 1) { player.inventory.items.splice(invindex, 1); }
  }
}

Thanks to everyone who commented and tried to help. I’m still pretty new to game coding, so I often rely on AI when it comes to building complex systems. I managed to fix this issue a couple of days ago, but now I’ve run into a new one.


I’m not sure if I should open a new thread for it, but I’ll explain here anyway. The system I’m working on is straightforward: the suspect gets arrested and sent to the holding cell passage. When you enter that passage, you see a box with the suspect’s info and three options.


The problem is that when I press the release button, it always releases the suspect at the very bottom of the list, just like what happened in my market system, rather than the one I actually select. Logically, it looks like the same kind of error, but as I mentioned, I’m still a beginner and when it comes to complex systems, I mostly just end up staring at the screen.

Holding cell passage:
Code:
:: holdingcell
<<print JSON.stringify($holdingCellSuspects)>>
You escort the suspect(s) to the holding cell.

<<if !$holdingCellSuspects || $holdingCellSuspects.length == 0>>
  <p>The cell is currently empty.</p>
<<else>>
  <h3>Suspects Currently in Holding:</h3>

  <<for _suspect range $holdingCellSuspects>>
    <<set _id = (_suspect && _suspect.id) ? _suspect.id : ("idx-" + $holdingCellSuspects.indexOf(_suspect))>>
    <div style="border:1px solid #ccc; padding:10px; margin:8px 0; border-radius:6px; display:flex; gap:10px; align-items:flex-start;">
      <div style="width:90px; flex:0 0 90px;">
        <<if _suspect && _suspect.img && _suspect.img !== "">>
          <img src="<<=_suspect.img>>" style="width:90px; height:90px; object-fit:cover; border-radius:6px; border:1px solid #ddd;">
        <<else>>
          <div style="width:90px; height:90px; display:flex; align-items:center; justify-content:center; background:transparent; border-radius:6px; color:#666; border:1px dashed #e0e0e0;">
            No image
          </div>
        <</if>>
      </div>

      <div style="flex:1;">
        <div style="font-weight:700; font-size:1em;"><<= (_suspect && _suspect.name) ? _suspect.name : "Unknown" >></div>
        <div style="color:#555; font-size:0.9em;">Age: <<= (_suspect && _suspect.age) ? _suspect.age : "—" >></div>
        <div style="color:#555; font-size:0.9em; margin-top:4px;">Crime: <<= (_suspect && _suspect.crime) ? _suspect.crime : "Unknown" >></div>

        <<if _suspect && _suspect.notes && _suspect.notes !== "">>
          <div style="margin-top:8px; font-size:0.9em; color:#444;"><strong>Notes:</strong> <<= _suspect.notes >></div>
        <<else>>
          <div style="margin-top:8px; font-size:0.9em; color:#777;"><em>No notes yet.</em></div>
        <</if>>
      </div>

      <div style="display:flex; flex-direction:column; gap:6px; margin-left:12px;">
        <<link "Interrogate">>
          <<set $selectedSuspect = _suspect>>
          <<goto "interrogation">>
        <</link>>

        <<link "Release">>
          <<run releaseById(_id)>>
        <</link>>

        <<link "Profile">>
          <<set $selectedSuspect = _suspect>>
          <<goto "suspect-profile">>
        <</link>>
      </div>
    </div>
  <</for>>
<</if>>

[[Return to station|pd]]
release suspect passage:
Code:
:: release-suspect
<<if $releaseId == null || $releaseId === undefined>>
  <p>No suspect selected to release.</p>
  [[Back|holdingcell]]
<<else>>
  <<run $holdingCellSuspects = $holdingCellSuspects.filter(function(s){ return String(s.id) !== String($releaseId); })>>
  <<set $releaseId = null>>
  <p>Suspect released.</p>
  [[Back to holding cell|holdingcell]]
<</if>>
StoryInit passage:
Code:
/* Suspect pools */
<<set $femaleSuspects = [
  {name: "Jessica Moore", age: 24, img: "images/suspects/jessica.jpg"},
  {name: "Lena Vasquez",  age: 30, img: "images/suspects/lena.jpg"},
  {name: "Aisha Khan",    age: 27, img: "images/suspects/aisha.jpg"}
]>>

<<set $maleSuspects = [
  {name: "Robert King",   age: 32, img: "images/suspects/robert.jpg"},
  {name: "Marcus Lee",    age: 28, img: "images/suspects/marcus.jpg"},
  {name: "Dmitri Ivanov", age: 35, img: "images/suspects/dmitri.jpg"}
]>>

/* Holding cell and counter */
<<set $holdingCellSuspects = $holdingCellSuspects ? $holdingCellSuspects : []>>
<<set $nextSuspectId = $nextSuspectId ? $nextSuspectId : 1>>

/* JS helper functions */
<<script>>
window.genSuspectId = function() {
  var vars = State.variables;
  if (!vars.nextSuspectId) vars.nextSuspectId = 1;
  var id = "s" + vars.nextSuspectId;
  vars.nextSuspectId += 1;
  return id;
};

window.releaseById = function(id) {
  var vars = State.variables;
  if (!vars.holdingCellSuspects) vars.holdingCellSuspects = [];
  vars.holdingCellSuspects = vars.holdingCellSuspects.filter(function(s){ return String(s.id) !== String(id); });
  if (typeof Engine !== "undefined" && typeof Engine.play === "function") {
    Engine.play("holdingcell");
  } else {
    location.reload();
  }
};
<</script>>
 

Alcahest

Forum Fanatic
Donor
Game Developer
Jul 28, 2017
4,054
4,881
The problem is that when I press the release button, it always releases the suspect at the very bottom of the list, just like what happened in my market system, rather than the one I actually select. Logically, it looks like the same kind of error
And it's the same answer I already (correctly) guessed and gave you. You must capture _id.
Code:
<<capture _id>>
  <<link "Release">>
    <<run releaseById(_id)>>
  <</link>>
<</capture>>
You should stop generating code using AI at once because you have proven you are using it to produce code above your current skill level. If you use AI for programming, it should be a tool to produce code you understand and can verify that it works correctly. Since you aren't, even if you manage to put together a game that seems to work, it will eventually start to break down and you are sitting with a buggy mess that you can't fix because you don't understand the code.
 

OldSailor

Newbie
Sep 11, 2021
60
21
And it's the same answer I already (correctly) guessed and gave you. You must capture _id.
Code:
<<capture _id>>
  <<link "Release">>
    <<run releaseById(_id)>>
  <</link>>
<</capture>>
You should stop generating code using AI at once because you have proven you are using it to produce code above your current skill level. If you use AI for programming, it should be a tool to produce code you understand and can verify that it works correctly. Since you aren't, even if you manage to put together a game that seems to work, it will eventually start to break down and you are sitting with a buggy mess that you can't fix because you don't understand the code.
You're right, but I've already come a long way, and my game currently has fully functional, playable systems outside of this. Learning the logic behind all this coding could take me almost a year, which would mean putting this project on hold for a year. We all start somewhere, and we had to start. Right? What began as a simple Twine game has now become more functional than many games on the market.
 

papel

Member
Game Developer
Sep 2, 2018
484
684
I’m still pretty new to game coding, so I often rely on AI when it comes to building complex systems
That's your biggest mistake. Ask experienced programmers who have used or are using AI on whether they think it's actually boosting productivity on code writing. The majority will say it's not helping at all.

Besides, since you yourself don't understand the logic behind the system you're trying to implement, you'll never understand what's going on and why, vibe code or not.
Learning the logic behind all this coding could take me almost a year, which would mean putting this project on hold for a year. We all start somewhere, and we had to start.
If you're not willing to put the effort in learning how one of the most important aspects of the game works, but insist on "doing it yourself (with AI)", you'll keep bashing your head against a wall with every new bit of code you add, an endless cycle of "The game is not doing what I want because I have no idea what the code is supposed to be doing in the first place"

What began as a simple Twine game has now become more functional than many games on the market.
Citation needed. Dysfunctional sounds more appropriate, considering your woes
 

OldSailor

Newbie
Sep 11, 2021
60
21
That's your biggest mistake. Ask experienced programmers who have used or are using AI on whether they think it's actually boosting productivity on code writing. The majority will say it's not helping at all.

Besides, since you yourself don't understand the logic behind the system you're trying to implement, you'll never understand what's going on and why, vibe code or not.

If you're not willing to put the effort in learning how one of the most important aspects of the game works, but insist on "doing it yourself (with AI)", you'll keep bashing your head against a wall with every new bit of code you add, an endless cycle of "The game is not doing what I want because I have no idea what the code is supposed to be doing in the first place"


Citation needed. Dysfunctional sounds more appropriate, considering your woes

Thanks for the info. I have created a 25-week coding plan for myself. During this process, while learning the basics of HTML, CSS, JavaScript, DOM, and various other factors, I will also make small changes to my project to ensure that it does not become stagnant, and that the seemingly meaningless chaos in front of me will eventually make sense to me. This game will not be released until I fully understand the functionality of all the code in my game and design the systems myself.



I would like to thank everyone who has helped and is trying to help, once again.
 
  • Like
Reactions: osanaiko and papel

osanaiko

Engaged Member
Modder
Jul 4, 2017
3,240
6,174
Thanks for the info. I have created a 25-week coding plan for myself. During this process, while learning the basics of HTML, CSS, JavaScript, DOM, and various other factors, I will also make small changes to my project to ensure that it does not become stagnant, and that the seemingly meaningless chaos in front of me will eventually make sense to me. This game will not be released until I fully understand the functionality of all the code in my game and design the systems myself.
I would like to thank everyone who has helped and is trying to help, once again.
That's a solid plan and has a much better chance of long term success.
I think you are correct in that the posters above are trying to help. Some are grumpy and some are blunt, but the advice comes from a place of wanting you (and all new devs) to succeed.
I for one contribute in this section because I want to help increase the number of good adult games in the world, because I like to play them.

Best of luck dude!
 

PTSdev

Member
Oct 21, 2019
117
414
Some observations regarding your code:
- To me, this looks overly complicated for what it does. You can achieve the functionality of what you're doing entirely with SugarCube code, these JS / DOM functions do work, but they open a new can of worms. Be careful with those, because they might lead to some unwanted side effects. Remember that Sugarcube / Twine only stores changes in the story history on passage (re)load.
- The in-line styling is what most beginners do (I still do it because I'm a lazy fuck), but at least for general / consistent styling, you should look into CSS and define stuff you're reusing over multiple passages.

On coding in general:
Do not get attached to anything you create during your first year of coding. The more you learn, the more efficient your code becomes - and the more you see structural mistakes. Make sure to properly lay out a plan for your game. Feature creep is really dangerous. Keep your first projects simple.

Personal opinion:
Do not vibe code. Instead, use AI to look over code you're written by yourself. And don't copy & paste stuff from AI suggestions if you don't understand the logic behind the code. The SugarCube documentation is amazing and very in-depth. Paired with AI suggestions and the SugarCube Discord, you should be good to go.

Good luck with your project!
 

OldSailor

Newbie
Sep 11, 2021
60
21
Some observations regarding your code:
- To me, this looks overly complicated for what it does. You can achieve the functionality of what you're doing entirely with SugarCube code, these JS / DOM functions do work, but they open a new can of worms. Be careful with those, because they might lead to some unwanted side effects. Remember that Sugarcube / Twine only stores changes in the story history on passage (re)load.
- The in-line styling is what most beginners do (I still do it because I'm a lazy fuck), but at least for general / consistent styling, you should look into CSS and define stuff you're reusing over multiple passages.

On coding in general:
Do not get attached to anything you create during your first year of coding. The more you learn, the more efficient your code becomes - and the more you see structural mistakes. Make sure to properly lay out a plan for your game. Feature creep is really dangerous. Keep your first projects simple.

Personal opinion:
Do not vibe code. Instead, use AI to look over code you're written by yourself. And don't copy & paste stuff from AI suggestions if you don't understand the logic behind the code. The SugarCube documentation is amazing and very in-depth. Paired with AI suggestions and the SugarCube Discord, you should be good to go.

Good luck with your project!

Thank you very much. Is it possible to build this entire system without JavaScript and DOM, using only sugarcube macros? If so, I will switch to learning sugarcube macros directly instead of JavaScript.
 

PTSdev

Member
Oct 21, 2019
117
414
If you wanna replace sth on the page without a full passage reload, <<replace>> is your friend. Just keep in mind that the variable change is not stored in the history before the next passage transition happens, i.e. the final value before that transition will be stored. Then there are <<append>> and <<prepend>> which add / remove content.

You can also look at the new <<do>> / <<redo>> macros which simplify this even further.

To get a better understanding of how to implement a custom inventory system, you can look at , but this might be a bit too much for what you're trying to do. You basically just adding / removing stuff to / from an object / array. Of course, you can keep the JS functions if they do the job. A purely SugarCube based alternative is a custom <<widget>> that executes its code after a link has been clicked. SC is based on JS, so you always can go down the JS route. Things can get messy if you have JS scripts that "watch" the window while it's being rendered, as this both can affect styling options (nobr sometimes conflicts with this) and lead to unwanted behavior when it comes to the history.

If you want to include sth that is executed with every passage transition, familiarize yourself with the PassageRender / PassageDone special passages. PassageRender executes its contents BEFORE the passage is being displayed, PassageDone is for post-display events. Personally, I use PassageRender for cyclical tasks (like keeping track of core story variables like money, date/time, etc.) and PassageDone for an achievement system. Understanding how SC renders passages is really helpful in general.
 
  • Like
Reactions: osanaiko

osanaiko

Engaged Member
Modder
Jul 4, 2017
3,240
6,174
Thank you very much. Is it possible to build this entire system without JavaScript and DOM, using only sugarcube macros? If so, I will switch to learning sugarcube macros directly instead of JavaScript.
I'd say your question reveals one of those "leaky abstraction" situations: The answer is "Yes", you can build quite a lot of the functional parts of a game (like choices and tracking variables and branching paths) using just Sugarcube macros.

HOWEVER, the next problem lies in understanding how it works under the hood enough to be able to troubleshoot when things go wrong. And that's where getting at least some understanding of the DOM and javascript is helpful.

As a (rough and probably problematic) analogy, Sugarcube might be a powersaw and nailgun for a carpenter - it will speed up your ability to do stuff... but in the end they just make things faster, because you still need to understand the basics of how to use the raw materials to implement a design.

Also, remember that Sugarcube is just for flow control - the content and "layout" still needs to use HTML and CSS. Note that there is default CSS in the package, so you should certainly build stuff and get the game concept working, but accept that it will literally look exactly like all the other default projects. Still, it's better to walk before you try to run.
 
  • Like
Reactions: OldSailor
May 17, 2024
20
74
I'll throw my hat in the ring here a little bit.

From what I saw of the code it's an interesting mix between simple and unreasonably advanced. The inventory is basically an array and yet it appears you're dealing with the window object for some reason? Perhaps there's a reason for it, but I'm not sure why an inventory system would have to do that. (using the setup object may be better, but it's sugarcube specific so the llm may not know about it.) In addition the organization seems very unclear to my eye, things are thrown together and seem more dense and disconnected than I think they need to be. In one part it seems you're setting a variable to the result of a ternary statement? That's a relatively advanced and specific use of javascript. I think your llm is doing the equivalent of opening a can with a jackhammer.

The good news is that the code could probably be cleaned up without needing too much advanced programming knowledge. But I also think it's a bit difficult to figure out what the existing code is even doing in the first place, I suspect some of it may be doing nothing. (I looked into the code I suspected did nothing -window.setTimeout- it takes a function and executes it after a given delay. The delay given is 0)

Ok now let me get into a little bit more of the brass tacks. Javascript is probably the better way to go around making more advanced, complex custom systems. you can get decently far in it without needing too much advanced knowledge, and sugarcube is more or less based on javascript so there's a actually a lot of overlap. However sugarcube has some good built in tools for easier dom manipulation and stuff like that. For something like an inventory system you may want to look into objects and methods as a programming concept, and that type of stuff is a bit better to use javascript for.

As somebody pointed out, sugarcube's for loops are a bit odd, and may need additional knowledge to use correctly, this is one of the areas I feel like javascript may actually be more powerful and intuitive. And as far as modifying an array based inventory, either buying or selling, you're probably going to have to pick up knowledge on how to modify and work with arrays (And with javascript you're probably going to want to look into the splice method of the inbuilt array type)

I actually wouldn't mind helping out a bit! I've already built an inventory system and your's doesn't seem too complicated. And if you have any questions about sugarcube or javascript you can reach out to me if you'd like!
 

PTSdev

Member
Oct 21, 2019
117
414
Good post, Purple Nurple08.

On for loops: As stated in this thread, <<capture>> is what he needs if he wants to keep track of variable changes inside of for loops. You can also add multiple variables to the widget statement, e.g. <<capture _variable1 _variable2>>.

On array manipulation: For a simple inventory system, you only really need push, splice / delete / deleteAt (depending on how the system is supposed to work) and maybe some sorting stuff. As SC and JS overlap, it's easy to include those functions.

On the setTimeout thing: Agreed. This isn't necessary. If an array change occurs when the player clicks a link, you don't need to mess with JS DOM functions. It all depends on whether he wants to manipulate the page without a reload or not. Without fully reloading the passage, the widgets mentioned above do everything he needs.
 
  • Like
Reactions: OldSailor