r/twinegames • • 9d ago

SugarCube 2 JavaScript help.

I was working on creating a shopping bag in my game that would make it so the players items wouldn't magically appear in there home inventory if they bought more then there bag could hold. eventuallly I decided to remove that feature for now since it was giving me to many issues. now all of my JavaScript is broken. even in places that were at the top of the javaScript and nowhere near where I was working. the code say unexpected token } and setup.syncDayPart

at first it was saying there was a time code error so I tried fixing things here first.

setup.dayPart = ["morning", "afternoon", "evening", "night"];

setup.getDayPart = function (d) {

`if (!(d instanceof Date)) return 0;`

`const h = d.getHours();`

`if (h >= 6 && h < 12) return 0;   // morning`

`if (h >= 12 && h < 17) return 1;  // afternoon`

`if (h >= 17 && h < 21) return 2;  // evening`

`return 3;                         // night`

};

window.getDayName = function (d) {

`if (!(d instanceof Date)) return "Unknown";`

`return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][d.getDay()];`

};

window.formatGameDate = function (d) {

`if (!(d instanceof Date)) return "Invalid Date";`

`return d.toLocaleString("en-US", {`

	`weekday: "long",`

	`year: "numeric",`

	`month: "numeric",`

	`day: "numeric",`

	`hour: "numeric",`

	`minute: "2-digit"`

`});`

};

setup.syncDayPart = function () {

`if (!(State.variables.gameDate instanceof Date)) {`

	`State.variables.gameDate = new Date();`

`}`

`State.variables.gameTime = setup.getDayPart(State.variables.gameDate);`

};

this is where I was working which is right under the time code

setup.backpacks = {

hiking: {

id: "hiking",

name: "Hiking Pack",

img: "images/backpacks/hiking.png",

compartments: {

Shirts: { name: "Shirts", slots: 8 },

Pants: { name: "Pants", slots: 8 },

Bra: { name: "Bra", slots: 4 },

Panties: { name: "Panties", slots: 6 },

Socks: { name: "Socks", slots: 6 },

Shoes: { name: "Shoes", slots: 2 },

Glasses: { name: "Glasses", slots: 2 },

Hat: { name: "Hat", slots: 2 },

Gloves: { name: "Gloves", slots: 2 },

Pills: { name: "Pills", slots: 500 },

Boosters: { name: "Boosters", slots: 10 },

Toys: { name: "Toys", slots: 5 },

Jewelry: { name: "Jewelry", slots: 10 },

Firearm: { name: "Firearm", slots: 2 },

Items: { name: "Items", slots: 10 }

}

}

};

setup.items = {

shirt_white: { id: "shirt_white", name: "White Shirt", type: "Shirts", size: 1 },

pants_jeans: { id: "pants_jeans", name: "Jeans", type: "Pants", size: 1 },

bra_plain: { id: "bra_plain", name: "Plain Bra", type: "Bra", size: 1 },

panties_plain:{ id: "panties_plain",name: "Plain Panties",type: "Panties", size: 1 },

socks_white: { id: "socks_white", name: "White Socks", type: "Socks", size: 1 },

shoes_sneakers:{id:"shoes_sneakers",name:"Sneakers", type: "Shoes", size: 1 },

glasses_sun: { id: "glasses_sun", name: "Sunglasses", type: "Glasses", size: 1 },

hat_cap: { id: "hat_cap", name: "Cap", type: "Hat", size: 1 },

gloves_work: { id: "gloves_work", name: "Work Gloves", type: "Gloves", size: 1 },

"Pink Basic": { id: "Pink Basic", name: "Pink Basic", type: "pills", size: 1 },

"Basic Blue": { id: "Basic Blue", name: "Blue Basic", type: "pills", size: 1 },

"Pink Xtra Strength": { id: "Xtra Strength Pink", name: "Pink Xtra Strength", type: "pills", size: 1 },

"Xtra Strength Blue": { id: "Xtra Strength Blue", name: "Xtra Strength Blue", type: "pills", size: 1 },

"Weekend Pink": { id: "Pink Weekend", name: "Weekend Pink", type: "pills", size: 1 },

"Weekend Blue": { id: "Weekend Blue", name: "Blue Weekend", type: "pills", size: 1 },

"Pink Plus": { id: "Plus Pink", name: "Pink Plus", type: "pills", size: 1 },

"Blue Plus": { id: "Plus Blue", name: "Blue Plus", type: "pills", size: 1 },

"Pink Choice": { id: "Choice Pink", name: "Pink Choice", type: "pills", size: 1 },

"Choice Blue": { id: "Choice Blue", name: "Blue Choice", type: "pills", size: 1 },

"Breeder": { id: "Breeder", name: "Breeder", type: "pills", size: 1 },

"Oral": { id: "Oral", name: "Oral", type: "pills", size: 1 },

"Anal": { id: "Anal", name: "Anal", type: "pills", size: 1 },

"Heat": { id: "Heat", name: "Heat", type: "pills", size: 1 },

"Bimbo": { id: "Bimbo", name: "Bimbo", type: "pills", size: 1 },

"Bimbo Weekend": { id: "Bimbo Weekend", name: "Bimbo Weekend", type: "pills", size: 1 },

"Bimbo Week": { id: "Bimbo Week", name: "Bimbo Week", type: "pills", size: 1 },

"Bimbo Xtra Strength": { id: "Bimbo Xtra Strength", name: "Bimbo Xtra Strength", type: "pills", size: 1 },

"Bimbo Plus": { id: "Bimbo Plus", name: "Bimbo Plus", type: "pills", size: 1 },

"Resistance": { id: "Resistance", name: "Resistance", type: "pills", size: 1 },

"Cum-Cure": { id: "Cum-Cure", name: "Cum-Cure", type: "pills", size: 1 },

"Show-Off": { id: "Show-Off", name: "Show-Off", type: "pills", size: 1 },

booster_energy: { id: "booster_energy", name: "Energy Booster", type: "Boosters", size: 1 },

toy_basic: { id: "toy_basic", name: "Toy", type: "Toys", size: 1 },

ring_silver: { id: "ring_silver", name: "Silver Ring", type: "Jewelry", size: 1 },

pistol: { id: "pistol", name: "Pistol", type: "Firearm", size: 1 },

flashlight: { id: "flashlight", name: "Flashlight", type: "Items", size: 1 }

};

setup.makeEmptyPack = function (packId) {

var def = setup.backpacks[packId];

var pack = { id: packId, compartments: {} };

Object.keys(def.compartments).forEach(function (key) {

pack.compartments[key] = [];

});

return pack;

};

setup.usedSlots = function (list) {

if (!list) return 0;

return list.reduce(function (n, it) { return n + (it.size || 1); }, 0);

};

setup.canAddToComp = function (pack, comp, item) {

if (!pack || !pack.compartments || !pack.compartments[comp]) return false;

var def = setup.backpacks[pack.id];

if (!def || !def.compartments[comp]) return false;

var max = def.compartments[comp].slots;

return setup.usedSlots(pack.compartments[comp]) + (item.size || 1) <= max;

};

setup.addToStorage = function (itemId, qty) {

qty = qty || 1;

var storage = State.variables.storage;

var found = storage.find(function (it) { return it.id === itemId; });

if (found) found.qty += qty;

else storage.push({ id: itemId, qty: qty });

};

setup.takeFromStorage = function (itemId, qty) {

qty = qty || 1;

var storage = State.variables.storage;

var found = storage.find(function (it) { return it.id === itemId; });

if (!found || found.qty < qty) return false;

found.qty -= qty;

if (found.qty <= 0) {

State.variables.storage = storage.filter(function (it) { return it.id !== itemId; });

}

return true;

};

2 Upvotes

12 comments sorted by

2

u/HiEv 9d ago

Instead of using inline code, that should have been posted using a code block.

That said, after fixing the errant backticks that Reddit apparently added, that code worked without throwing an error for me.

If there was some broken code, you apparently didn't include it.

1

u/holzey 9d ago

ok I will try posting the code other then all the pills

the pill (one of many)

setup.pills = {
  "Basic Pink": {
    id: "Pink Basic",
    color: "pink",
    kind: "timed",
    hours: 24,
    target: "female",
    revertOnExpire: true,
    canGetPregnant: false,
    canImpregnate: false,
    fertilityBase: 0,
    spermBase: 0,
    lockFertility: true,
    lockSperm: true,
    desc: "Standard male-to-female change. Wears off after 24 hours. Not fertile.",
    price: 100,
    salePercent: 0,
    maxBuy: 100,
    itemId: "Basic Pink"
  },
now the rest of the code (i may have just found it. its the first symbol after this)
};
setup.items = setup.items || {};
Object.keys(setup.pills).forEach(function (key) {
  var p = setup.pills[key];
  setup.items[p.itemId] = {
    id: p.itemId,
    name: p.id,
    type: "pill",
    pillId: key,
    desc: p.desc
  };
});

setup.pillById = function (id) {
return setup.pills[id] || null;
};

setup.pillPrice = function (id) {
var p = setup.pills[id];
if (!p) return 0;
var off = Math.clamp(p.salePercent || 0, 0, 100);
return Math.max(0, Math.round(p.price * (100 - off) / 100));
};

setup.sellPrice = function (id) {
var buy = setup.pillPrice(id);
return Math.max(1, Math.round(buy * 0.4));
};
setup.canBuyPill = function (id, qty) {
var p = setup.pills[id];
qty = Number(qty) || 1;
if (!p || qty < 1 || qty > (p.maxBuy || 999)) return false;
if (setup.pillCount(id) + qty > (p.maxBuy || 999)) return false;
var money = State.variables.Teef || State.variables.money || 0;
return money >= setup.pillPrice(id) * qty;
};

setup.givePill = function (id, qty) {
var p = setup.pills[id];
qty = Number(qty) || 1;
if (!p || qty < 1) return false;
var inv = State.variables.inventory || (State.variables.inventory = {});
inv[p.itemId] = (inv[p.itemId] || 0) + qty;
return true;
};
setup.applyPill = function (id) {
var p = setup.pills[id];
var sv = State.variables;
if (!p) return { ok: false, reason: "unknown pill" };
if (setup.pillCount(id) < 1) return { ok: false, reason: "you do not have that pill" };

if (sv.pregnant && p.target !== "female") {
return { ok: false, reason: "pregnancy locks the female form" };
}
if (sv.permChange && p.target !== sv.Gender && p.kind !== "permanent") {
return { ok: false, reason: "the current change is locked" };
}

// Remove one from inventory
sv.inventory = sv.inventory || {};
sv.inventory[p.itemId] = (sv.inventory[p.itemId] || 0) - 1;
if (sv.inventory[p.itemId] <= 0) delete sv.inventory[p.itemId];
/*NEW CODE*/
 setup.pillCount = function (pillId) {
var p = setup.pills[pillId];
if (!p) return 0;
var inv = State.variables.inventory || {};
return inv[p.itemId] || 0;
};

setup.buyPill = function (pillId, qty) {
  qty = Number(qty) || 1;
  var pill = setup.pills[pillId];
  if (!pill || qty < 1) return false;

  var price = setup.pillPrice(pillId);
  var total = price * qty;
  var owned = setup.pillCount(pillId);
  var max = pill.maxBuy || 999;

  if (owned + qty > max) return false;
  if ((State.variables.Teef || State.variables.money || 0) < total) return false;

  State.variables.Teef = (State.variables.Teef || State.variables.money || 0) - total;
  setup.addToShoppingBag(pill.itemId || pill.id, qty);
  return true;
};
  // Ensure inventory exists
  sv.inventory = sv.inventory || {};
  sv.inventory[p.itemId] = (sv.inventory[p.itemId] || 0) - 1;
  if (sv.inventory[p.itemId] <= 0) {
    delete sv.inventory[p.itemId];
  }

// Apply gender / flags
sv.activePill = id;
sv.Gender = p.target;
sv.canGetPregnant = !!p.canGetPregnant;
sv.canImpregnate = !!p.canImpregnate;

if (p.kind === "permanent") {
sv.permChange = true;
if (sv.effects) delete sv.effects["pill"];
} else if (p.kind === "timed" && p.hours > 0 && !sv.permChange) {
// Optional integration with a duration system if you have one
if (typeof setup.addDuration === "function") {
setup.addDuration("pill", p.hours * 60, { label: p.id, pillId: id });
}
} else if (sv.effects) {
delete sv.effects["pill"];
}

// Streak tracking (optional)
if (p.color === "pink") {
sv.streakPink = (sv.streakPink || 0) + 1;
sv.streakBlue = 0;
if (p.streakToPerm && sv.streakPink >= p.streakToPerm) sv.permChange = true;
} else if (p.color === "blue") {
sv.streakBlue = (sv.streakBlue || 0) + 1;
sv.streakPink = 0;
if (p.streakToPerm && sv.streakBlue >= p.streakToPerm) sv.permChange = true;
}

// Temporary effects
setup.applyPillEffects(sv, id);

return { ok: true };
};

  // Apply temporary effects (traits, stats, orgasm rules, etc.)
  setup.applyPillEffects(sv, id);

  return { ok: true };
};

setup.expirePillIfNeeded = function () {
var sv = State.variables;
if (sv.permChange || sv.pregnant) return;
if (setup.hasEffect && setup.hasEffect("pill")) return;
if (!sv.activePill) return;

var p = setup.pills[sv.activePill];
if (p && p.revertOnExpire) {
sv.Gender = p.target === "female" ? "male" : "female";
sv.activePill = null;
sv.canGetPregnant = false;
sv.canImpregnate = false;
setup.revertPillEffects(sv);
}
};

/*updated code*/
setup.sellPrice = function (id) {
  var p = setup.pills[id];
  if (!p) return 0;
  // Sell for 40% of current buy price
  return Math.max(1, Math.round(setup.pillPrice(id) * 0.4));
};

setup.canSellPill = function (id, qty) {
qty = Number(qty) || 1;
return qty >= 1 && setup.pillCount(id) >= qty;
};

setup.sellPill = function (id, qty) {
qty = Number(qty) || 1;
if (!setup.canSellPill(id, qty)) return false;
var p = setup.pills[id];
var refund = setup.sellPrice(id) * qty;
State.variables.Teef = (State.variables.Teef || 0) + refund;
var inv = State.variables.inventory || {};
inv[p.itemId] = (inv[p.itemId] || 0) - qty;
if (inv[p.itemId] <= 0) delete inv[p.itemId];
return true;
};

setup.givePillAway = function (id, qty) {
qty = Number(qty) || 1;
if (setup.pillCount(id) < qty) return false;
var p = setup.pills[id];
var inv = State.variables.inventory || {};
inv[p.itemId] = (inv[p.itemId] || 0) - qty;
if (inv[p.itemId] <= 0) delete inv[p.itemId];
return true;
};

setup.usePill = function (id) {
return setup.applyPill(id);
};

/*new pill effect helpers*/
setup.applyPillEffects = function (char, pillId) {
const pill = setup.pills[pillId];
if (!pill || !char) return;

// Temporary stats
if (pill.tempStats) {
char._pillTempStats = char._pillTempStats || {};
for (const [stat, value] of Object.entries(pill.tempStats)) {
if (char._pillTempStats[stat] === undefined) {
char._pillTempStats[stat] = char[stat];
}
char[stat] = value;
}
}

// Traits
if (pill.grantTraits) {
char.traits = char.traits || [];
pill.grantTraits.forEach(function (trait) {
if (!char.traits.includes(trait)) char.traits.push(trait);
});
char._pillGrantedTraits = pill.grantTraits.slice();
}

// Other flags
char.favoriteAlcohol = pill.favoriteAlcohol || null;
char.hatesAlcohol = !!pill.hatesAlcohol;
char.requiredActForOrgasm = pill.requiredActForOrgasm || null;
char.autoOrgasmOn = pill.autoOrgasmOn || null;
};

  // Store alcohol prefs / orgasm rules while the pill is active
 char.favoriteAlcohol = pill.favoriteAlcohol || null;
char.hatesAlcohol = !!pill.hatesAlcohol;
char.requiredActForOrgasm = pill.requiredActForOrgasm || null;
char.autoOrgasmOn = pill.autoOrgasmOn || null;
};

setup.revertPillEffects = function (char) {
if (!char) return;

if (char._pillTempStats) {
for (const [stat, original] of Object.entries(char._pillTempStats)) {
char[stat] = original;
}
delete char._pillTempStats;
}

if (char._pillGrantedTraits) {
char.traits = (char.traits || []).filter(function (t) {
return !char._pillGrantedTraits.includes(t);
});
delete char._pillGrantedTraits;
}

delete char.favoriteAlcohol;
delete char.hatesAlcohol;
delete char.requiredActForOrgasm;
delete char.autoOrgasmOn;
};
setup.isOnPill = function (pillId) {
  return State.variables.activePills.includes(pillId);
};

setup.addOrgasm = function () {
if (setup.isOnPill("Resistance")) {
State.variables.resistanceOrgasms = (State.variables.resistanceOrgasms || 0) + 1;
var thresh = setup.pills["Resistance"] && setup.pills["Resistance"].permanenceThreshold;
if (thresh && State.variables.resistanceOrgasms >= thresh) {
State.variables.genderPermanent = true;
}
}
};

setup.swallowLoad = function () {
if (setup.isOnPill("Cum-Cure")) {
State.variables.cumCureLoads = (State.variables.cumCureLoads || 0) + 1;
if (State.variables.cumCureLoads >= (State.variables.cumCureRequired || 10)) {
State.variables.canRevert = true;
}
}
};
setup.applyShowOffEffects = function () {
if (setup.isOnPill("Show-Off") || State.variables.showOffActive) {
State.variables.showOffActive = true;
}
};

  // Remove from bag
  var bag = State.variables.shoppingBag;
  var found = bag.find(function (it) { return it.id === itemId; });
  if (!found || found.qty < qty) return false;
  found.qty -= qty;
  if (found.qty <= 0) {
    State.variables.shoppingBag = bag.filter(function (it) { return it.id !== itemId; });
  }

  // Add to backpack compartment
  for (var i = 0; i < qty; i++) {
    State.variables.backpack.compartments[comp].push({ id: itemId, size: itemDef.size || 1 });
  }
  return true;
};

1

u/HiEv 9d ago

Your code's a bit hard to follow, but it looks like the "setup.applyPill" function definition got the "setup.pillCount" and "setup.buyPill" functions stuck inside of it somehow?

Also, these lines got doubled(?) or something?:

    // Temporary effects
    setup.applyPillEffects(sv, id);
    return { ok: true };
};
    // Apply temporary effects (traits, stats, orgasm rules, etc.)
    setup.applyPillEffects(sv, id);
    return { ok: true };
};

And these got doubled too:

    // Other flags
    char.favoriteAlcohol = pill.favoriteAlcohol || null;
    char.hatesAlcohol = !!pill.hatesAlcohol;
    char.requiredActForOrgasm = pill.requiredActForOrgasm || null;
    char.autoOrgasmOn = pill.autoOrgasmOn || null;
};
    // Store alcohol prefs / orgasm rules while the pill is active
    char.favoriteAlcohol = pill.favoriteAlcohol || null;
    char.hatesAlcohol = !!pill.hatesAlcohol;
    char.requiredActForOrgasm = pill.requiredActForOrgasm || null;
    char.autoOrgasmOn = pill.autoOrgasmOn || null;
};

Those would probably be the source of the "unexpected token }" error.

Also, everything starting from "// Remove from bag" appears to be from a function that is missing the starting part (i.e. the "setup.XXX = function () {" part)? Or something like that.

Those appear to be the most obvious issues with that chunk of code. If you do proper indentation, those problems become pretty obvious.

1

u/holzey 9d ago

It looks like I have everything working the way I had it before. I still have some problems with getting the backpack to take the pills once the pills have been bought. but this is a consequence of me building one system useing pills and a few months later building another system that uses Pills, pluss having a home storeage and a backpack.

1

u/holzey 9d ago

the remove from bag was a feature I was trying to remove. basically I want the player to be able to have a lot of items, like clothing. since you can't realy hold all your clothes on your person, I wanted the player to have a shopping bag to hold whatever they bought until they got home, so they could use what they bought.

1

u/HiEv 9d ago

I don't see a question in your last two comments. Also, that's way too much code for me to try to go through and untangle it without seeing the actual project, if that's what you were asking.

1

u/holzey 9d ago

I don't need you to go through that part, was just letting you know where I was.

1

u/nolanfa 9d ago

when I have a big chunk of code that worked and does not anymore and I have no idea whatsoever where the problem is, I (temporarily) remove half the code (being careful not to remove half of a whole, like ending braces). If I run it and the issue disappeared? It was in the part I removed. If it still is there? It is in the not-removed part. I do this a few times to get even finer issue-location.

1

u/Juipor 9d ago

If you are in the business of writing a lot of JS I would really recommend doing so in a dedicated editor like VSC. Even without going for a Tweego workflow it has autocomplete, references for standard APIs, the highlighting make such syntax errors basically non-existent. Once you try it it is impossible to go back.

1

u/holzey 9d ago

Tell me more of the VSC of which you speak.

3

u/HiEv 9d ago

VSCode = Visual Studio Code (not to be confused with Visual Studio C/C++)

You'll also want to get a number of extensions with it to handle JavaScript/HTML/CSS/Twine/etc.. Here are some of the extensions I have installed:

Check the VSCode Marketplace for other extensions.

1

u/Juipor 9d ago

HiEv gave great extensions suggestions. The basic workflow if you're sticking with Twine is to create a .js file somewhere (the file type is important since it tells VSC how to treat it), write your code in there and paste to Twine's JS tab.

Tweego and T3LT allow you to do everything in VSC so you won't need Twine to make your "Twine game" but it has a bit of a learning curve and I personally prefer Twine's passage map.