how to show when a value is zero or below - javascript

I am busy whith a monopaly game.It is almost done but I cant find out how to
show when the user is bankrupt
I would prefer to use my isBankrupt function to check if the persons money is less then or equal to zero, if so it sould log that that user is bankrupt
I have tried including an if statement in my dice function but it is not working.
let player = [
{
name: "",
money: 1000,
position: 0,
propertys: [
{
name: "raslow",
position: 2,
cost: 20
},
{
name: "luadiam",
position: 4,
cost: 50
},
{
name: "eldo",
position: 6,
cost: 100
},
{
name: "erasmia",
position: 8,
cost: 200
}
],
dice() {
let random = Math.floor(Math.random() * 11);
for (var i = 0; i < player[0].propertys.length; i++) {
if (random === player[0].propertys[i].position) {
console.log("you are safe");
break;
}
else if (random == 1 || random == 10) {
console.log("you are safe");
break;
}
else if(random !== player[0].propertys[i].position){
if (random === 3) {
console.log("you have landed on Columbus");
player[0].money -= 20;
player[1].money += 20;
break;
}
if (random === 5) {
console.log("you have landed on Essex");
player[0].money -= 50;
player[1].money += 50;
break;
}
if (random === 7) {
console.log("you have landed on Eugene ");
player[0].money -= 100;
player[1].money += 100;
break;
}
if (random === 9) {
console.log("you have landed on Diego ");
player[0].money -= 200;
player[1].money += 200;
break;
}
}
}
console.log(player[0].name + ' ' + "has" + " " + player[0].money);
console.log(player[1].name + ' '+ "has" + " " + player[1].money);
},
isBankrupt(){
while(player[0].money <= 0){
console.log(player[0].name + ' ' + 'is Bankrupt')
}
}
},
{
name: "",
money: 1000,
position: 0,
property: [
{
name: "Columbus",
position: 3,
cost: 20
},
{
name: "Essex",
position: 5,
cost: 50
},
{
name: "Eugene",
position: 7,
cost: 100
},
{
name: "Diego",
position: 9,
cost: 200
}
],
dice() {
let random = Math.floor(Math.random() * 11);
for (var i = 0; i < player[0].propertys.length; i++) {
if (player[1].money <= 0) {
break;
}
if (random === player[0].propertys[i].position) {
console.log("you are safe");
break;
}
else if (random == 1 || random == 10) {
console.log("you are safe");
break;
}
else if(random !== player[0].propertys[i].position) {
if (random === 2) {
console.log("you have landed on raslow");
player[0].money += 20;
player[1].money -= 20;
break;
}
if (random === 4) {
console.log("you have landed on luadiam ");
player[1].money -= 50;
player[0].money += 50;
break;
}
if (random === 6) {
console.log("you have landed on eldo ");
player[1].money -= 100;
player[0].money += 100;
break;
}
if (random === 8) {
console.log("you have landed on erasmia ");
player[1].money -= 200;
player[0].money += 200;
break;
}
}
}
console.log(player[0].name + ' ' + "has" + " " + player[0].money);
console.log(player[1].name + ' ' + "has" + " " + player[1].money);
},
isBankrupt(){
while(player[0].money <= 0){
console.log(player[0].name + ' ' + 'is Bankrupt')
}
}
}
];
function playgame() {
player[0].name = prompt('Enter player1 name')
player[1].name = prompt('Enter player2 name')
}
Please help out

You can check for bankruptcy with a simple if statement:
if (player[0].money <= 0) {
console.log(player[0].name + ' ' + 'is Bankrupt');
}
If you want to put it into a function so that you can call it for each player -- instead of writing multiple checks into your code -- you can call isBankrupt with the index of the current player and write the function like this:
function isBankrupt(p) {
// p = the current player
if (player[p].money <= 0) {
console.log(player[p].name + ' ' + 'is Bankrupt');
}
}

Related

How can I fix the uncaught type error in this code?

I don't believe I can set the type of the variable before the function that expands the array and it is being set in that function. So, I'm not sure why it would have a type error.
Thus the variable with the issue playercontrolledf is set to false throughout the array as soon as it is first initialized.
I apologize in advance if I have not posted correctly or broken any etiquette is has been some time since I have been on stack overflow and I am relatively new to javascript and stack overflow as well. Also to actually see what the code is doing you will have to switch it to fullscreen.
The Error I am getting in Chrome is
Uncaught TypeError: Cannot read property '127' of undefined
at gameTurn (main.js:76)
at endTurn (main.js:120)
at reposition (main.js:206)
at HTMLDocument.<anonymous> (main.js:233)
Here is my code for the game
/* Dunegon Valley by heromedel all rights reserved */
function gameloop() { // Entire Game contained withing function
var mainArray = []; // most game data will be held withing the array
var mapSizeX = 32; // sets the height of the rendered map and corresponding array coordinates
var mapSizeY = 128; // sets the width
var idPos = {
x: 16,
y: 64
}; // currently used to set player location and check for collisions
var rendFlr = 0; // sets which floor to render
var curFlr = 0; // sets which floor is currently accepting input
var maxlayout = 10; // sets the number of floors to generate
var curTurnX = 0;
var curTurnY = 0;
var gameState = 0;
var tile = { // lists charcters used for rendered tiles and objects
player: "☺",
bunny: "b",
rabbit: "r",
empty: ".",
wall: "#",
oak: "♠",
maple: "♣",
grass: "‚",
tallgrass: "„",
water: "≈"
};
function getRndInteger(min, max) { // returns random number from min to max number appears to not function predictably if min and max are the same number
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function nl() { // Creates a new line in the rendered text
GameScreen.innerText += "\n";
}
function gameTurn(cx, cy) { // progresses through each tile checking if its player controlled or not using the while statement in end turn
if (mainArray[cx][cy]['playercontrolledf' + curFlr] === "true") {
render(rendFlr);
mainArray[cx][cy]['entTurnf' + curFlr] = "true";
gameState = 1;
}
if (mainArray[cx][cy]['playercontrolledf' + curFlr] != "true") { // call functions for non player controlled tiles
//mainArray[cx][cy]['entTurnf' + curFlr] = "true";
if (mainArray[cx][cy]['entityf' + curFlr] === "bunny") {
//alert("Bunny Turn" );
mainArray[cx][cy]['entityf' + curFlr] = "rabbit" // to show that each bunny is getting selected this line changes the bunnny into a rabbit
}
}
// progress to next turn / tile
if (curTurnX < mapSizeX) {
curTurnX++;
}
if (curTurnX === mapSizeX) {
if (curTurnY < mapSizeY) {
curTurnX = 0;
curTurnY++;
}
if (curTurnX === mapSizeX) {
if (curTurnY === mapSizeY) {
alert("worked"); // why does this never trigger
curTurnX = 0;
curTurnY = 0;
}
}
}
}
function endTurn() {
while (gameState === 0) {
gameTurn(curTurnX, curTurnY);
//alert("Turn "+ (curTurnX + curTurnY));
//render(rendFlr);
}
}
function initMap(mapSizeX, mapSizeY) { // expands and populates the array
for (var i = 0; i < mapSizeX; i++) {
mainArray.push([]) // I belive this is only expaning it 2 dimesionaly and matching the height
for (var j = 0; j < mapSizeY; j++) {
for (var k = 0; k < maxlayout; k++) {
const obj = mainArray[i][j] || {}; // creates on object to alter and add back into the main array
obj['tilef' + k] = tile.empty;
obj['terrainf' + k] = "empty";
obj['solidf' + k] = "false";
obj['entityf' + k] = "none";
obj['playercontrolledf' + k] = "false";
obj['entTurnf' + k] = "false";
obj['finished' + k] = "false";
mainArray[i][j] = obj;
if (k > 0) {
if (j == 0 || // wraps the underground floor 1 in walls
j == mapSizeY - 1 ||
i == 0 ||
i == mapSizeX - 1) {
mainArray[i][j]['terrainf' + k] = "wall";
mainArray[i][j]['solidf' + k] = "Wall";
}
}
}
//else{ // unneeded as the above for j is already creating empties
//mainArray[i][j].terrain = "empty";
//mainArray[i][j].solid = "false";
//}
}
}
}
function randAdd(odds, feature, solid, flr, type) { // A chance to add named feature and solid type
for (var i = 0; i < mapSizeX; i++) {
for (var j = 0; j < mapSizeY; j++) {
if (mainArray[i][j][type + 'f' + flr] === "empty" || mainArray[i][j][type + 'f' + flr] === "none") {
roll = getRndInteger(1, odds);
if (roll === odds) {
mainArray[i][j][type + 'f' + flr] = feature;
mainArray[i][j]['solidf' + flr] = solid;
}
}
}
}
}
function genMaps() { // Inside this function each line uses randAdd to randomly add a terrain type to a specified floor
randAdd(200, "wall", "solid rock", 0, 'terrain');
randAdd(100, "oak", "a tree", 0, 'terrain'); // (odds,terrain,solid,floor,type)
randAdd(100, "maple", "a tree", 0, 'terrain');
randAdd(2, "grass", "False", 0, 'terrain');
randAdd(2, "tallgrass", "False", 0, 'terrain');
randAdd(200, "bunny", "false", 0, 'entity');
randAdd(3, "wall", "solid rock", 1, 'terrain');
randAdd(2, "wall", "solid rock", 2, 'terrain');
randAdd(1, "wall", "solid rock", 3, 'terrain');
randAdd(1, "wall", "solid rock", 4, 'terrain');
randAdd(1, "wall", "solid rock", 5, 'terrain');
randAdd(1, "water", "false", 8, 'terrain');
randAdd(1, "water", "false", 9, 'terrain');
}
function tileSelect() {
for (var i = 0; i < mapSizeX; i++) {
for (var j = 0; j < mapSizeY; j++) {
if (mainArray[i][j]['entityf' + rendFlr] === "none") {
mainArray[i][j]['tilef' + rendFlr] = tile[mainArray[i][j]['terrainf' + rendFlr]];
} else {
mainArray[i][j]['tilef' + rendFlr] = tile[mainArray[i][j]['entityf' + rendFlr]]
}
}
}
}
function render(flr) { // displays the array tiles to the browser
GameScreen.innerText = mainArray.map(arr => arr.map(cell => cell['tilef' + flr]).join("")).join("\n");
nl();
nl();
}
function reposition(xChange, yChange, strA) { // checks if target position is not blocked and if not moves the player
if (mainArray[idPos.x + xChange][idPos.y + yChange]['solidf' + curFlr] === "false" ||
mainArray[idPos.x + xChange][idPos.y + yChange]['solidf' + curFlr] === "False" ||
mainArray[idPos.x + xChange][idPos.y + yChange]['solidf' + curFlr] === "") {
idPos.x = idPos.x + xChange;
idPos.y = idPos.y + yChange;
mainArray[idPos.x][idPos.y]['entityf' + curFlr] = "player";
mainArray[idPos.x - xChange][idPos.y - yChange]['entityf' + curFlr] = "none";
GameLog.innerText = "You take a step to the " + strA
} else {
GameLog.innerText = "You can not enter " + mainArray[idPos.x + xChange][idPos.y + yChange]['solidf' + curFlr];
}
mainArray[idPos.x][idPos.y]['terrainf' + curFlr] != "empty" ?
GameLog.innerText += "\n There is " + mainArray[idPos.x][idPos.y]['terrainf' + curFlr] + " in this spot" :
GameLog.innerText += "\n There is nothing in this spot";
GameLog.innerText += "\n \n Elevation " + (curFlr * 50 * -1);
tileSelect();
render(rendFlr);
gameState = 0;
endTurn();
}
//Startup
initMap(32, 128);
genMaps();
mainArray[idPos.x][idPos.y]['entityf' + curFlr] = "player";
mainArray[idPos.x][idPos.y]['playercontrolledf' + curFlr] = "true";
//First Render
tileSelect();
render(rendFlr);
document.addEventListener('keydown', function(event) {
if (event.keyCode === 38) { // up arrow
reposition(-1, 0, "North");
//alert(curTurnX);
}
if (event.keyCode === 40) { // down arrow
reposition(1, 0, "South");
}
if (event.keyCode === 37) { // left arrow
reposition(0, -1, "West");
}
if (event.keyCode === 39) { // right arrow
reposition(0, 1, "East");
}
if (event.keyCode === 190) { // period
if (rendFlr < maxlayout - 1) {
mainArray[idPos.x][idPos.y]['entityf' + (curFlr + 1)] = "player";
mainArray[idPos.x][idPos.y]['entityf' + (curFlr)] = "none";
curFlr++;
rendFlr++;
GameLog.innerText = "You descened. \n \n Elevation " + (curFlr * 50 * -1);
}
tileSelect();
render(rendFlr);
}
if (event.keyCode === 188) { // comma
if (rendFlr > 0) {
mainArray[idPos.x][idPos.y]['entityf' + (curFlr - 1)] = "player";
mainArray[idPos.x][idPos.y]['entityf' + (curFlr)] = "none";
curFlr--;
rendFlr--;
GameLog.innerText = "You ascened. \n \n Elevation " + (curFlr * 50 * -1);
}
tileSelect();
render(rendFlr);
}
//alert(event.keyCode);
});
}
gameloop();
/* Dunegon Valley by heromedel all rights reserved */
.info {
color: #7d7d7d;
font-family: Lucida Console;
}
.info span {
color: #ABABAB;
font-family: Lucida Console;
font-size: 0.5em;
}
#GameScreen {
color: #000000;
font-family: Lucida Console;
font-weight: italic;
margin-left: auto;
margin-right: auto;
}
#GameLog {
color: #000000;
font-family: Lucida Console;
}
<!DOCTYPE html>
<!-- Dunegon Valley by heromedel all rights reserved -->
<html>
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="utf-8">
<title>Dungeon Valley</title>
</head>
<body>
<br>
<p class="info">Dungeon Valley.<br>
<span class="">
Taming the Borderlands.<br> v0.011 By heromedel.
</span>
</p>
<span id="GameScreen"></span>
<section id="GameLog">Arrow Keys to move.<br></section>
<script src="main.js"></script>
</body>
</html>
The problem is that curTurnY is too large. This code:
if (curTurnY < mapSizeY) {
curTurnX = 0;
curTurnY++;
}
allows it to get too high. The maximum value of curTurnY should be 127. But when the value is already 127, this code will increment it to 128, which is outside the array. Change the condition to:
if (curTurnY < mapSizeY-1) {
curTurnX = 0;
curTurnY++;
}
Check all your other conditions for similar errors.

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

Use While Loop With setTimeout

I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:
function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
var ibumped = i + 1;
console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
var weaponChoice = prompt("Which weapon do you choose?");
switch (weaponChoice) {
case 1:
weaponChosen = userWeapons[0];
console.log(userWeapons[0].name + " chosen.");
break;
case 2:
weaponChosen = userWeapons[1];
console.log(userWeapons[1].name + " chosen.");
break;
default:
weaponChosen = userWeapons[0];
console.log(userWeapons[0].name + " chosen.");
};
}, 1000);
setTimeout(function() {
if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
enemy.shields = enemy.shields - weaponChosen.damage;
weaponChosen.fire(enemy);
if (enemy.shields < 0) {
enemy.health = enemy.health + enemy.shields;
console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
} else {
console.log("Enemy shields have been reduced to " + enemy.shields + ".");
}
} else {
enemy.health = enemy.health - weaponChosen.damage;
weaponChosen.fire(enemy);
console.log("Enemy takes " + weaponChosen.damage + " damage!");
}
if (enemy.health <= 0 && battleOver === false) {
console.log("Enemy destroyed!");
battleOver = true;
}
}, 3000);
setTimeout(function() {
if (enemy.health > 0 && battleOver === false) {
if (enemy.weapons != null) {
console.log(enemy.weapons.name + " fired at you.");
health = health - enemy.weapons.damage;
console.log("You have " + health + " health left.");
if (health <= 0) {
console.log("Game over... You were destroyed");
battleOver = true;
}
} else {
console.log("The enemy did nothing...");
}
};
}, 5000);
}
}
All help is appreciated!
Things start getting very tricky when you use setTimeout. Most games will have a "main game loop" that runs 60 times a second.
Try using a main game loop and cooldowns.
Here's an example of how you could restructure the program.
var timeForOneFrame = 1000/60 // 60 Frames per second
var enemy;
var battleOver;
function initGame() {
/*
Initialize the enemy etc.
*/
}
function gameLoop() {
battle(enemy);
}
function battle(enemy) {
/*
Do all the battle stuff, this function is called 60 times a second-
there's no need for setTimeout!
*/
// If you want an enemy to only be able to attack every 2 seconds, give them
// a cooldown...
if (enemy.cooldown <= 0) {
// Attack!
enemy.cooldown += 2000
} else {
enemy.cooldown -= timeForOneFrame
}
if (enemy.health <= 0 && battleOver === false) {
console.log("Enemy destroyed!");
battleOver = true;
clearInterval(gameLoopInterval)
}
}
initGame();
var gameLoopInterval = setInterval(gameLoop, timeForOneFrame);
A while loop blocks the whole page until it ends, and as your loop never exits its infinite. You may replace it with a high speed interval:
const loop = setInterval( function(){
if( battleOver ) return clearInterval(loop);
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
console.log("Press " + (i + 1) + " to fire the " + userWeapons[i].name + ".");
}
},10);
I would take that loop out and use a recursive call on the end of the interactions.
Let's say:
function battle(enemy) {
//All your code here
if (HeroAlive) {
battle(enemy);
}
}

True/false as strings, only allowed boolen

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)

error message instead of NaN output and negative 'Nett Payment' output

var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent);
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
document.write("<br/>" + "Discount Amount: $" + applyDiscount);
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount);
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
At the moment when I enter a value that isn't between 1 to 100 in 'vTicketQty' the output is 'NaN' for 'Nett Payment' and 'Discount Amount', how do I get the output value to show an error message instead of NaN?
Also when I don't enter 'a' , 'b' or 'c' for 'vTicketType' the output for 'Nett Payment" is negative, again how do I get the output to show an error message instead?
use like this .
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent)|0;
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount)|0;
variable is invalid it's return with '0'
var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent)|0;
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
if(applyDiscount){
document.write("<br/>" + "Discount Amount: $" + applyDiscount)
}
else{
document.write("<br/>Error-something not right in Discount Amount")
}
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount)|0;
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
if(vNettPayment){
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
}
else{
document.write("<br/>Error-something not right in Nett Payment ")
}

Categories

Resources