Simple Typing game (JavaScript)

Viewed 389

I am trying to create a typing game that allows users to input the correct alphabets for the word displayed on the screen. If any wrong alphabet is used as input the game won't show a new word until all the alphabets are correctly provided as input. What I am not able to figure out is how I do match multiple characters with Array elements. Here is my code sample.

var p = document.getElementById('word');
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
  
function keyboardEventsHandle(e){
    p.append(e.key);

    if(e.key=='a')
    {
        alert('You typed A');
    }
}
<html>
    <head>
        <title>Simple Typing Tutor</title>
    </head>
    <body>
        <p id="word"></p>
        <h3> america </h3>
        <script src="javas.js"></script>
    </body>
</html>

2 Answers

var p = document.getElementById('word');
var word = document.getElementById("toType")
document.addEventListener('keyup', keyboardEventsHandle , false);
var wordsList = ['america','japan','italy','jordan','turkey'];
var gameRunning = true

var charIndex = 0;
var wordIndex = 0;

function keyboardEventsHandle(e){
  // If you use append here. Every character gets printed out
  // p.append(e.key);
  if(e.key==wordsList[wordIndex].charAt(charIndex) && gameRunning)
    {
        // If you use append here only correct characters get printed out
        p.append(e.key)
        alert('Correct!');
        if (wordsList[wordIndex].length == charIndex + 1) {
          // Defines which word should get controlled
          if (wordsList.length == wordIndex + 1) {
            gameRunning = false;
            alert('Done');
          } else {
            wordIndex++;
            charIndex = 0;
            word.innerHTML = wordsList[wordIndex];
            p.innerHTML = "";
          }
          
        } else {
          // Defines which character of the word should get controlled
          charIndex++;
        }
    }
 
}
<html>
<head>
 <title>Simple Typing Tutor</title>
</head>
<body>
  <p id="word"></p>
    <h3 id="toType"> america </h3>
  <script src="javas.js"></script>
</body>
</html>

You can create a list of elements to match and then do something like this:

const wordsList = ['america','japan','italy','jordan','turkey'];
const listToMatch = ['america','japan'];

let trueOrFalse = listToMatch.every(i=> wordsList.includes(i));
 console.log(trueOrFalse) //true

var anotherList = ['america', 'India'];
trueOrFalse = anotherList.every(i=> wordsList.includes(i));
console.log(trueOrFalse) //false

Related