Create a game with JavaScript in 5 minutes!!

Anthony Mwaura
Geek Culture
Published in
7 min readNov 26, 2022

--

Hello there, i recently made this amazing game in JavaScript and decided to share it here. The game applies events driven programming hence it is easy to understand and quick to build. The game captures the speed of a player when typing and outputs the time taken. It has an array of words that it shows to a player and loops through a word as the player is typing.

The code uses JavaScript programming language though you can use any language. Since this output is displayed on the browser, JavaScript is more suited here. HTML and CSS is also used here. I originally decided to try out making this game so as to understand how events in JavaScript are handled.

What are events though?

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them. For example when a user clicks on a button in a webpage, the user expects a reaction such as displaying an information box or redirecting to another page like a submit button.

Other examples from mdn web docs to aid your curiosity include:

  • The user selects, clicks, or hovers the cursor over a certain element.
  • The user chooses a key on the keyboard.
  • The user resizes or closes the browser window.
  • A web page finishes loading.
  • A form is submitted.
  • A video is played, paused, or ends.
  • An error occurs.

To react to an event, a programmer attaches an event listener which now reacts to the event after the event fires. The listener, as the name suggests, listens to an event and responds to it via an event handler which handles the event.

The Code

HTML is used here to provide a visual interface where a user may type into.

<!DOCTYPE html>
<html>
<head>
<title>This is an event Driven Game</title>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="./style.css"/>
<script src="./script.js" defer></script>
</head>
<body>
<h1>Typing game!</h1>
<p>Practice your typing skills with a quote from Sherlock Holmes. Click **start** to begin!</p>
<p id="quote"></p><!-- This displays our quote -->
<p id="message"></p><!-- This displays status message -->
<div>
<input type="text" aria-label="current word" id="typed-value" />
<button type="button" id="start">Start</button>
</div>
</body>
</html>

JavaScript uses the id attributes within the paragraph tags, input tag and button tag, to manipulate the tags and display text on the browser.

We also have CSS to provide a little bit of styling to the game.

body{
background-color: #cca3ed;
}
h1{
text-align: center;
font-family: sans-serif, Arial, Helvetica;
}
.highlight{
background-color: yellow;
}
.error{
background-color: lightcoral;
border: red;
}

Now we move on to the main dish on the menu, JavaScript!

At the very top of the script, we have an array with a list of quotes.

const quotes = [
'When you have eliminated the Impossible, whatever remain, howevre impossible, must be completed',
'There is nothing more deceptive than an obviuos fact',
'I ought to know by this time that when a fact appears to be opposed to a long train of deductions it invariably proves to be capable of bearing some other interpretation.',
'I never make exceptions. An exception dispoves the rules',
'What one man can invent, another can discover',
'Nothing clears up a case so much as stating it to another person',
'Education never ends, Watson. Life is a series of learning and learning until the day we die.'
];

This array stores the data that the game tests you against to see how fast you can type. An array in simple terms is a collection of elements of the same type.

Just like a recipe, this is what we need:

  • Array with the list of all quotes
  • Empty array to store all the words for the current quote
  • Space to store the index of the word the player is currently typing
  • The time the player clicked start

We’re also going to want references to the UI elements:

  • The textbox (typed-value)
  • The quote display (quote)
  • The message (message)
let words = [];
let wordIndex = 0;
let startTime = Date.now();
const quoteElement = document.getElementById('quote');
const messageElement = document.getElementById('message');
const typedvalueElement = document.getElementById('typed-value');

The empty array stores all the words for the current quote. Say the quote being displayed is maybe the second one ‘There is nothing more deceptive than an obvious fact’, then this will be the quote to be stored in the empty array. The wordIndex variable is used as space to store the index of the word the user is currently typing. The startTime variable shows the time when the user has started typing. This is useful to measure how long the user has typed thus far hence compute time taken to type the quote.

Adding the start logic

document.getElementById('start').addEventListener('click', () =>{
const quoteIndex = Math.floor(Math.random() * quotes.length);
const quote = quotes[quoteIndex];
words = quote.split(' ');
wordIndex = 0;
const spanWords = words.map(function(word) { return `<span>${word} </span>`});
quoteElement.innerHTML = spanWords.join('');
quoteElement.childNodes[0].className = 'highlight';
messageElement.innerText = '';
typedvalueElement.value = '';
typedvalueElement.focus();
startTime = new Date().getTime();
});

As shown above, an event listener is used to listen for an event to occur and show something in return. When the user clicks start, the code selects a quote, sets up the user interface and setup tracking for the current word and timing.

setup the word for tracking

Using Math.floor and Math.random allows us to randomly select a quote from the quotes array. Math.floor() is a function in JavaScript that rounds down and returns the largest integer less than or equal to the given number. Math.random() function returns a floating-point, pseudo-random number that’s greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.

We convert the quote into an array of words so we can track the words the player is currently typing. The wordIndex is set to 0 since the user will start on the first word.

setup the UI

We create an array of spanWords which contains each word inside a span element allowing us to highlight the word on display. Join the array using .join() to create a string which can be used to update the innerHTML on quoteElement. This will display a quote to the player.

We set the className of the first span element to highlight so as to highlight it as yellow. The styling for this is shown on the css file above.

Clean the messageElement by setting innerText to (‘ ’).

setup the textbox

We clear the current value on typedValueElement and set the focus to typedValueElement.

Start the timer by calling getTime.

Adding typing logic


typedvalueElement.addEventListener('input', () => {
const currentWord = words[wordIndex];
const typedValue = typedvalueElement.value;
if(typedValue === currentWord && wordIndex === words.length -1) {
const elapsedTime = new Date().getTime() - startTime;
const message = `CONGRATULATIONS! You finished in ${elapsedTime / 1000} seconds`;
messageElement.innerText = message;
}else if (typedValue.endsWith(' ') && typedValue.trim() === currentWord){
typedvalueElement.value = '';
wordIndex++;
for(const wordElement of quoteElement.childNodes){
wordElement.className = '';
}
quoteElement.childNodes[wordIndex].className = 'highlight';
}else if(currentWord.startsWith(typedValue)){
typedvalueElement.className = '';
} else{
typedvalueElement.className = 'error';
}
});

As a player types, an input event will be raised. This event listener will check to ensure the player is typing the word correctly, and handle the current status of the game. We first grab the current word and value the player has typed thus far. Then logic proceeds as follows, we check if the quote is complete, the word is complete, the word is correct, or finally, if there is an error.

Quote is complete if typedValue is equal to currentWord and wordIndex is equal to one less than the length of words as shown in the if condition. We calculate elapsed time by subtracting the startTime from the current time. We divide elapsedTime by 1000 to convert from milliseconds to seconds. This elapsed time is shown as the success message after the player has finished typing the quote.

For a word to be complete, the typedValue must end with a space and must be equal to currentWord. We set the value on typedElement to (‘ ’) so as to allow the next word to be typed. We also loop through all the childNodes of quoteElement to set the className to empty (‘ ’) to revert to default display. Set the className of the current word to highlight to flag it as the next word to type.

If currentWord started with typedValue, then this shows that the word was typed correctly but not complete. We ensure typedValue is displayed by default by clearing className.

If an error occurs, we set the className on typedValue to error.

And that’s all it takes to build a typing game in JavaScript. Take this code and test it out on your machine to see if it runs.

Happy Hacking!!

--

--

Anthony Mwaura
Geek Culture

Building tech to help steer society foward. Writing here to share my experience on this journey.