DEV Community

Sadick
Sadick

Posted on • Originally published at Medium on

Make a simple game with Vuejs

Re-type the number you see below. Ez right?

Vuejs Memory Game

The idea is simple. Display a number and then let the user type the number they see on screen. There is a twist though. We start by displaying single digit number and then we proceed by adding the number of digits displayed as the user goes to higher levels. We also introduce a timeout display on the number, such that the number will display only for a specific duration and then it will be hidden from the user. Ez right?

I am going to skip the html and css part and get right into the vuejs part and making the game.

Generating a random number.

Generating a random number in javascript is pretty easy. Just throw in Math.random() and we are done. The problem though is Math.random() only generates a random number between 0 and 1. We want to be able to generate integers with n number of digits. The code below enables us to do that.

Now that generating a random number is taken care of let’s make a new vue instance with the game setup.

Lets imagine that the user has already seen the number, how long should we wait before hiding it? This is how i did it. let time = this.level * 160 . There is no special thing about the 160 . After testing with various interval i concluded that this interval would be pretty fair. We will use setTimeout to hide the number by calling hideNumber() function.

One last thing. We need to display a number a soon our component is loaded. In vuejs this is simple. We need to place our code in the mounted function.

Putting it together.

The demo.

Vuejs Memory Game

This post was inspired by Pham Mikun’s codepen (React Version)

Top comments (1)

Collapse
 
webdeasy profile image
webdeasy.de

Nice one! :D Simple, but it's perfect to understande the Vue technic by a practical example.