I'm building a simple little math flashcards game for my kids. Part of the appeal for them to play is the ability for them to "choose" a videogame character that will animate when the get a problem right or wrong.
Currently, my flashcards and code work fine. I have saved some animated GIFs for one videogame character in an /images
folder for different scenarios.
My kids would ostensibly choose their character from a select
element, then start the game and watch the magic happen.
I'm not a professional programmer, but it seems like there should be a more elegant way to call the appropriate set of GIFs based on the select. Rather than code a bunch of if/else
conditions for the 10 various characters they could choose.
Is there a way to put the src
path for the various GIFs in an array or object that could be called only for a specific character? Can someone help nudge me with some ideas?
I was thinking something like:
var chars = {
char1_right: "/path/to/this GIF",
char1_wrong: "/path/to/this GIF",
char2 etc...
}
then
var img = new Image();
var img.src = chars.??? // changed based on the select box selection
UPDATED SOLUTION: Based on @runcom's suggestion, I set up an object thusly:
var img_map = {
ken: {
win: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=KenPalette.bin&pcolornum=0&pname=ken/ken-fireball.gif',
lose: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=KenPalette.bin&pcolornum=0&pname=ken/ken-twist.gif'
},
ryu: {
win: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=RyuPalette.bin&pcolornum=0&pname=ryu/ryu-shoryuken.gif',
lose: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=RyuPalette.bin&pcolornum=0&pname=ryu/ryu-twist.gif'
},
dhal: {
win: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=OroPalette.bin&pcolornum=0&pname=oro/oro-uppercut.gif',
lose: 'http://www.zweifuss.ca/colorswap.php?pcolorstring=OroPalette.bin&pcolornum=0&pname=oro/oro-twist.gif'
}
};
and updated the img.src
attribute with this:
var img_win = new Image();
var img_lose = new Image();
img_win.src = img_map.ken.win;
img_lose.src = img_map.ken.lose;
$('#charac').on('change', function () {
var sel = $(this).val();
if (sel in img_map) {
img_win.src = img_map[sel].win;
img_lose.src = img_map[sel].lose;
}
});
Here is the example fiddle: http://jsfiddle.net/z17LgyLn/1/.