Creating a Running Game in VueJS - Part 1 - Moving
January 16, 2021
If, like me, you’re over the age of 35, you may have owned a Spectrum, Amstrad, or Commodore 64. One of the games, especially on the Spectrum, that was guaranteed to ruin your keyboard, and make your family think you were having some kind of fit, was Daley Thomson’s Decathlon.
In this post, I introduced the basics of writing a game in VueJS. In this series of posts, I’m going to try to recreate that game, at least in spirit. I’m afraid I won’t have the amazing graphics, but hopefully we can create something vaguely similar.
I’ll be putting the various parts in GitHub here. I made a similar series of posts using React; you can find them here.
In this first section, we’ll create a player (it’ll just be a box on the screen for now), and a timer. To get the code, look here.
We're simply binding the style of the **div** to one computed property, and **secondsRemaining** is another. Let's see what the **computed** section looks like next:
``` js
computed: {
location: function() {
return 'width:10px; height:10px; left:' + this.playerX + 'px; top:' + this.playerY + 'px; border:1px solid #000; position: absolute;';
},
secondsRemaining: function() {
const diff = (this.startTime - this.timeNow) / 1000;
return Math.round(diff);
}
},
Remember that this section will cause a screen refresh when the variables it uses change; it does not know that the function will return a different value otherwise; which is why I’m not getting the current time inside the secondsRemaining function.
The location will force an update when the playerX or playerY properties change. Let’s see the data:
This is the update method, but it’s more akin to a draw method: it’s limited to updating the variables that force a screen update. It also slows the runner down naturally (so if the player does nothing, the character will stop).
There’s just one more thing we have yet to see, and that’s the method that handles the keypress; which, in fact, is two methods:
One of the defining features of the original game was that you ran by pressing the left key, and then the right in quick succession; we’ve emulated this by simply setting a flag, and comparing them.
That’s it, the first part complete:
I know you’re probably wondering how I managed to great such amazing graphics!
The code works (after a fashion), but it’s messy. In Part 2, we’ll refactor this code into components.