Simple Typing game (JavaScript) - javascript

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>

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

JS or jQuery to compare two texts character by character

It should compare the texts and update it. I am using onkeyup for each time text is updated.
$(document).ready(function() {
$("#color").keyup(validate);
});
function validate() {
var password1 = $("#color").val();
var pass = $('#coltext').text();
var length = $("#color").val().length;
for (int i = 0; i < length; i++) {
if (pass[i] == password1[i]) {
$("#coltext").css("color", "green"); //make only correct character green
} else {
$("#coltext").css("color", "red");
}
}
}
<input id="color" type="text" />
<p id="coltext">This</p>
So what I want to do is whenever I type the "This" written should update character by character, green for correct and red for wrong. You can say like what typing tutor does.
You have to break the password into spans in order to style them seperately, then to compare then use $("#coltext span").eq(i).text() instead of pass[i];
$(document).ready(function() {
$("#color").keyup(validate);
});
function validate() {
var password1 = $("#color").val();
// put each of your password chars in a span
var pass = "<span>"+$('#coltext').text().split("").join("</span><span>")+"</span>";
$('#coltext').html(pass);
var length = $("#color").val().length;
for (var i = 0; i < length; i++) {
if ($("#coltext span").eq(i).text() == password1[i]) {
$("#coltext span").eq(i).css("color", "green"); //make only correct character green
} else {
$("#coltext span").eq(i).css("color", "red");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="color" type="text" />
<p id="coltext">This</p>
<!DOCTYPE html>
<html>
<body>
<script>
var x = "Cancelled";
var y = "Cancelled";
if(x==y)
{
alert("equal");
}
else
{
alert("not equal");
}
</script>
</body>
</html>

How to skip converting element text

i want output text oldnames not changes if user insert text 'false'
for example:
user input text "false toni" in textbox.
and i want output still "false toni"
why my code still changes text "toni" with "rina"?
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (oldNames== 'false ' + oldNames){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
UPDATE:
Improve the question:
Trying enter text "My name is rian and my name is false toni" .
Posible to make output "rian" still change to "susi"?
use includes x.includes(value) to check whether the text area value contains a word that you want to replace . if it contains false then your oldnames not get changed.
If you are using IE then use x.indexOf(value)>0 instead of x.includes(value)
http://www.w3schools.com/jsref/jsref_includes.asp
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'rian'];
var newNames = ['rina', 'susi'];
oldNames.forEach(function(value, index) {
/*if (x.includes('false '+value)){
var oldNames1=['false '+value];
x = x.replaceArr(oldNames1, oldNames1);
}*/
if (x.includes(value)) {
var oldNames1 = [value];
x = x.replaceArr(oldNames1, newNames[index]);
newNames1 = ['false ' + newNames[index]];
oldNames1 = ['false ' + value];
x = x.replaceArr(newNames1, oldNames1);
}
});
document.getElementById("check").innerHTML = x;
}
</script>
<body>
ENTER TEXT:
<br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
You false checking condition is wrong, you can do it using substr:
if (x.substr(0, 6) === 'false ') {
// The string starts with false
} else {
}
You can find more details on the substr from MDN.
UPDATE: As mentioned in the comment same can be done via startsWith and this is a better approach.
if (x.startsWith('false ')) {
// The string starts with false
} else {
}
try this. Compare array values instead of array.
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (x.indexOf('false') > -1 ){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>

How to compare the current variable with current type?

In my code I try to comapare the current element from the array tmp with the types string and number. With this compare I want to print in the console the result different, i.e. if is a string to print it on the same line(the whole word), the next word to be on the second line and so on. But if is a number every digit to print in the new line.
Output number
Input string
Output string
HTML
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Exercises in JS</title>
<script src="exercises.js"></script>
<body>
<label for="myText">Input array:</label>
<input type="text" id="myText">
Submit
<br/>
<br/>
<label for="myText2">Input for delete:</label>
<input type="text" id="myText2">
Submit
</body>
</head>
</html>
Javascript
window.onload = function(){
inputBox =document.getElementById("myText");
btn = document.getElementById('sub');
inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');
btn.addEventListener("click",function(event){
event.preventDefault();
saveArr(inputBox.value);
});
btn2.addEventListener("click",function(event){
event.preventDefault();
removeItemAndprintNewArray(inputBox.value, inputBox2.value);
});
function saveArr(arr) {
var rv = [];
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
function removeItemAndprintNewArray(rv, number) {
var tmp = [],
st = "";
for(var index in rv){
if(rv[index] !== number){
tmp.push(rv[index]);
}
}
for (var i = 0; i < tmp.length; i++){
if (typeof(tmp[i]) == "String"){
st += tmp[i];
console.log(st);
}
else if (typeof(tmp[i]) === "Number"){
st += tmp[i];
console.log(st[i]);
}
}
}
}
Javascript automatically makes type conversations, and if conversation fails it returns NaN value instead of throw exception. Let's use it)
Small example
var arr = [12, "asd", 4];
arr.forEach(function(item) {
console.log(item - 0);
});
So you can check on NaN, don't forget that you should use special function isNaN()
var arr = [12, "asd", 4];
arr.forEach(function(item) {
if(isNaN(item - 0)) {
//do what you want with string
console.log("string");
};
else {
//do what you want with Number
console.log("number");
}
});

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

Function returning value 'NaN'

I am writing a code that checks the user input and gives the result according to it. But the twist here is that the string can also contain the word 'dozen', which just means twelve. The thing will be cleared after looking at the following code:
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>iRock</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<form>
<label for="numDonut">Enter how many donuts you want: </label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
JS:
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
function getTotalDonuts(donutString){
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
Now here is the problem : No matter what input I give, even if it doesn't contain the word 'dozen', the function returns NaN, which is not making sense.
What can be the problem?
You need to change the function callDonut like :
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem: you don't reassign the new value of your input into the variable numDonutString
The problem you are having is you have tried to pre define your var numDonutString = document.getElementById('numDonut').value; however what this does is takes a copy of the value and it will never update that value.
So what you need to do is get the new value each time you click the SUBMIT button.
jsFiddle : https://jsfiddle.net/CanvasCode/xue6sbz2/
function getTotalDonuts(donutString){
alert(donutString);
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem is in the callDonut function and the text box value you are getting is only at the document load, so the value is always NaN.
window.getTotalDonuts = function(donutString) {
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if (donutString.indexOf('dozen') != -1) {
finalDonuts = initialDonutCount * 12;
} else {
finalDonuts = initialDonutCount;
}
return finalDonuts || 0;
}
window.callDonut = function() {
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
<form>
<label for="numDonut">Enter how many donuts you want:</label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
</body>
[DEMO][1]

Categories