Is there a way to do something every time a variable changes?

Started by newwaveburritos, Thu 29/07/2021 04:59:14

Previous topic - Next topic

newwaveburritos

So, I've got a journal in the game, and as you meet and get to know people in the game your "friendship level" so to speak increases.  Well, after scripting quite a few I realized it would be a good idea to give the player some feedback that something in their journal has changed so I had the idea to play a sound.  I could search through and find every instance of "ChefRomanFriendshipPoints++;" et al but I think it might be easier to have a couple of lines of code that plays the sound when anything changes.

I have a hunch that someone is going to tell me that this is exactly what for loops are for and how come I haven't actually learned how to use them yet.

Thanks again, everybody!!

Khris

Sorry, no for loops :)

It gets worse: you have to search and replace all those  ChefRomanFriendshipPoints++;  lines. You cannot detect a change in a variable, but since you are the one making it, you can call a function instead:

Code: ags
function FriendshipChefRoman(int change) {
  ChefRomanFriendshipPoints  = change;
  aFriendshipincrease.Play();
}


You then call  FriendshipChefRoman(1);  to add one to the value and also play the sound.

Using the full capabilities of AGS you can of course change this to

Code: ags
function ChangeNPCLevel(Character *npc, eLevel level, int by) {
  levels[npc.ID].value[level]  = by;
  if (by > 0) aLevelincrease.Play();
  else aLeveldecrease.Play();
}


This requires some more setup of course (a struct to store the levels and an enum containing  eLevelFriendship  etc.)

newwaveburritos

Okay, this makes sense.  I'm not super clear on using structs to keep everything organized although, in theory, it does make sense.  I've just been using the journal itself to track it when testing.  I do have kind of a lot of characters to track so maybe I should try this.

Khris

Here's the full code:
Code: ags
// header
enum Stat {
  eFriendship, eLove
};

struct CharStat {
  int level[3]; // amount of stats
};

import void ChangeLevel(this Character*, Stat stat, by = 1);


Code: ags
CharStat stats[30]; // highest ID if NPC + 1

void ChangeLevel(this Character*, Stat stat, int by) {
  stats[this.ID].level[stat] += by;
  if (by > 0) aLevelincrease.Play();
  if (by < 0) aLeveldecrease.Play();
}


Call it like:
Code: ags
  cChefRoman.ChangeLevel(eFriendship);  // default change: +1

newwaveburritos

Oh, thanks!  I'm sure this will come in useful.  It's a real learning experience, too.

SMF spam blocked by CleanTalk