Ask coding questions

← Back to all posts
Unexpected end of input?
AIC27 (0)

I am trying to make a simple canvas game, but after creating a simple input/output system, the code won't run, and an "unexpected end of input" error is returned. (Also, I'm open to suggestions on how to make my code more efficient as well because I'm doing this on chrome OS)

Answered by BananaJellyfish (199) [earned 5 cycles]
View Answer
Comments
hotnewtop
BananaJellyfish (199)

I dont really code in html, but i think it might be because you forgot to close a bracket off somewhere? Hope this helps!

AIC27 (0)

@BananaJellyfish yep,forgot a bracket 🤦

xxpertHacker (865)

Also, I'm open to suggestions on how to make my code more efficient as well...)

Well, there's this:

if ( myCanvas.key && myCanvas.key == 37) {
    this.speed == 1;
}
if ( myCanvas.key && myCanvas.key == 39 ) {
    this.speed == -1;
}
if ( myCanvas.key == false ) {
    this.speed == 0;
}

First, we have a bug, these should be assignment operators, not equality (=), then, it can be optimized to this:

const { key } = myCanvas;

if ( key !== false ) {
    if ( key === 37 ) {
        this.speed = 1;
    } else if ( key === 39 ) {
        this.speed = -1;
    } else {
        this.speed = 0;
    }
}

and further to:

const { key } = myCanvas;

if ( key !== false ) {
    this.speed = key === 37
        ? 1
        : key === 39
            ? -1
            : 0;
}

but really, I'd expect JS loading to be the slowest part of this once it get larger.

I'd suggest learning about ESM modules, and using this HTML:

...
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <script type="module" src="script.mjs"></script>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>
...

This will let the browser send the HTTP request for the JS before it has finished parsing and rendering the document.

Really, to put the JS at the end of the document is just laziness.

Also, btw, you have another bug:

window.onload = startGame()

onload is supposed to be a function that is called once the page has loaded.

should be:

window.onload = startGame;

or

window.addEventListener(
    "load",
    startGame, {
        once: true // listener is removed after calling startGame
        // which should help w/ memory usage, aside from more accurately
        // showing your intent
    }
);
xxpertHacker (865)

Whoa, the problem was still the missing bracket, wasn't it?