HTML How can I display a random image from a folder if the initial image does not exist? (Twine 2 - Sugarcube 2)

KingCocoa

Newbie
Jul 23, 2017
23
3
I have a few passages where the code will display a specific image relevant to the current character, but if that character doesn't have a corresponding image, it will show a "generic" image instead.

For the passage I'm currently writing, I have it set to the same thing, but I would love to have multiple "generic" images available so it doesn't get stale for the player. Is this possible? I've tried so many variations of the code and it just won't run. I either get an error or it just prints the code. Has anyone done anything like this before?
 

KingCocoa

Newbie
Jul 23, 2017
23
3
Sounds like this thread is close enough to what you're asking:
https://f95zone.to/threads/how-to-call-on-random-images.107847/
Thank you.

Looks like this would work if I'm just trying to get a random image, but I'm specifically looking to call a random image only in the event of an initial image not existing.

Basically I have 100+ NPCs, only 10 of them are considered major characters and have their own unique images. The others will rely on a random pool of images... if it's possible.

Example:

Code:
<img @src="'event/meet/greeting/' + $npc.var + '.gif'" onerror="''">
The first part of the code works perfectly on it's own. I just can't work out how to call for random images in the onerror= section.
 

Alcahest

Engaged Member
Donor
Game Developer
Jul 28, 2017
3,153
4,047
One way you could do it is like this:

Code:
onerror="SugarCube.setup.randomImage()"

/* and then in JavaScript section */

setup.randomImage = function() {
    //code to display random image
}
Might be better ways. I don't have time to code the javascript function right now.
Anyway, even with this onerror call, the broken image symbol will still be shown. Not sure you can fix that. I never worked with onerror.
 

guest1492

Member
Apr 28, 2018
312
262
It'd probably be a good idea to write your own macro (I'm not sure that a widget would be good enough) to do this. I have no idea how you want to figure out what random images you want to replace it with though.
 

KingCocoa

Newbie
Jul 23, 2017
23
3
I have found a workaround.. I'm going to create an array for the characters that have images relevant to situations. eg
Code:
<<set $GreetingsImages = ["CharacterName","OtherCharacter"]
Then in the passage I can use
Code:
<<if $GreetingsImages.includes("CharacterName")>> IMAGE PATH <<else>> GENERIC IMAGE PATH
Messy, but I just tested it and it works fine.