开发者

How to switch between 3 different levels of a game using DOM and JavaScript? E.g. Easy, Medium and Hard

开发者 https://www.devze.com 2023-03-06 03:58 出处:网络
I\'m trying making a simple game using DOM and JavaScript, and within this game I\'ve 3 different levels: easy, medium and hard. By default when the page loads the easy level is used! But I want to be

I'm trying making a simple game using DOM and JavaScript, and within this game I've 3 different levels: easy, medium and hard. By default when the page loads the easy level is used! But I want to be able to switch between the 3 different levels using javascript!

It is possible to do this using javascript cookie session, so a particular function is being used/activated when a button is clicked, then that function is used until the user clicks on another button, say for example the medium level.

For example:

function easylevel() {
}

function mediumlevel() {
}

function hardlevel() {
}

So any of the above functions is activated and stored into a cookie session by clicking a button, for example:

<input type="button" onclick="easylevel()" value="Easy Level" />
<input type="button" onclick="mediumlevel()" value="Medium Level" />
<input type="button" onclick="hardlevel()" value="Hard Level" />

I've already tried this, but it doesn't works开发者_如何学编程, can somebody please explain me where I'm going wrong! I'm 200% sure that I'm wrong because I don't know much about JS, so need help and advice for sure!


If what you want is that a function is called repeatedly, then you could use setInterval

<script>
var intervalInMilliseconds = 1000; // change this to watever value you like
var activeInterval = undefined;
function startEasyLevel() {
    if (activeInterval) {
         clearInterval(activeInterval);
    }
    activeInterval = setInterval(easylevel, intervalInMilliseconds);
}
function startMediumLevel() {
    if (activeInterval) {
         clearInterval(activeInterval);
    }
    activeInterval = setInterval(mediumlevel, intervalInMilliseconds);
}
function startHardLevel() {
    if (activeInterval) {
         clearInterval(activeInterval);
    }
    activeInterval = setInterval(hardlevel, intervalInMilliseconds);
}
</script>

<input type="button" onclick="startEasyLevel()" value="Easy Level" />
<input type="button" onclick="startMediumLevel()" value="Medium Level" />
<input type="button" onclick="startHardLevel()" value="Hard Level" />

Add to this your current level functions and it should call the function every second. As soon as you click one of your buttons it will stop calling the current level function and continue to call the function associated with the clicked button.

If you want some level be loaded by default you can use the onload event of the window element:

window.onload = startEasyLevel;
0

精彩评论

暂无评论...
验证码 换一张
取 消