Jump to content

User:RCSDevs/quiz.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
importStylesheet('User:RCSDevs/quiz.css');

//Add function to array that selects random element (to make things easier)
Array.prototype.random = function()
{
    return this[Math.floor(Math.random() * this.length)];
};

//Checks if string is null, or blank
String.prototype.isEmpty = function()
{
    return (this === null || this.length === 0 || this.trim() === "");
};

String.prototype.capitalize = function()
{
	return this.charAt(0).toUpperCase() + this.slice(1);
};

String.prototype.contains = function(str)
{
	return this.indexOf(str) !== -1;
};

//A blacklist of words that would be easy to guess out of context
var thezWrdsR2EzCauzWeMLG = [
	"though",
	"although",
	"even", 
	"while",
	"only",
	"unless",
	"until",
	"provided",
	"assuming",
	"even",
	"lest",
	"than",
	"rather",
	"whether",
	"whereas",
	"after",
	"before",
	"once",
	"since",
	"till",
	"when",
	"whenever",
	"while",
	"because",
	"since",
	"that",
	"what",
	"whatever",
	"which",
	"whichever",
	"whoever",
	"whom",
	"whomever",
	"whose",
	"where",
	"wherever",
	"from",
	"will",
	"well"
],
isOpen = false,
score = 0,
numberCorrect = 0,
numberWrong = 0,
word = "",
denyPageSearch = function (e)
{
	if(e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70))
    {
    	e.preventDefault();
    }
},
currentParagraph = null,
checkWord = function(word)
{
	return !thezWrdsR2EzCauzWeMLG.includes(word.toLowerCase()) && !word.isEmpty() && word.length > 3;
};

function openNav()
{
	$('#mySidenav').css('width', '15vw');
    $('#content').css('margin-right', 'calc(15vw + 1px)');
    window.addEventListener("keydown", denyPageSearch);
    isOpen = true;
}

function closeNav()
{
	$('#mySidenav').css('width', '0');
    $('#content').css('margin-right', '0');
    window.removeEventListener("keydown", denyPageSearch);
    isOpen = false;
}

function createQuestion()
{
	var paragraph = $.makeArray($('p')).filter(function(p) { return p.parentNode.getAttribute('id') === 'mw-content-text' && !p.textContent.isEmpty(); }).random(),
		text = paragraph.textContent.replace(/\[.*?\]/g, '').trim(),//Using Regex to remove all citations
		sentences = text.split(/[\.|\;]\s/g).filter(function(s) { return /[^A-Z]/g.test(s.slice(-1)) }); //Split sentence by either '. ' or '; ' while ensuring the last character of before the split is not an uppercase letter
	
	do
	{
		sentence = sentences.random().trim().capitalize(),
		words = sentence.split(/\s|\,\s/g).filter(checkWord);
		word = words.random().trim();
		index = sentence.indexOf(word);
		newSentence = sentence.slice(0, index) + "_".repeat(word.length) + sentence.slice(index + word.length);//sentence.replace(word, "_".repeat(word.length));
	}
	while(word.isEmpty() && newSentence.replace('_', '').trim().length === 0);
	
	var jpara = $(paragraph);
	
	if(sentence.length > 120)
	{
		var charsLeft = parseInt((sentence.length - 120) / 2);
		
		if(charsLeft > 6)
		{
			if(newSentence.startsWith('_'))
			{
				newSentence = newSentence.substring(0, newSentence.indexOf(' ', newSentence.length - (charsLeft * 2)) + 1) + '...';
			}
			else if(newSentence.endsWith('_'))
			{
				newSentence = '...' + newSentence.substring(newSentence.lastIndexOf(' ', charsLeft * 2));
			}
			else
			{
				blankIndex = newSentence.indexOf('_'),
				startIndex = newSentence.indexOf(' ', Math.max(0, blankIndex - (60 + charsLeft))) + 1,
				endIndex = newSentence.lastIndexOf(' ', Math.min(newSentence.length, blankIndex + (60 + (word.length - 1) - charsLeft)));
				newSentence = '...' + newSentence.substring(startIndex, endIndex) + '...';
			}
		}
	}
	else
	{
		newSentence += '.';
	}
	
	$("#madLib").text(newSentence);
	currentParagraph = jpara;
	scrollParagraph();
}

function scrollParagraph()
{
	var paraOffset = currentParagraph.offset().top;
	var paraHeight = currentParagraph.height();
	var windowHeight = $(window).height();
	var scrollOffset;
  
	if(paraHeight < windowHeight)
	{
    	scrollOffset = paraOffset - ((windowHeight / 2) - (paraHeight / 2));
  	}
  	else
  	{
    	scrollOffset = paraOffset;
  	}
  	
	$('html, body').animate(
	{
    	scrollTop: scrollOffset
    }, 2000, function()
	{
		currentParagraph.addClass('flashMe');
    	setTimeout(function() { currentParagraph.removeClass('flashMe'); }, 650);
    	$('#qAnswer').focus();
	});
}

$(document).ready(function()
{
	var tab = $('#ca-nstab-main');

	if(tab.length && tab.attr('class') === 'selected')
	{
		//Append 'Play' tab to namespace bar
		$('#p-namespaces ul').append('<li id="ca-play"><span><a href="#" title="Games about the content page [alt-shift-p]" accesskey="p">Quiz</a></span></li>');
		$('body').append('<div id="mySidenav" class="sidenav"><div class="container"><a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&#10005</a><a href="javascript:void(0)" class="focus" onclick="scrollParagraph()">&#128270;</a><center><p id = "counter"><sup id="right" style="color: green">+0</sup><span>0</span><sup id="wrong" style="color: red">-0</sup></p><p id = "madLib"></p><input type = "text" id = "qAnswer"><button id = "checkAnswer">&#10003;</button></center></div></div>');
		$('#footer').css('background-color', '#F6F6F6');
		
		//Add 'click' event to 'Play' tab
		$('#ca-play').click(function(event)
		{
			event.preventDefault();
		
			if(!isOpen)
			{
				openNav();
				createQuestion();
				
				$('#qAnswer').keyup(function(event)
				{
    				if(event.keyCode == 13)
    				{
        				$('#checkAnswer').click();
    				}
				});
				
				$('#qAnswer').focus();
			}
			else
			{
				closeNav();
			}
		});

		$('#checkAnswer').click(function(event)
		{
			var answer = $('#qAnswer').val();

			console.log(answer);
			console.log(word);

			if(answer.includes(word) && !answer.includes(' '))
			{
				numberCorrect++;
				score++;
				$('#counter span').text(score);
				$('#right').text('+' + numberCorrect);
				$('#counter').css("color", 'green');
				$('#qAnswer').val("");
				createQuestion();
			}
			else
			{
				numberWrong++;
				score = Math.max(0, score - 1);
				$('#counter span').text(score);
				$('#wrong').text('-' + numberWrong);
				$('#counter').css("color", 'red');
				$('#qAnswer').val("");
			}
			
			setTimeout(function()
			{
				$('#counter').css("color", 'black');
			}, 1000);
		});
	}
});