madlibs generator webpage with javascript - javascript

I want to use only 1 input bar to cycle through different prompts asking the user to input nouns, verbs, adjectives, etc. I want it to cycle through every time the user presses the 'enter' key. And at the very end, I want the entire madlib paragraph to print out at the bottom with the stored user input values. I think using an array was correct in order to store the user input values.. I'm stuck. Am I doing this right??
full codepen with HTML and CSS here (to see my simple concept idea): https://codepen.io/stanimal93/pen/GRJGeEb
let prompt = document.getElementById('prompt');
let input = document.getElementById('userinput');
let madlib = document.getElementById('madlibparagraph');
input.addEventListener("keyup", submit(event));
input.addEventListener("keyup", resetInput);
input.addEventListener("keyup", changePrompt);
function submit(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
}
function resetInput() {
input.value = "" // to clear the input
}
function changePrompt() {
let word = new Array();
word[0] = "a location: "
word[1] = "a living thing: "
word[2] = "a name: "
word[3] = "a kind of food: "
word[4] = "a noun: "
word[5] = "a verb: "
word[6] = "a color: "
word[7] = "a plural noun: "
word[8] = "a sound: "
for (i = 0; i < 10; i++) {
prompt.innerHTML = word[i];
word[i] = input.value
};
}
// var location = "a location: "
// var livingThing = "a living thing: "
// var name = "a name: "
// var food = "a kind of food: "
// var noun = "a noun: "
// var verb = "a verb: "
// var color = "a color: "
// var pluralNoun = "a plural noun: "
// var sound = "a sound: "
// let words = [location, livingThing, name, food, noun, verb, color, pluralNoun, sound]
let madib.innerHTML = "Once upon a time in " + _______ + ", there was a " + _______ + " named " + _________ + ". The world was stricken by coronavirus in the year 2020 and there was no " + ________ + " to eat anymore. " + ________ + " went outside to find " + _________ + " and realized everyone was " + ________ + ". There were " + ________ + " colored " + __________ + " and you could hear " + ___________ + " in the distance.";

Solved and finished it myself and it is bug free! I had trouble wrapping my head around using a for loop as opposed to an if statement during an eventListener keypress event, along with a fadein type of function. Feel free to play it! in this codepen: https://codepen.io/stanimal93/pen/GRJGeEb
$(document).ready(function() {
let prompt = document.getElementById('prompt');
let input = document.getElementById('userinput');
let madlib = document.getElementById('madlibparagraph');
function resetInput() {
input.value = '' // to clear the input
}
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
prompt.style.opacity = 0;
storeAnswer();
resetInput();
setTimeout(fadein, 500);
function fadein() {
prompt.style.opacity = 1;
changePrompt();
}
}
});
let word = new Array();
word[0] = "a living thing: "
word[1] = "a name: "
word[2] = "a kind of food: "
word[3] = "a noun: "
word[4] = "a verb: "
word[5] = "a color: "
word[6] = "a plural noun: "
word[7] = "a sound: "
word[8] = "Read your madlib below!"
var i = 0
function changePrompt() {
if (i < 9) {
console.log(i);
prompt.innerHTML = word[i];
console.log(answer);
i++
}
if (i === 9) {
madlib.innerHTML = "Once upon a time in " + answer[0].toUpperCase().bold() + ", there was a " + answer[1].toUpperCase().bold() + " named " + answer[2].toUpperCase().bold() + ". The world was stricken by coronavirus in the year 2020 and there was no " + answer[3].toUpperCase().bold() + " to eat anymore. " + answer[2].toUpperCase().bold() + " went outside to find " + answer[4].toUpperCase().bold() + " and realized everyone was " + answer[5].toUpperCase().bold() + ". There were " + answer[6].toUpperCase() + " colored " + answer[7].toUpperCase().bold() + " and you could hear " + answer[8].toUpperCase().bold() + " in the distance.";
}
}
function storeAnswer() {
for (var a = 0; a < 9; a++) {
answer[i] = input.value;
}
}
let answer = new Array();
answer[0] = ""
answer[1] = ""
answer[2] = ""
answer[3] = ""
answer[4] = ""
answer[5] = ""
answer[6] = ""
answer[7] = ""
answer[8] = ""
});

Related

Basic JavaScript - How to randomly compare two properties from an array of objects

I have an exercise where from an object constructor, I have created several objects, all with an ID property.
The first part of the exercise consist in pairing each object, compare their markAv properties and print the one that had it bigger.
[ a vs b => b wins]
They suggested to do so by using the ID property but I didn't know how to do it that way... so I tried a workaround, as you will see in the code below.
However, the second part of the exercise wants me to do the same but, this time, creating the pairs randomly. Here I have tried to use the ID property by generating a random number that matches the ID but I don´t know how to structure the code for it to work.
The output for the second part should be the same as above, with the only difference that the pairing is now randomly generated.
I have added a partial solution for the second part, partial because from time to time it throws an error that I can´t identify. However, I think I'm getting close to get my desired output.
I would really appreciate if anyone could give me a hint for me to crack the code below and to get it working because I really want to understand how to do this.
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function getPairs(array) {
function getPairs(array) {
for (let i = 0; i < array.length; i += 2) {
if (array[i].markAv < array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i + 1].name + " Wins")
} else if (array[i].markAv > array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i].name + " Wins")
}
}
}
getPairs(heroes)
///
function randomAv(array) {
let result = []
let hero1 = heroes[Math.floor(Math.random() * 6) + 1]
for(let i = 0; i<array.length; i++){
if (array[i].markAv <= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + array[i].name + " Wins"))
} else if(array[i].markAv >= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + hero1.name + " Wins"))
}
}
console.log(result)
}
First shuffle the array:
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
let heroes_shuffle = heroes.sort((a, b) => 0.5 - Math.random())
Then do as normal
getPairs(heroes_shuffle )
All Possible Combination :
function allPairs(heroes) {
while (heroes) {
[hero, ...heroes] = heroes
for (enemy of heroes) {
if (hero.markAv === enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": draw")
else if (hero.markAv < enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": " + enemy.name + " Wins")
else
console.log(hero.name + " vs " + enemy.name + ": " + hero.name + " Wins")
}
}
}
You can take the function from here https://stackoverflow.com/a/7228322/1117736
And do something like this:
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
let hero1 = heroes[randomIntFromInterval(1, 6)]
let hero2 = heroes[randomIntFromInterval(1, 6)]
if (hero1.markAv < hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero1.name + " Wins")
} else if(hero1.markAv > hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero2.name + " Wins")
}

javascript alert showing code insted of string

first and foremost i'm new to javascript and coding. second, i'm coding a book store project with javascript with an alert message that shows each customer's total factor. but the alert message shows the code of my function "printFactor" insted of the string that is made by this function. this is my code:
function Book(name, writer, date, price)
{
this.name = name;
this.writer = writer;
this.date = date;
this.price = price;
}
function Customer(name, gender, turn)
{
this.name = name;
this.gender = gender;
this.turn = turn;
this.numberOfBooks = 0;
this.totalSum = 0;
this.bookList = [new Book("-", "-", "-", 0)];
//Functions.
this.addBook = function (newBook) {
this.numberOfBooks++;
this.bookList.push(newBook);
};
this.printFactor = function () {
var message = "";
if (this.numberOfBooks === 0) {
message = "No Books Has Been Added to Book List!";
return (message);
}
else {
message = this.name + " " + this.gender + " Number of Books: " + this.numberOfBooks + " Customer's Turn: " + this.turn + "\nBooks:\n";
var i;
var newMessage;
for (i = bookList.length - 1; i > 0; i--) {
newMessage = bookList[i].name + " " + bookList[i].writer + " " + bookList[i].date + " " + bookList[i].price.toString() +"\n" ;
message += newMessage;
this.totalSum += bookList[i].price;
this.bookList.pop();
}
newMessage = "Total Sum: " + this.totalSum;
message += newMessage;
return (message);
}
};
}
var book = new Book("Faramarz Bio", "Faramarz Falsafi Nejad", "1377/04/29", 13000);
var faramarz = new Customer("faramarz", "Male", 3);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
var m = faramarz.printFactor;
window.alert(m);
You need to invoke the function:
var m = faramarz.printFactor();
As is your variable m contains a reference to the function, but you need to call it to get the result.
var m = faramarz.printFactor();
window.alert(m);
You simply don't call your function, this should work.
var m = faramarz.printFactor()
Beside you reference an unexisting variable 'booklist', that should be "this.booklist"
for (i = this.bookList.length - 1; i > 0; i--) {
newMessage = this.bookList[i].name + " " + this.bookList[i].writer + " " + this.bookList[i].date + " " + this.bookList[i].price.toString() +"\n" ;
You need to actually call the function by adding () to the end, like this:
var m = faramarz.printFactor()

Edit a variable within an array

I'm attempting to create a Choose Your Own Adventure type of game, and I'm currently trying to write a 'battle' script. What I've got so far is:
var name = "Anon";
var health = 100;
var youAttack = [name + " hits the " + opp + " with his sword", name + " uses magic!", name + " is too scared to fight!"];
var youBattle = function() {
var youBattle = youAttack[Math.floor(Math.random() * 3)];
return youBattle;
};
var opp = "Orc";
var oppHealth = 100;
var oppAttack = ["The " + opp + " hits you with his hammer!", "The " + opp + " does nothing!", "The " + opp + " back hands you!"];
var oppBattle = function() {
var oppBattle = oppAttack[Math.floor(Math.random() * 3)];
return oppBattle;
};
oppBattle();
youBattle();
I've done it like this so the opponent and player names can easily be changed.
What I'm struggling to figure out is how I can add / remove health from both the opponent and the player depending what attack is used. Obviously no health would be removed if the opp / player does nothing.
Is there a way I can do this without a bunch of messy if / else statements?
I was hoping for something easy like name + " hits the " + opp + " with his sword" + health = health - 10; but obviously that didn't work.
Thanks in advance!
http://jsbin.com/qerud/3/edit
Hope this isn't too much code:
var Attack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
return this.message;
};
};
var Character = function(name,health){
this.name = name;
this.health = health;
};
hero = new Character('Anon',100);
orc = new Character('Orc',150);
attack1 = new Attack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = new Attack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = new Attack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = new Attack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
I can tell you first hand that trying to write this type of code uses a lot of if/else and more statements, regardless of what language you're using. You can use an array to hold the values of your attack patterns:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
function youAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
But, without seeing exactly what you're doing I cannot say how you should do your attacks and damages. I can only assume. You will need a system of evaluating attacks, misses, etc. that does use IF/ELSE Statements at least somewhere.

So I've restarted my While-loop program and now am getting all NaN or they aren't saving the text I input

I need to write a program for a wedding planner. They wish to create a gift registry for each couple. They want the gifts broken down by the whether the gift giver is on the bride side or groom side. They also know that specific gifts (toasters, silverware, and stemware) tend to be repeated so they want those gifts listed and have the name of the gift giver under them. The repeating gifts are only the ones that have been told you by the client (toasters, silverware, and stemware) they do not want you to determine which gifts repeat, they are just looking for those specific three. So I can implement code for only silverware, stemware, and toasters, which I have this time. But now I cannot get any correct output.
After the program has run, it should have a printout somewhat like this.
Groom side:
Tom: toaster
Bill: silverware
Bob: stemware
Steve: Lexus
Bride side:
Jill: toaster
Suzy: silverware
Pat: stemware
Karen: horse
Multiple toasters by:
Tom
Jill
Multiple silverware by:
Bill
Suzy
Multiple stemware by:
Bob
Pat
Here is what I've got so far...
var guestName;
var gift, side, kind, groomNameAccum, brideNameAccum;
var toaster, silverware, stemware, giftType;
var toasterAccum, silverwareAccum, stemwareAccum;
var noGift = 0;
var groomCounter = 0;
var brideCounter = 0;
//initalizing loop
var guest = "yes";
//start loop
while (guest == "yes") {
side = prompt("Which side are you on? groom or bride?", "");
guestName = prompt("Whats your name?", "");
kind = prompt("What kind of gift?", "");
if (side == "groom") {
groomCounter = groomCounter + 1;
if (groomCounter == 1) {
groomNameAccum = "Groom side: <br>" + groomCounter + ". " + guestName + ": " + kind;
} else {
groomNameAccum = groomNameAccum + "<br>" + groomCounter + ". " + guestName + ": " + kind;
}
} else
if (side == "bride") {
brideCounter = brideCounter + 1;
if (brideCounter == 1) {
brideNameAccum = "<p>Bride side: <br>" + brideCounter + ". " + guestName + ": " + kind;
} else {
brideNameAccum = brideNameAccum + "<br>" + brideCounter + ". " + guestName + ": " + kind;
}
}
if (kind == "toaster")
{
toasterAccum = toasterAccum + "; " + guestName;
}
else if(kind == "silverware")
{
silverwareAccum= silverwareAccum + "; " + guestName;
}else if (kind == "stemware")
{
stemwareAccum = stemwareAccum + "; " + guestName
}
else
{
multiples = 0;
}
guest = prompt("Are there anymore guests?", "yes");
}
document.write(groomNameAccum);
document.write(brideNameAccum);
document.write("<p>Multiple Toasters by:<br>" + toasterAccum + "<br/>");
document.write("Multiple Silverware by:<br>" + silverwareAccum + "<br/>");
document.write("Multiple Stemware by:<br>" + stemwareAccum + "<br/>");
As I was saying, my teacher doesn't try to teach us the shortcuts and easy stuff, because it is a classroom of technical college students. I know there are easier ways to write it out, but I don't know how yet. Hes got his formula for success that always leads me looking for correct answers....

I can't figure out how to write this "if statement"

I need to have only the multiple gifts outputted by the names of people that gave the gift.
example: multiple toasters by: jack and jill
heres my code: thanks for the help. My loop works but not my ending if statement. confused...
<script type="text/javascript">
var guest = "yes"
var gift, side, yourName, kind, groomNameAccum, brideNameAccum;
var toaster, silverware, stemware, giftType;
var noGift = 0;
var groomCounter = 0;
var brideCounter = 0;
kind = parseInt(kind);
//initalizing loop
weddingGift = "yes"
//start loop
while (guest == "yes") {
side = prompt("Which side are you on? groom or bride?", "")
yourName = prompt("Whats your name?", "");
kind = prompt("What kind of gift?", "");
if (side == "groom") {
groomCounter = groomCounter + 1;
if (groomCounter == 1) {
groomNameAccum = "Groom side: <br>" + groomCounter + ". " + yourName + ": " + kind;
} else {
groomNameAccum = groomNameAccum + "<br>" + groomCounter + ". " + yourName + ": " + kind;
}
} else
if (side == "bride") {
brideCounter = brideCounter + 1;
if (brideCounter == 1) {
brideNameAccum = "<p>Bride side: <br>" + brideCounter + ". " + yourName + ": " + kind;
} else {
brideNameAccum = brideNameAccum + "<br>" + brideCounter + ". " + yourName + ": " + kind;
}
}
if (kind > 1) {
giftType = toaster + silverware + stemware;
} else {
giftType = noGift;
}
guest = prompt("Are there anymore guests?", "yes");
}
document.write(groomNameAccum);
document.write(brideNameAccum);
document.write("<p>Multiples Toasters by:<br>" + giftType + yourName + "<br/>");
document.write("Multiples Silverware by:<br>" + gift + "<br/>");
document.write("Multiples Stemware by:<br>" + gift);
// -->
</script>
If kind should be an integer then there should be parseInt before if (kind > 1) {
kind = parseInt(kind);
if (kind > 1) {
giftType = toaster + silverware + stemware;
} else {
giftType = noGift;
}
Or simply
kind = parseInt(prompt("What kind of gift?", ""));
Because promt returns a string or null.
Here in the popup for "What kind of gift?" we are entering some text for that. If you are doing parseInt(kind) but its value is text only. So in java script you are not able do any operation between two different types like (int and text). So the last if condition for if(kind > 1) is not executing.
Demo

Categories

Resources