I am making this 2d canvas game in JavaScript and I want to switch to file level2/level2.html when the boss of level 1 (level1/level1.html) is dead. This way I can have my stuff organized better.

This is the condition statement where I want to put the file change.

if(e.bosshealth <= 0){
  enemies = [];
  alert("LEVEL 1 COMPLETED");
  // I want the file switch to be here if possible.

You can navigate to another URL by setting the variable window.location.href = url or with the function window.location.replace(url).

The difference between the two methods is how the browser's back-button will behave. The first one will generate a separate navigation history entry for each level while the second one will not.

But, you should consider if making each level an own HTML document is really a good architecture. It will cause a variety of problems:

  • Technical complications with passing data between two levels.
  • Long loading times on level changes, because the whole game needs to be reloaded from the server.
  • It makes development more tedious, because when you change something, you might have to make the change to the files of every single level.
  • Each level having its own URL will allow players to bypass your level navigation by sharing the URLs to later levels

For these reasons, you should look into ways to create your game as a single-page application. When the player completed a level, load the data for the next level and switch out the level without leaving the application.

  • \$\begingroup\$ thank you so much , it worked perfectly! \$\endgroup\$ – Chrissisbeast Oct 28 '19 at 12:37
  • \$\begingroup\$ by the way , making it a single-page application ,won't it make the code so much more and more complicated rather then separating it in different files. \$\endgroup\$ – Chrissisbeast Oct 28 '19 at 12:46
  • \$\begingroup\$ @Chrissisbeast Yes, the code will get slightly more complicated because you now need to handle the case of loading a new level when you already have a level loaded. But it will make development much easier in the long term because any changes you make to your game architecture will automatically be applied to all levels. \$\endgroup\$ – Philipp Oct 28 '19 at 13:09
  • \$\begingroup\$ One more question , In my game i have my hero , the enemies and the boss as different .js files and then i just put them in my html as <script> src="...js"</script> is that a good idea or it will just slow down the loading as well and i would rather put everything in one file. \$\endgroup\$ – Chrissisbeast Oct 29 '19 at 17:57
  • \$\begingroup\$ Because i saw this method from the YT channel The coding train and i thought its a really good idea to organize my code. \$\endgroup\$ – Chrissisbeast Oct 29 '19 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.