refact: game end for loss, linting issues, style

This commit is contained in:
ysandler 2019-07-06 04:40:44 -05:00 committed by Joshua Shoemaker
parent bbb9a65777
commit 22f044ac83
2 changed files with 220 additions and 247 deletions

View File

@ -1,25 +1,25 @@
//----------Constant Values and Objects--------- // ----------Constant Values and Objects---------
let targetIpAddress = ''; // left empty, is assigned later. let targetIpAddress = '' // left empty, is assigned later.
const lockoutMax = 12; //How many chances the user gets const lockoutMax = 12 // How many chances the user gets
let lockoutHits = 0; let lockoutHits = 0
const amountOfIps = 20; //amount of entries to chohose from const amountOfIps = 20 // amount of entries to chohose from
let ipAttempts = []; let ipAttempts = []
let time = 460000; //Games time limit let time = 460000 // Games time limit
let lose = false; let lose = false
let win = false; let win = false
let timerElement = document.getElementById('timer'); //The HTML element that renders the time left let timerElement = document.getElementById('timer') // The HTML element that renders the time left
let timeInterval = {}; //Empty object that will be turned into a timeInterval that will control the game timer. let timeInterval = {} // Empty object that will be turned into a timeInterval that will control the game timer.
let score = 0; let score = 0
let winScore = 3; //How many rounds the game has let winScore = 3 // How many rounds the game has
const systemTypes = ["HIDDEN", "KALILINUX", "WINDOWSXP", "WINDOWS2000", const systemTypes = ['HIDDEN', 'KALILINUX', 'WINDOWSXP', 'WINDOWS2000',
"WINDOWS10", "REDHAT", "ANDROID4.4", "NETHUNTER"]; 'WINDOWS10', 'REDHAT', 'ANDROID4.4', 'NETHUNTER']
const Entry = function(){ const Entry = function () {
return { return {
value: createIP(), value: createIP(),
machineType: systemTypes[randomInRange(0, systemTypes.length - 1, 0)], machineType: systemTypes[randomInRange(0, systemTypes.length - 1, 0)],
status: "ACTIVE", status: 'ACTIVE',
hostName: createRandomName(), hostName: createRandomName(),
lastResponse: randomInRange(1000, 10000000, 0), lastResponse: randomInRange(1000, 10000000, 0),
systemLocation: { systemLocation: {
@ -29,333 +29,298 @@ const Entry = function(){
} }
} }
// ---------------------Helper Functions---------------------
/* These are pure functions. They do not change the state of the
//---------------------Helper Functions---------------------
/*These are pure functions. They do not change the state of the
application so I keep these seperated from teh business logic application so I keep these seperated from teh business logic
funcitons that alter the view and take in input*/ funcitons that alter the view and take in input */
function createIP() { function createIP () {
let text = ""; let text = ''
let possible = "0123456789"; let possible = '0123456789'
for (var i = 0; i < 10; i++) for (var i = 0; i < 10; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length)); text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text; return text
} }
function formatIP (ip) {
let newIP = ip
function formatIP(ip){ newIP = newIP.slice(0, 2) + '.' + newIP.slice(2)
let newIP = ip; newIP = newIP.slice(0, 6) + '.' + newIP.slice(6)
newIP = newIP.slice(0, 9) + '.' + newIP.slice(9)
newIP = newIP.slice(0, 2) + '.' + newIP.slice(2); return newIP
newIP = newIP.slice(0, 6) + '.' + newIP.slice(6);
newIP = newIP.slice(0, 9) + '.' + newIP.slice(9);
return newIP;
} }
/* This function is used several time to get random numbers that are used
/*This function is used several time to get random numbers that are used
to get the random Longitude and Lattiudes, to select one of the IP addresses to get the random Longitude and Lattiudes, to select one of the IP addresses
as the target, etc.*/ as the target, etc. */
function randomInRange(min, max, fixed){ function randomInRange (min, max, fixed) {
return (Math.random() * (max - min) + min).toFixed(fixed) * 1; return (Math.random() * (max - min) + min).toFixed(fixed) * 1
} }
/* This function is used to return a randon alphanumeric sting that is added to
a new Entry() object to give its 'systemName' a unique value. */
function createRandomName () {
let text = ''
let possible = '0123456789QWERTYUIOP_-ASDFGHJKLZXCVBNM'
/*This function is used to return a randon alphanumeric sting that is added to for (let i = 0; i < 10; i++) {
a new Entry() object to give its 'systemName' a unique value.*/ text += possible.charAt(Math.floor(Math.random() * possible.length))
function createRandomName(){ }
let text = "";
let possible = "0123456789QWERTYUIOP_-ASDFGHJKLZXCVBNM";
for (var i = 0; i < 10; i++) return text
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
} }
/* This takes in the entry object that was instantiated by 'new Entry()'
/*This takes in the entry object that was instantiated by 'new Entry()'
We return the HTML element in the form of a string. This will later be We return the HTML element in the form of a string. This will later be
put into the Array htmlArray that is declared later on above the 'Business put into the Array htmlArray that is declared later on above the 'Business
Logic Section'*/ Logic Section' */
function createEntryHTML(entry){ function createEntryHTML (entry) {
// ES6 object destructuring
//ES6 object destructuring let { value, status, machineType, hostName, lastResponse, systemLocation } = entry
let {value, status, machineType, hostName, lastResponse, systemLocation} = entry; // let ipAddress = formatIP(value)
let ipAddress = formatIP(value); let htmlString = `<tbody>
let htmlString = "<tbody>\ <tr class="entry" data-ip-value="${value}">
<tr class='entry' data-ip-value='"+ value +"'>\ <span style="display: hidden"></span>
<span style='display: hidden'></span>\ <td class='ip'>"${formatIP(value)}"</td>
<td>"+ formatIP(value) +"</td>\ <td>${status}</td>
<td>"+ status +"</td>\ <td>${hostName}</td>
<td>"+ hostName +"</td>\ <td>${machineType}</td>
<td>"+ machineType +"</td>\ <td>${lastResponse}MS</td>
<td>"+ lastResponse +"MS</td>\ <td>${systemLocation.long}_${systemLocation.lat}</td>
<td>"+ systemLocation.long + "_" + systemLocation.lat +"</td>\ </tr>
</tr>\ </tbody>`
</tbody>"
return htmlString;
return htmlString
} }
/*This returns the array of HTML Element strings. This array is later /* This returns the array of HTML Element strings. This array is later
iterated through in a function to concatinate the strings together in iterated through in a function to concatinate the strings together in
'concatEntryHTMLArray().' That concatenated value is then used to render 'concatEntryHTMLArray().' That concatenated value is then used to render
the entries */ the entries */
function createEntryHTMLArray(entries){ function createEntryHTMLArray (entries) {
let htmlStrings = []
let htmlStrings = []; entries.forEach(function (e) {
htmlStrings.push(createEntryHTML(e))
}, this)
entries.forEach(function(e) { return htmlStrings
htmlStrings.push(createEntryHTML(e));
}, this);
return htmlStrings;
} }
/* This funciton creates an array of Entry objects that will later be iterated
/*This funciton creates an array of Entry objects that will later be iterated
though to render to the view. */ though to render to the view. */
function createEntryArray(){ function createEntryArray () {
let entries = []
let entries = []; for (let i = 0; i < amountOfIps; i++) {
entries.push(new Entry())
for(i = 0; i < amountOfIps; i++){
entries.push(new Entry());
} }
return entries; return entries
} }
/* This function iterates thou the array of HTML Entry Element strings to turn them
/*This function iterates thou the array of HTML Entry Element strings to turn them
into one big string that will be used to render to the view. */ into one big string that will be used to render to the view. */
function concatEntryHTMLArray(entries){ function concatEntryHTMLArray (entries) {
let htmlString = ''
let htmlString = ""; entries.forEach(function (e) {
htmlString += e
}, this)
entries.forEach(function(e) { return htmlString
htmlString += e;
}, this);
return htmlString;
} }
/*This function is used to extract and return the data-ip-address value from the literal /* This function is used to extract and return the data-ip-address value from the literal
html element that is passed into it. We need to extract this data when we click on the html element that is passed into it. We need to extract this data when we click on the
entries in the view. to perform certain tasks.*/ entries in the view. to perform certain tasks. */
function extractIpAddressFromElement(element){ function extractIpAddressFromElement (element) {
ipAddress = element.getAttribute('data-ip-value'); let ipAddress = element.getAttribute('data-ip-value')
return ipAddress; return ipAddress
} }
/* This function finds a value among the entires that have already been genrated and returns
/*This function finds a value among the entires that have already been genrated and returns
that value. That value will later be assigned to a global aiable */ that value. That value will later be assigned to a global aiable */
function selectTargetIpAddress(entries){ function selectTargetIpAddress (entries) {
let value = entries[randomInRange(0, entries.length - 1, 0)].value; let value = entries[randomInRange(0, entries.length - 1, 0)].value
return value; return value
} }
/* This function finds the similarity between the selected entriy and the target entry
/*This function finds the similarity between the selected entriy and the target entry
and returns a number that tells how similar they were. It uses the Levenstien method and returns a number that tells how similar they were. It uses the Levenstien method
that is provided in a different file. */ that is provided in a different file. */
function compareIpAddress(value){ function compareIpAddress (value) {
let levDis = new Levenshtein(value, targetIpAddress); let levDis = new Levenshtein(value, targetIpAddress)
let similarCount = 10 - levDis.distance; let similarCount = 10 - levDis.distance
return similarCount; return similarCount
} }
/* These functions are used to alter the state of the application. Here we work with user
/*These functions are used to alter the state of the application. Here we work with user
input and view rendering as well as progress in the game, starting, stopping, and restarting. */ input and view rendering as well as progress in the game, starting, stopping, and restarting. */
//--------------------Business Logic------------------ // --------------------Business Logic------------------
/* At the begining of the round we find the divs that we will render views too.
Create the data of the IP Address entries that are use */
function beginRound () {
document.getElementById('entry_table').innerHTML = ''
ipAttempts = []
let entryArray = createEntryArray()
let htmlArray = createEntryHTMLArray(entryArray)
let entryHTMLString = concatEntryHTMLArray(htmlArray)
let entryElements = document.getElementsByClassName('entry')
/*At the begining of the round we find the divs that we will render views too. targetIpAddress = selectTargetIpAddress(entryArray)
Create the data of the IP Address entries that are use*/ renderEntries(entryHTMLString)
function beginRound(){ assignClickEvent(entryElements)
document.getElementById('entry_table').innerHTML = ""; renderSuccessPrecentage(score * 100 / winScore)
ipAttempts = []; renderAttempts()
let entryArray = createEntryArray();
let htmlArray = createEntryHTMLArray(entryArray);
let entryHTMLString = concatEntryHTMLArray(htmlArray);
let entryElements = document.getElementsByClassName('entry');
targetIpAddress = selectTargetIpAddress(entryArray);
renderEntries(entryHTMLString);
assignClickEvent(entryElements);
renderSuccessPrecentage(score * 100/winScore);
renderAttempts();
console.log(targetIpAddress);
console.log(targetIpAddress)
} }
function beginClicked(){ function beginClicked () {
let messege = document.getElementById('messege'); let messege = document.getElementById('messege')
messege.innerHTML = "" messege.innerHTML = ''
messege.className = "hidden"; messege.className = 'hidden'
timeInterval = setInterval(countDown, 10); timeInterval = setInterval(countDown, 10)
beginRound(); beginRound()
} }
function assignClickEvent (elements) {
function assignClickEvent(elements){ for (let i = 0; i < elements.length; i++) {
let entry = elements[i]
for(i = 0; i < elements.length; i++){ entry.onclick = function () {
let entry = elements[i]; clickedEntry(entry)
entry.onclick = function(){
clickedEntry(entry);
} }
} }
} }
function clickedEntry (entry) {
if (!lose && !win) {
let ipDifference = compareIpAddress(extractIpAddressFromElement(entry))
function clickedEntry(entry){ if (ipDifference === 10) {
targetIpAddressFound(entry)
if(!lose && !win){ } else {
let ipDifference = compareIpAddress(extractIpAddressFromElement(entry)); wrongEntrySelected(entry, ipDifference)
renderLockout()
if(ipDifference === 10){ renderSuccessPrecentage(score * 100 / winScore)
targetIpAddressFound(entry); checkStatus()
}
else{
wrongEntrySelected(entry, ipDifference);
renderLockout();
renderSuccessPrecentage(score * 100/winScore);
checkStatus();
} }
} }
} }
function targetIpAddressFound (entry) {
function targetIpAddressFound(entry){ score += 1
score += 1; if (score > winScore - 1) {
if(score > winScore - 1){ gameWin()
gameWin(); } else {
} beginRound()
else{
beginRound();
} }
} }
function wrongEntrySelected (entry, similarity) {
let value = extractIpAddressFromElement(entry)
function wrongEntrySelected(entry, similarity){ lockoutHits = lockoutHits + 1
let value = extractIpAddressFromElement(entry); saveAttempt(value)
renderAttempts()
lockoutHits = lockoutHits + 1; console.log(value + ' was incorrect. Tries left: ' + (lockoutMax - lockoutHits))
saveAttempt(value); console.log(similarity + ' characters were correct. Try Again!')
renderAttempts();
console.log(value + " was incorrect. Tries left: " + (lockoutMax - lockoutHits));
console.log(similarity + " characters were correct. Try Again!")
} }
function renderEntries (htmlString) {
function renderEntries(htmlString){ document.getElementById('entry_table').innerHTML = htmlString
document.getElementById('entry_table').innerHTML = htmlString;
} }
function renderSuccessPrecentage(percentage){ function renderSuccessPrecentage (percentage) {
let successPercentage = document.getElementById('precentage'); let successPercentage = document.getElementById('precentage')
successPercentage.innerHTML = Math.floor(percentage) + "%"; successPercentage.innerHTML = Math.floor(percentage) + '%'
} }
function renderLockout () {
let lockoutElement = document.getElementById('lockout')
function renderLockout(){ lockoutElement.innerHTML = ''
let lockoutElement = document.getElementById('lockout');
lockoutElement.innerHTML = ''; for (let i = 0; i < lockoutHits; i++) {
lockoutElement.innerHTML = lockoutElement.innerHTML + "<span class'lockoutMark'> X </span>"
for(i = 0; i < lockoutHits; i++){
lockoutElement.innerHTML = lockoutElement.innerHTML + "<span class'lockoutMark'> X </span>";
} }
} }
function saveAttempt (value) {
function saveAttempt(value){ ipAttempts.push(value)
ipAttempts.push(value);
} }
function renderAttempts () {
let attemptsTable = document.getElementById('attempts_table')
attemptsTable.innerHTML = ''
function renderAttempts(){ ipAttempts.forEach(function (e) {
let attemptsTable = document.getElementById('attempts_table'); attemptsTable.innerHTML += `<td>${formatIP(e)}</td>
attemptsTable.innerHTML = ""; <td>${compareIpAddress(e)} similar chars</td>`
}, this)
ipAttempts.forEach(function(e) {
attemptsTable.innerHTML += "<td>" + formatIP(e) + "</td>\
<td>" + compareIpAddress(e) + " similar chars</td>"
}, this);
} }
function renderEndGame (win) {
document.getElementById('entry_table').innerHTML = ''
let messege = document.getElementById('messege')
function renderEndGame(){ if (win) {
document.getElementById('entry_table').innerHTML = ""; messege.innerHTML = "<p>You have found her! It was not easy, but your diligence paid off. The data you have collected has been sent to the F.B.I. Please help actually fight human trafficking by donating to one of several private organizations or report tips to goverment agencies that do just that!</p><button onclick='redirectToFoundation()'>HELP NOW</button>"
let messege = document.getElementById('messege'); } else {
messege.innerHTML = "<p>You have failed. And unfortuantly have not been able to find her. But to help in the actual battle agains human trafficking, you can donate to one of the several private organizations or report tips to government agencies that do just that!</p><button onclick='redirectToFoundation()'>HELP NOW</button>"
messege.innerHTML = "<p>You have found her! It was not easy, but your diligence paid off. The data you have collected has been sent to the F.B.I. Please help actually fight human trafficking by donating to one of several private organizations or report tips to goverment agencies that do just that!</p><button onclick='redirectToFoundation()'>HELP</button>" }
messege.className = ""; messege.className = ''
} }
function checkStatus(){ function checkStatus () {
if(lockoutHits >= lockoutMax){ if (lockoutHits >= lockoutMax) {
gameLose(); gameLose()
} }
} }
function gameLose () {
let entryElements = document.getElementsByClassName('entry')
lose = true
function gameLose(){ timerElement.innerHTML = 0
let entryElements = document.getElementsByClassName('entry'); clearInterval(timeInterval)
let entryArray = []; Array.prototype.forEach.call(entryElements, function (e) {
e.className = 'entry error'
}, this)
lose = true; setTimeout(function () {
renderEndGame(false) // false means game lost
timerElement.innerHTML = 0; }, 4000)
clearInterval(timeInterval);
Array.prototype.forEach.call(entryElements, function(e) {
e.className = "entry error"
}, this);
setTimeout(function(){
window.location.reload(true)
}, 4000);
} }
function gameWin(){ function gameWin () {
let targetElement = document.querySelector('[data-ip-value="' + targetIpAddress + '"]') let targetElement = document.querySelector('[data-ip-value="' + targetIpAddress + '"]')
win = true; win = true
targetElement.className = "win"; targetElement.className = 'win'
clearInterval(timeInterval); clearInterval(timeInterval)
timerElement.innerHTML = 0; timerElement.innerHTML = 0
renderEndGame(); renderEndGame(true) // true means game wone
console.log("Game Win");
} }
function countDown(){ function countDown () {
if(time > 0 && !lose){ if (time > 0 && !lose) {
time -= 10; time -= 10
timerElement.innerHTML = time; timerElement.innerHTML = time
} } else {
else{ gameLose()
gameLose();
} }
} }
function redirectToFoundation(){ function redirectToFoundation () {
window.open('https://www.dhs.gov/blue-campaign/identify-victim?utm_source=bing&utm_medium=cpc&utm_campaign=search-p1.broad-allcit-allpri&utm_content=trafficking&utm_term=%2Btrafficking', '_blank') window.open('https://www.dhs.gov/blue-campaign/identify-victim?utm_source=bing&utm_medium=cpc&utm_campaign=search-p1.broad-allcit-allpri&utm_content=trafficking&utm_term=%2Btrafficking', '_blank')
} }

View File

@ -1,15 +1,18 @@
html,body{
margin: 0px;
padding: 0px
}
.hidden{ .hidden{
display: none; display: none;
} }
.screen{ .screen{
width: 900px; width: calc(100vw - 2px);
height: 720px; height: calc(100vh - 2px);
margin: 30px auto;
border-color: #00FF00; border-color: #00FF00;
border-width: 1px; border-width: 1px;
border-style: solid; border-style: solid;
border-radius: 26px;
background-color: black; background-color: black;
color: white; color: white;
font-family: monospace; font-family: monospace;
@ -92,10 +95,11 @@ button:hover{
hr{ hr{
border-color: #00ff00; border-color: #00ff00;
margin: 6px 0px; margin: 6px 0px;
width: 100vw;
} }
table{ table{
width: 900px; width: 100%;
font-size: 14px; font-size: 14px;
} }
@ -146,3 +150,7 @@ td{
display: inline; display: inline;
font-size: 16px; font-size: 16px;
} }
.ip{
color: rgb(209, 255, 191);
}