True/false as strings, only allowed boolen - javascript

function start() {
var arrNums = [18,23,20,17,21,18,22,19,18,20];
var lowValue, highValue, index, count;
lowValue = Number(document.getElementById("lowValue").value);
highValue = Number(document.getElementById("highValue").value);
index = 0;
count = 0;
document.getElementById("msg").innerHTML+="The values in the array are: ";
while(index < arrNums.length) {
document.getElementById("msg").innerHTML+= arrNums[index] + " ";
index++;
}
index = 0;
if(validateLowAndHigh(lowValue, highValue) == "true") {
while(index < arrNums.length) {
if(arrNums[index] >= lowValue && arrNums[index] <= highValue) {
count++;
}
index++;
}
document.getElementById("msg").innerHTML+= "<br/> There are " + count + " values that exist in this range";
}
}
function validateLowAndHigh(low, high) {
if(low <= high) {
return("true");
} else {
document.getElementById("msg").innerHTML+= "<br/> Low value must be less than or equal to the high vaules";
return("false");
}
}
function clearOutput() {
document.getElementById("msg").innerHTML=" ";
}
I was told that I am not allowed to use true/false as strings, only as boolean. How do I go about fixing this? I am not sure how this works, thank you for the help.

Change your code as like this
Change return true instead of return ("true") or ("false")
And change if (validateLowAndHigh(lowValue, highValue)) instead of if (validateLowAndHigh(lowValue, highValue) == 'true')
function start() {
var arrNums = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var lowValue, highValue, index, count;
lowValue = Number(document.getElementById("lowValue").value);
highValue = Number(document.getElementById("highValue").value);
index = 0;
count = 0;
document.getElementById("msg").innerHTML += "The values in the array are: ";
while (index < arrNums.length) {
document.getElementById("msg").innerHTML += arrNums[index] + " ";
index++;
}
index = 0;
if (validateLowAndHigh(lowValue, highValue)) {
while (index < arrNums.length) {
if (arrNums[index] >= lowValue && arrNums[index] <= highValue) {
count++;
}
index++;
}
document.getElementById("msg").innerHTML += "<br/> There are " + count + " values that exist in this range";
}
}
function validateLowAndHigh(low, high) {
if (low <= high) {
return true;
} else {
document.getElementById("msg").innerHTML += "<br/> Low value must be less than or equal to the high vaules";
return false;
}
}
function clearOutput() {
document.getElementById("msg").innerHTML = " ";
}

Instead of using return("true") and return("false"), use return true and return false
Also, replace if(validateLowAndHigh(lowValue, highValue) == "true") with
if(validateLowAndHigh(lowValue, highValue))
OR
if(validateLowAndHigh(lowValue, highValue) == true)

Related

Mine Sweeper - getting all cells until they neighbor with a bomb

I'm trying to perform the function where i click on a cell , and if it isn't in proximity of a bomb, it'll reveal all up until those who neighbour with a bomb.
I'm practically stuck :
I'm adding the code i think relevant here
//Click cells to reveal + placing mines for the first time
function cellClicked(elCell, i, j) {
if (!gGame.isOn) return;
if (gClickCounter === 0) {
getRandomMine(gLevel.mines, i, j);
startTimeInterval();
gClickCounter++;
}
var cell = gBoard[i][j];
console.log('cell:', cell);
if (cell.isShown) return;
if (!cell.isShown) {
cell.isShown = true;
elCell.classList.add('shown');
gGame.shownCount++;
console.log('gGame.shownCount:', gGame.shownCount);
}
if (cell.isMine === true) {
gLivesLeft--;
var elLives = document.querySelector('.lives');
elLives.innerHTML = gLivesLeft;
elCell.innerText = BOMB;
if (gLivesLeft === 0) {
gameOver();
}
} else {
var gNegs = countNegs(i, j);
elCell.innerText = gNegs;
console.log('elCell:', elCell.dataset.i);
console.log('elCell:', elCell.dataset.j);
cell.minesAroundCount = gNegs;
if (gNegs === 0) {
//check up
if (i > 0) {
var uCell = document.getElementById(gBoard.length * (i - 1) + j);
if (!gBoard[i - 1][j].isShown && !gBoard[i - 1][j].isMarked) {
cellClicked(uCell, i - 1, j);
}
}
//check down
if (i < gBoard.length - 1) {
var uCell = document.getElementById(gBoard.length * (i + 1) + j);
if (!gBoard[i + 1][j].isShown && !gBoard[i + 1][j].isMarked) {
cellClicked(uCell, i + 1, j);
}
}
//check right
if (j < gBoard.length - 1) {
var uCell = document.getElementById(gBoard.length * i + (j + 1));
if (!gBoard[i][j + 1].isShown && !gBoard[i][j + 1].isMarked) {
cellClicked(uCell, i, j + 1);
}
}
}
}
}
//counting neighbors
function countNegs(cellI, cellJ) {
var negsCount = 0;
for (var i = cellI - 1; i <= cellI + 1; i++) {
if (i < 0 || i > gBoard.length - 1) continue;
for (var j = cellJ - 1; j <= cellJ + 1; j++) {
if (j < 0 || j > gBoard[i].length - 1) continue;
if (i === cellI && j === cellJ) continue;
if (gBoard[i][j].isMine) {
negsCount++;
}
if (negsCount === 0) {
}
}
}
return negsCount;
}
and the entire code is here :
https://codepen.io/Aegtar/pen/XWaLLzz
Would appreciate any life savers here!

Logic issue in minesweeper

--SOLVED--
I was just forgetting to reset the number of flags after each game.
I'm having issues with the number of flags in my minesweeper game. For some reason, sometimes when I flag a tile the number of flags increases by more than 1. Sometimes it increases by 3, sometimes 4, sometimes 7. I can't find the issue in my logic, so I was hoping to get another set of eyes on it.
The only sort of pattern I can see when it adds more flags than it should, i.e. the flags variable is incremented more than once, is when I flag a tile that is mostly surrounded by revealed tiles.
Javascript:
var flags = 0;
var trueFlags = 0;
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
var q = Math.floor(Math.random() * 50);
if (0 <= q && q <= 2) {
numBombs += 1;
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 0 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + 'data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
$("#board").append("<br/>");
}
$(".controls h2").text("Bombs to go: " + numBombs);
$(".tile").css("background-color", "white");
$(".tile").width(15);
$(".tile").height(15);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
$(".tile").click(function(e) {
if (e.shiftKey) {
flagKey($(this));
$(".controls h2").text("Bombs to go: " + (numBombs - flags));
}
else if ($(this).data("contains") == 0) {
console.log("you lose");
boardClear();
newGame();
return;
}
else {
revealNeighbors($(this));
// if (gameWon() == true) {
// alert("You have won!");
// newGame();
// }
return;
}
});
}
function boardClear() {
$("#board").empty();
}
function revealNeighbors(tile) {
var cordsx = tile.data("row");
var cordsy = tile.data("col");
// tile has bomb
if(tile.data("contains") == 0) {return;}
// tile is flagged
else if(tile.data("flagged") == true){return;}
// tile has been revealead already
else if(tile.prop("revealed") == true) {return;}
// reveal the tile
var tileBombs = nearbyBombCount(tile);
tile.prop("revealed", true);
tile.text(tileBombs);
tile.css("background-color", "grey");
if (tileBombs == 0){tile.text("");}
else if(tileBombs != 0) {return;}
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (cordsx + i < 1 || cordsy + j < 1) {continue;}
else if (cordsx + i > $("#width").val() || cordsy + j > $("#height").val()) {continue;}
else if (i == 0 && j == 0) {continue;}
var neighbor = $('.tile[data-row="' + (cordsx+i) + '"][data-col ="'+(cordsy+j)+'"]');
revealNeighbors(neighbor);
}
}
}
function nearbyBombCount(tile) {
var cx = tile.data("row");
var cy = tile.data("col");
var nearbyBombs = 0;
for (var n = -1; n < 2; n++) {
for (var m = -1; m < 2; m++) {
if (cx + n < 1 || cy + m < 1) {continue;}
else if (cx + n > $("#width").val() || cy + m > $("#height").val()) {continue;}
var neighbor = $('.tile[data-row="' + (cx+n) + '"][data-col ="'+(cy+m)+'"]');
if (neighbor.data("contains") == 0) {
nearbyBombs++;
}
}
}
return nearbyBombs;
}
function flagKey(tile) {
// tile is already revealed
if (tile.data("revealed") == true) {
return;
}
// tile is already flagged
else if (tile.data("flagged") == true) {
tile.data("flagged", false);
tile.css("background-color", "white");
flags--;
// contains bomb
if (tile.data("contains") == 0) {
trueFlags--;
}
return;
}
// tile not flagged
else if (tile.data("flagged") == false) {
flags++;
tile.data("flagged", true);
tile.css("background-color", "red");
// contains bomb
if (tile.data("contains") == 0) {
trueFlags++;
console.log(trueFlags);
}
}
else {
return;
}
}
My guess is that there's something wrong with my revealNeighbors() function or it's some scope issue, but I can't for the life of me figure out what it is.
Hi I change a litle and works fine
<html>
<head>
<style>
.tile{padding:5px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Width : <input type="text" id="width" value="15" /> Height :<input type="text" id="height" value="15" /><input type="button" onclick="newGame()" id="btnstart" value="start" />
<br />
<div>
<div id="board" >
</div>
</div>
<script>
var flags = 0;
var trueFlags = 0;
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
var q = Math.floor(Math.random() * 50) + 1;
if (q <= 2) {
numBombs += 1;
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 0 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + 'data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
$("#board").append("<br/>");
}
$(".controls h2").text("Bombs to go: " + numBombs);
$(".tile").css("background-color", "white");
$(".tile").width(15);
$(".tile").height(15);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
$(".tile").click(function (e) {
if (e.shiftKey) {
flagKey($(this));
$(".controls h2").text("Bombs to go: " + (numBombs - flags));
}
else if ($(this).data("contains") == 0) {
console.log("you lose");
boardClear();
newGame();
return;
}
else {
revealNeighbors($(this));
// if (gameWon() == true) {
// alert("You have won!");
// newGame();
// }
return;
}
});
}
function boardClear() {
$("#board").empty();
}
function revealNeighbors(tile) {
var cordsx = tile.data("row");
var cordsy = tile.data("col");
// tile has bomb
if(tile.data("contains") == 0) {return;}
// tile is flagged
else if(tile.data("flagged") == true){return;}
// tile has been revealead already
else if(tile.prop("revealed") == true) {return;}
// reveal the tile
var tileBombs = nearbyBombCount(tile);
tile.prop("revealed", true);
tile.text(tileBombs);
tile.css("background-color", "grey");
if (tileBombs == 0){tile.text("");}
else if(tileBombs != 0) {return;}
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (cordsx + i < 1 || cordsy + j < 1) {continue;}
else if (cordsx + i > $("#width").val() || cordsy + j > $("#height").val()) {continue;}
else if (i == 0 && j == 0) {continue;}
var neighbor = $('.tile[data-row="' + (cordsx+i) + '"][data-col ="'+(cordsy+j)+'"]');
revealNeighbors(neighbor);
}
}
}
function nearbyBombCount(tile) {
var cx = tile.data("row");
var cy = tile.data("col");
var nearbyBombs = 0;
for (var n = -1; n < 2; n++) {
for (var m = -1; m < 2; m++) {
if (cx + n < 1 || cy + m < 1) {continue;}
else if (cx + n > $("#width").val() || cy + m > $("#height").val()) {continue;}
var neighbor = $('.tile[data-row="' + (cx+n) + '"][data-col ="'+(cy+m)+'"]');
if (neighbor.data("contains") == 0) {
nearbyBombs++;
}
}
}
return nearbyBombs;
}
function flagKey(tile) {
// tile is already revealed
if (tile.data("revealed") == true) {
return;
}
// tile is already flagged
else if (tile.data("flagged") == true) {
tile.data("flagged", false);
tile.css("background-color", "white");
flags--;
// contains bomb
if (tile.data("contains") == 0) {
trueFlags--;
}
return;
}
// tile not flagged
else if (tile.data("flagged") == false) {
flags++;
tile.data("flagged", true);
tile.css("background-color", "red");
// contains bomb
if (tile.data("contains") == 0) {
trueFlags++;
console.log(trueFlags);
}
}
else {
return;
}
}
</script>
</body>
</html>

how to modify below function to read 3 decimal places

I am using tafgeet javascript function to convert numbers into Arabic words, but the problem is that it supports only 2 decimal places, how can I modify the function to make it read 3 decimal places:
It actually translates upto a million on the left hand side, so it would be possible to apply the same methodology on the right side.
I tried to fiddle with it, but it doesn't work. I am posting the original javascript.
/**
* TafgeetJS module.
* #module TafgeetJS
* #description Converts currency digits into written Arabic words
* #author Mohammed Mahgoub <mmahgoub#gmail.com>
*/
function Tafgeet(digit) {
var currency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "SDG";
//Split fractions
var splitted = digit.toString().split(".");
this.fraction = 0;
if (splitted.length > 1) {
var fraction = parseInt(splitted[1]);
if (fraction >= 1 && fraction <= 99) {
this.fraction = splitted[1].length === 1 ? fraction * 10 : fraction;
} else {
//trim it
var trimmed = Array.from(splitted[1]);
this.fraction = "" + trimmed[0] + trimmed[1];
}
}
this.digit = splitted[0];
this.currency = currency;
}
Tafgeet.prototype.parse = function () {
var serialized = [];
var tmp = [];
var inc = 1;
var count = this.length();
var column = this.getColumnIndex();
if (count >= 16) {
console.error("Number out of range!");
return;
}
//Sperate the number into columns
Array.from(this.digit.toString()).reverse().forEach(function (d, i) {
tmp.push(d);
if (inc == 3) {
serialized.unshift(tmp);
tmp = [];
inc = 0;
}
if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
serialized.unshift(tmp);
}
inc++;
});
// Generate concatenation array
var concats = []
for (i = this.getColumnIndex(); i < this.columns.length; i++) {
concats[i] = " و";
}
//We do not need some "و"s check last column if 000 drill down until otherwise
if (this.digit > 999) {
if (parseInt(Array.from(serialized[serialized.length - 1]).join("")) == 0) {
concats[parseInt(concats.length - 1)] = ""
for (i = serialized.length - 1; i >= 1; i--) {
if (parseInt(Array.from(serialized[i]).join("")) == 0) {
concats[i] = ""
} else {
break;
}
}
}
}
var str = "";
str += "فقط ";
if (this.length() >= 1 && this.length() <= 3) {
str += this.read(this.digit);
} else {
for (i = 0; i < serialized.length; i++) {
var joinedNumber = parseInt(serialized[i].reverse().join(""));
if (joinedNumber == 0) {
column++;
continue;
}
if (column == null || column + 1 > this.columns.length) {
str += this.read(joinedNumber);
} else {
str += this.addSuffixPrefix(serialized[i], column) + concats[column];
}
column++;
}
}
if (this.currency != "") {
if (this.digit >= 3 && this.digit <= 10) {
str += " " + this.currencies[this.currency].plural;
} else {
str += " " + this.currencies[this.currency].singular;
}
if (this.fraction != 0) {
if (this.digit >= 3 && this.digit <= 10) {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fractions;
} else {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fraction;
}
}
}
str += " لا غير";
return str;
};
Tafgeet.prototype.addSuffixPrefix = function (arr, column) {
if (arr.length == 1) {
if (parseInt(arr[0]) == 1) {
return this[this.columns[column]].singular;
}
if (parseInt(arr[0]) == 2) {
return this[this.columns[column]].binary;
}
if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
return (
this.readOnes(parseInt(arr[0])) +
" " +
this[this.columns[column]].plural
);
}
} else {
var joinedNumber = parseInt(arr.join(""));
if (joinedNumber > 1) {
return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
} else {
return this[this.columns[column]].singular;
}
}
};
Tafgeet.prototype.read = function (d) {
var str = "";
var len = Array.from(d.toString()).length;
if (len == 1) {
str += this.readOnes(d);
} else if (len == 2) {
str += this.readTens(d);
} else if (len == 3) {
str += this.readHundreds(d);
}
return str;
};
Tafgeet.prototype.readOnes = function (d) {
if (d == 0) return;
return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function (d) {
if (Array.from(d.toString())[1] === "0") {
return this.tens["_" + d.toString()];
}
if (d > 10 && d < 20) {
return this.teens["_" + d.toString()];
}
if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
return (
this.readOnes(Array.from(d.toString())[1]) +
" و" +
this.tens["_" + Array.from(d.toString())[0] + "0"]
);
}
};
Tafgeet.prototype.readHundreds = function (d) {
var str = "";
str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];
if (
Array.from(d.toString())[1] === "0" &&
Array.from(d.toString())[2] !== "0"
) {
str += " و" + this.readOnes(Array.from(d.toString())[2]);
}
if (Array.from(d.toString())[1] !== "0") {
str +=
" و" +
this.readTens(
(Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
);
}
return str;
};
Tafgeet.prototype.length = function () {
return Array.from(this.digit.toString()).length;
};
Tafgeet.prototype.getColumnIndex = function () {
var column = null;
if (this.length() > 12) {
column = 0;
} else if (this.length() <= 12 && this.length() > 9) {
column = 1;
} else if (this.length() <= 9 && this.length() > 6) {
column = 2;
} else if (this.length() <= 6 && this.length() >= 4) {
column = 3;
}
return column;
};
Tafgeet.prototype.ones = {
_1: "واحد",
_2: "ٱثنين",
_3: "ثلاثة",
_4: "أربعة",
_5: "خمسة",
_6: "ستة",
_7: "سبعة",
_8: "ثمانية",
_9: "تسعة"
};
Tafgeet.prototype.teens = {
_11: "أحد عشر",
_12: "أثني عشر",
_13: "ثلاثة عشر",
_14: "أربعة عشر",
_15: "خمسة عشر",
_16: "ستة عشر",
_17: "سبعة عشر",
_18: "ثمانية عشر",
_19: "تسعة عشر"
};
Tafgeet.prototype.tens = {
_10: "عشرة",
_20: "عشرون",
_30: "ثلاثون",
_40: "أربعون",
_50: "خمسون",
_60: "ستون",
_70: "سبعون",
_80: "ثمانون",
_90: "تسعون"
};
Tafgeet.prototype.hundreds = {
_100: "مائة",
_200: "مائتين",
_300: "ثلاثمائة",
_400: "أربعمائة",
_500: "خمسمائة",
_600: "ستمائة",
_700: "سبعمائة",
_800: "ثمانمائة",
_900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
singular: "ألف",
binary: "ألفين",
plural: "ألآف"
};
Tafgeet.prototype.milions = {
singular: "مليون",
binary: "مليونين",
plural: "ملايين"
};
Tafgeet.prototype.bilions = {
singular: "مليار",
binary: "مليارين",
plural: "مليارات"
};
Tafgeet.prototype.trilions = {
singular: "ترليون",
binary: "ترليونين",
plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];
Tafgeet.prototype.currencies = {
SDG: {
singular: "جنيه سوداني",
plural: "جنيهات سودانية",
fraction: "قرش",
fractions: "قروش"
},
SAR: {
singular: "ريال سعودي",
plural: "ريالات سعودية",
fraction: "هللة",
fractions: "هللات"
},
QAR: {
singular: "ريال قطري",
plural: "ريالات قطرية",
fraction: "درهم",
fractions: "دراهم"
},
AED: {
singular: "درهم أماراتي",
plural: "دراهم أماراتية",
fraction: "فلس",
fractions: "فلوس"
},
EGP: {
singular: "جنيه مصري",
plural: "جنيهات مصرية",
fraction: "قرش",
fractions: "قروش"
},
USD: {
singular: "دولار أمريكي",
plural: "دولارات أمريكية",
fraction: "سنت",
fractions: "سنتات"
},
AUD: {
singular: "دولار أسترالي",
plural: "دولارات أسترالية",
fraction: "سنت",
fractions: "سنتات"
},
TND: {
singular: "دينار تونسي",
plural: "دنانير تونسية",
fraction: "مليم",
fractions: "مليمات"
}
};
module.exports = Tafgeet;
Thanks.
Change this:
this.fraction = "" + trimmed[0] + trimmed[1];
To this:
this.fraction = "" + trimmed[0] + trimmed[1] + trimmed[2];
But this is a crude solution you need to do some validations and checks before you deploy this to production

Can't understand the logic of a JavaScript code block [Bulls and Cows game]

I'm in need of a little help. I need to write a detailed interpretation of a JavaScript code for a game of Bulls and Cows and I don't understand exactly what's happening in the main logic block. This is the block:
//Check Bull,Cow,Try Again
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
for (var k = 0; k < userText.length; k++) {
if ((getNum[i] == userText[k]) && (i == k)) {
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
cow++;
}
}
}
if (bull == 0 && cow == 0) {
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
}
check = true;
}
Also here's the entire program in case you need to check the interconnection of variables and such:
var getNum = new Array();
var numLength;
var check = true;
window.onload = function() {
numLength = document.getElementById("select").value;
setNumber();
}
/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
var random;
getNum.splice(0, getNum.length);
while (getNum.length < numLength) {
random = Math.floor(Math.random() * 9) + 1;
for (var i = 0; i < getNum.length; i++) {
if (getNum[i] == random) {
check = false;
break;
}
}
if (check) {
getNum.push(random);
}
check = true;
}
}
//Check user number
function checkUserText() {
var userText = document.getElementById("userText").value;
var setText = document.getElementById("textArea");
//Check if userText is number
for (var i = 0; i < userText.length; i++) {
if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
|| userText.length != numLength) {
setText.innerHTML += "Type only" + numLength + " numbers!\n";
check = false;
break;
}
}
//Check Bull,Cow,Try Again
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
for (var k = 0; k < userText.length; k++) {
if ((getNum[i] == userText[k]) && (i == k)) {
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
cow++;
}
}
}
if (bull == 0 && cow == 0) {
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
}
check = true;
}
//change difficulty
function difficulty() {
numLength = document.getElementById("select").value;
reload();
}
//restart game
function reload() {
setNumber();
document.getElementById("textArea").innerHTML = "";
}
I understand the general idea of the block but I can't see the specifics, I can't see the logic behind it, if someone could explain this block to me or make a quick flow chart I would be more than grateful.
var getNum = new Array();
var numLength;
var check = true;
window.onload = function() {
numLength = document.getElementById("select").value;
setNumber();
}
/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
var random;
getNum.splice(0, getNum.length);
while (getNum.length < numLength) {
random = Math.floor(Math.random() * 9) + 1;
for (var i = 0; i < getNum.length; i++) {
if (getNum[i] == random) {
check = false;
break;
}
}
if (check) {
getNum.push(random);
}
check = true;
}
}
//Check user number
function checkUserText() {
var userText = document.getElementById("userText").value;
var setText = document.getElementById("textArea");
//Check if userText is number
for (var i = 0; i < userText.length; i++) {
if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
|| userText.length != numLength) {
setText.innerHTML += "Type only" + numLength + " numbers!\n";
check = false;
break;
}
}
//Check Bull,Cow,Try Again
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
for (var k = 0; k < userText.length; k++) {
if ((getNum[i] == userText[k]) && (i == k)) {
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
cow++;
}
}
}
if (bull == 0 && cow == 0) {
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
}
check = true;
}
//change difficulty
function difficulty() {
numLength = document.getElementById("select").value;
reload();
}
//restart game
function reload() {
setNumber();
document.getElementById("textArea").innerHTML = "";
}
<!DOCTYPE html>
<html>
<head>
<title>Bulls and Cows</title>
<script type="text/javascript" src="operation.js">
</script>
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
h2 {
font-family: Lobster;
color: blue;
}
body {
background-color: #cccccc
}
</style>
</head>
<body>
<h2>Bulls and Cows</h2>
<label for="userText">Type here: </label>
<input type="text" id="userText"/>
<br />
<button id="ch" onclick="checkUserText()">check</button>
<button id="re" onclick="reload()">restart</button>
Length : <select id="select" onchange="difficulty()">
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<br />
<textarea id="textArea" rows="20" cols="30" readonly="readonly" style="overflow-y: scroll"></textarea>
</body>
</html>
// ok lets assume the getNum.length is 3
// and the random getNum is 123
// and user enters 321 and clicks check
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
// this will loop three times
// in the first iteration getNum[i] == 1
// the second iteration getNum[i] == 2
// the third iteration getNum[i] == 3
for (var k = 0; k < userText.length; k++) {
// for each iteration of getNum it will iterate all user input (also 3 times)
// so 3 times per iteration of getNum, clear so far? good
// so at first iteration userText[k] == 3
// so at second iteration userText[k] == 2
// so at third iteration userText[k] == 1
// while i keeps the value of the outer loop
// this expression checks if user input matches the same number on the same position in getNum
if ((getNum[i] == userText[k]) && (i == k)) {
// in the second iteration of the outer loop its a bull because
// getNum[i] == 2 == userText[k] == 2 AND 1 == 1 (number and position of number/index is matching the random number
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
// in the first and last iteration of the outer loop its a cow because
// getNum[i] == 1/2 == userText[k] == 1/2 AND 0/2 is NOT 2/0 (number is matching but position not matching)
cow++;
}
// if the getNum[i] doesnt exist at all in userText, neither cow or bull will count up
}
}
if (bull == 0 && cow == 0) {
// so if no number matched - try again
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
// if all numbers and positions (cow) matched you won
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
// else show how many "cows" and "bulls"
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
// so the output of above assumption would be
// 1 bull, 2 cows
// cool game ;-)
}

Nothing happens after Prompt

Sorry, I wasn't clear enough. I need it to list all the numbers from 0 to the number inputted by the prompt into the HTML. I made some suggested changes but now I only get the result for the specific number inputted, not all the numbers up to that number. I am just starting out so please be gentle. Thanks!
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for(var i = 0; i <= number; i++) {
if ( i %15 == 0) {
result = "Ping-Pong";
}
else if (i %5 == 0) {
result = "Pong";
}
else if (i %3 == 0) {
result = "Ping";
}
else {
result = number;
}
document.getElementById("show").innerHTML = result;
};
});
You can do either:
for(var i = 0; i <= number; i++) {
var digit = number[i]; // or any other assigment to new digit var
if ( digit % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
or
if ( number % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
Problem is you did nothing after the return keyword. Also you didn't declared variable as digit. I hope this is what you are looking for.
With loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for (var i = 0; i <= number; i++) {
if (i % 15 == 0) { // replaced `digit` with `i`
result = "Ping-Pong";
} else if (i % 5 == 0) {
result = "Pong";
} else if (i % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
if (number % 15 == 0) { // replaced `digit` with `number`
result = "Ping-Pong";
} else if (number % 5 == 0) {
result = "Pong";
} else if (number % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Ok, I figured it out. For future reference, this is what I was trying to do:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var i
var text = "";
for(i = 1; i <= number; i++) {
if ( i %15 == 0) {
text += "<br>" + "Ping Pong" + "<br>";
}
else if (i %5 == 0) {
text += "<br>" + "Pong" + "<br>";
}
else if (i %3 == 0) {
text += "<br>" + "Ping" + "<br>";
}
else {
text += "<br>" + i + "<br>";
}
};
document.getElementById("show").innerHTML = text;
});

Categories

Resources