0 votes
by (350 points)
edited by

I created a game in which the user has to make several decisions, and his choices change the values of some variables. At the end of the game, in the last passage, I would like to change the background image according to the variable that has the highest value.

I've already created the code to find the variable with the highest value. Now I just need to know how do I change the background image according to a variable.

For example:

If the variable $result is "A", the background image will be "img_A.jpg".
If the variable $result is "B", the background image will be "img_B.jpg".
If the variable $result is "C", the background image will be "img_C.jpg".

In the JavaScript Editor, I create some functions:

 

setup.resultA = function () {
	$(document.body).css('background-image', 'images/img_A.jpg');
};
setup.resultB = function () {
	$(document.body).css('background-image', 'images/img_B.jpg');
};
setup.resultC = function () {
	$(document.body).css('background-image', 'images/img_C.jpg');
};
setup.resultD = function () {
	$(document.body).css('background-image', 'images/img_D.jpg');
};
setup.resultE = function () {
	$(document.body).css('background-image', 'images/img_E.jpg');
};

 

And in the PassageReady, I put the code:

 

<<if tags().includes("changeBG") && $result is "A">>
	<<run setup.resultA()>>
<<elseif tags().includes("changeBG") && $result is "B">>
	<<run setup.resultB()>>
<<elseif tags().includes("changeBG") && $result is "C">>
	<<run setup.resultC()>>
<<elseif tags().includes("changeBG") && $result is "D">>
	<<run setup.resultD()>>
<<elseif tags().includes("changeBG") && $result is "E">>
	<<run setup.resultE()>>
<</if>>

 

But that didn't work.

Can someone help me?

1 Answer

0 votes
by (63.1k points)
edited by

"Didn't work" isn't a great description of what went wrong. If it just does nothing (probably the case here), say that. Sometimes people say something didn't work and don't report the error messages that could help us debug the issue. 

The issue is likely because you need to use "url(path/to/img)", not just the path. 

Also, there's a few things I think you could do more efficiently. First, I'd condense that all into one function: 

setup.changeBG = function (result) {
    if ["A", "B", "C", "D", "E"].includes(result) {
        var path = "url(images/img_" + result + ".jpg)";
        $(document.body).css("background-image", path);
    }
};

Then, you'd just do something like: 

<<if tags().includes("changeBG")>>
    <<run setup.changeBG($result)>>
<</if>>

 

...