i need to make a dice rolling program that rolls dice and says who won if it is a tie it rolls again and after each win you earn a point first to 5 wins the game whenever i run mine it uses the same numbers over and over again because it only generated the once how can i fix this and what else do i need to do after this issue to finish the program, thanks for the help!
<script>
var comp1 = Math.floor((Math.random()*6) + 1);
var comp2 = Math.floor((Math.random()*6) + 1);
var you1 = Math.floor((Math.random()*6) + 1);
var you2 = Math.floor((Math.random()*6) + 1);
var counter = 1;
var youPoints = 0;
var mePoints = 0;
while(counter < 6)
{{
alert("Let's shake some dice!")
alert("your turn to roll \n\n you shook a " + you1 + " and a " + you2 + ", so you have " + (you1 + you2));
alert("my turn to roll \n\n I shook a " + comp1 + " and a " + comp2 + ", so I have " + (comp1 + comp2));
counter++
var you = you1 + you2;
var me = comp1 + comp2;
if(you > me)
{
alert("you win " + you + " to " + me);
youPoints++
}
if (me > you)
{
alert("I win " + me + " to " + you);
mePoints++
}
}}
</script>
You're initializing your random variables (you1, you2) outside the while loop.
It's being initialized only once and hence producing the same number every time.
Bring it inside the loop, and that might fix it!
Move the code the generates the random numbers to inside of the loop because, right now, they only generate once... before the loop even starts.
Also, do yourself a favor and use a for counting loop, rather than a while, because while loops are easily misconfigured to cause infinite loops to occur.
var youPoints = 0;
var mePoints = 0;
for(var counter = 1; counter < 6; counter++){
// The code that generates the random numbers has to be in the loop
// in order for new randoms to be generated upon each loop iteration
var comp1 = Math.floor((Math.random()*6) + 1);
var comp2 = Math.floor((Math.random()*6) + 1);
var you1 = Math.floor((Math.random()*6) + 1);
var you2 = Math.floor((Math.random()*6) + 1);
alert("Let's shake some dice!")
alert("your turn to roll \n\n you shook a " + you1 + " and a " + you2 + ", so you have " + (you1 + you2));
alert("my turn to roll \n\n I shook a " + comp1 + " and a " + comp2 + ", so I have " + (comp1 + comp2));
var you = you1 + you2;
var me = comp1 + comp2;
// Don't make two separate if statements. Use one with an else if
if(you > me) {
alert("you win " + you + " to " + me);
youPoints++
} else if (me > you) {
alert("I win " + me + " to " + you);
mePoints++
}
}
Here you go, this should be a complete working example.
Note: I replaced alert() for console.log() so we can see the output here in the console and without popups, but it will work either way.
var compPoints = 0;
var youPoints = 0;
var winnerOfFive = false;
function rollTheDice() {
return Math.floor((Math.random()*6) + 1);
}
function rollAllDice() {
let you1 = rollTheDice();
let you2 = rollTheDice();
let comp1 = rollTheDice();
let comp2 = rollTheDice();
console.log("your turn to roll \n\n you shook a " + you1 + " and a " + you2 + ", so you have " + (you1 + you2));
console.log("my turn to roll \n\n I shook a " + comp1 + " and a " + comp2 + ", so I have " + (comp1 + comp2));
var you = you1 + you2;
var me = comp1 + comp2;
if(you > me) {
console.log("you win " + you + " to " + me);
youPoints++;
} else if(me > you) {
console.log("I win " + me + " to " + you);
compPoints++;
} else {
console.log("It was a tie, no one wins. Re-rolling...");
rollAllDice();
}
}
function startGame() {
while( !winnerOfFive ) {
console.log("Let's shake some dice!")
rollAllDice();
if(compPoints == 5) {
console.log("Comp is first to 5 games and wins " + compPoints + " to " + youPoints);
winnerOfFive = true;
} else if (youPoints == 5) {
console.log("You are first to 5 games and win " + youPoints + " to " + compPoints);
winnerOfFive = true;
}
}
}
// Start the game like this
startGame();
Related
I want to start off by saying I have no idea what I am doing with HTML and Javascript but I am trying to learn. What I am creating will not be hosted by any server , it is more of a HTML web form(I think that is what i would call it) for employees to fill out and create a standardized email. I have 97% of it working but need a little help with the last part. Below is the Javascript that works:
function populateEmail() {
let bl = document.getElementById("blurb").value;
let a = document.getElementById("reg").value;
let b = document.getElementById("lvl").value;
let c = document.getElementById("node").value;
let i = document.getElementById("cust").value;
let d = document.getElementById("rea").value;
let e = document.getElementById("ma").value;
let f = document.getElementById("start_dt").value.replace("T", " ");
let g = document.getElementById("poc").value;
let h = document.getElementById("appr").value;
let m_to = "DL-ListOne; DL-ListTwo; DL-ListThree"
let m_cc = "DL-ListFour; DL-ListFive;"
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
let yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
let notify = document.getElementById("notify_lvl").value;
if (notify == "Initial"){
let deap = "Activation ";
}
else if (notify == "Update"){
let deap = "Update ";
}
else{
let deap = "De-Activation ";
}
document.location.href = "mailto:" + encodeURIComponent(m_to) + "?cc=" + encodeURIComponent(m_cc)
+ " &subject=DEAP " + encodeURIComponent(b) + ": Any Region " + today
+ " "
+ "&body="
+ "%0D%0A%0D%0A"
+ encodeURIComponent(bl) + "%0D%0A%0D%0A"
+ "Name: " + encodeURIComponent(a) + "%0D%0A"
+ "Activation – (" + encodeURIComponent(b)
+ "Current Impact = " + encodeURIComponent(c) + " modules, " + encodeURIComponent(i) + " customers) %0D%0A"
+ "Reason: " + encodeURIComponent(d) + "%0D%0A"
+ "Event Geographical Area: " + encodeURIComponent(e) + "%0D%0A"
+ "Event Start: " + encodeURIComponent(f) + "%0D%0A"
+ "POC: " + encodeURIComponent(g) + "%0D%0A"
+ "Approved by: " + encodeURIComponent(h) + "%0D%0A"
}
Now when I try and add the Variable deap to the subject line it stops creating the email. Here are the different ways I have tried to add it.
+ " &subject=DEAP " + deap + encodeURIComponent(b) + ": NE Region " + today
+ " &subject=DEAP " + encodeURIComponent(deap) + encodeURIComponent(b) + ": NE Region " + today
then I thought that maybe I had to add some text or space in there to have it take affect so I tried adding + " " + after the variable deap
I am trying to keep the post to a minimum, if you need my ugly looking HTML I will be happy to post it
but I am still trying to figure out how to load div from Javascript so my code isn't DRY.
Thank you in advance for your time
It's because you're declaring deap inside your if statements:
if ('notify' == "Initial") {
let deap = "Activation ";
} else if ('notify' == "Update") {
let deap = "Update ";
} else {
let deap = "De-Activation ";
}
console.log(deap);
If you declare it outside and reassign it inside your if blocks, it should work:
let deap;
if ('notify' == "Initial") {
deap = "Activation ";
} else if ('notify' == "Update") {
deap = "Update ";
} else {
deap = "De-Activation ";
}
console.log(deap)
I couldn't have the variables add up as total and neither could I make them multiply inside the var.
What am I doing wrong?
var order;
var amountsoda;
var amountbeer;
var amountwine;
var total = amountsoda + amountbeer + amountwine;
while (order != "stop") {
order = prompt("What order would you like to add? \n\n soda 2 dollar \n beer 5 dollar \n wine 10 dollar")
if (order == "soda") {
amountsoda = prompt("How much " + order + " would you like to add.");
} else if (order == "beer") {
amountbeer = prompt("How much " + order + " would you like to add.");
} else if (order == "wine") {
amountwine = prompt("How much " + order + " would you like to add.");
}
}
document.write("soda: " + amountsoda + " x 2 =" + amountsoda * 2);
document.write("<br>")
document.write("beer: " + amountbeer + " x 5 =" + amountbeer * 5);
document.write("<br>")
document.write("wine: " + amountwine + " x 10 =" + amountwine * 10);
document.write("<br>")
document.write("total: " + total);
You have to initialize the product-amounts and the total with '0'
You need to add up the total inside the while-loop depending on the product chosen
var order;
var amountsoda = 0;
var amountbeer = 0;
var amountwine = 0;
var total = 0
while (order != "stop"){
order = prompt("What order would you like to add? \n\n soda 2 dollar \n beer 5 dollar \n wine 10 dollar")
if (order == "soda" ){
amountsoda = prompt("How much " + order + " would you like to add.");
total = total + amountsoda * 2;
}
else if (order == "beer"){
amountbeer = prompt("How much " + order + " would you like to add.");
total = total + amountbeer * 5;
}
else if (order == "wine"){
amountwine = prompt("How much " + order + " would you like to add.");
total = total + amountwine * 10;
}
}
document.write ("soda: " + amountsoda + " x 2 =" + amountsoda*2);
document.write ("<br>")
document.write ("beer: " + amountbeer + " x 5 =" + amountbeer*5);
document.write ("<br>")
document.write ("wine: " + amountwine + " x 10 =" + amountwine*10);
document.write ("<br>")
document.write ("total: " + total);
I'm trying to use questionFunction() again once the user clicks a button which calls myFunction but I'm getting an error 'questionFunction is not defined'
window.onload = function questionFunction() {
var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}
function myFunction() {
return questionFunction();
}
I wan't the text to be changed on load and also again once the user clicks to call myFunction()
You're getting that error because a function expression doesn't add an identifier for the function to the scope where it appears (only function declarations do that).
The simple answer is to make that a function declaration instead:
function questionFunction() {
var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}
window.onload = questionFunction;
Since that adds an identifier for the function, now you can call it the way you do in myFunction.
Just declare questionFuntion, and reuse this function where you want
function questionFunction() {
var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}
window.onload = questionFunction;
function myFunction() {
return questionFunction();
}
function questionFunction() {
var questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
}
window.onload = questionFunction;
function myFunction() {
return questionFunction();
}
This will work.
You're getting error because of wrong function scope.
You can read about it here:
https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
I am trying to make so when the looping of 100 hits on the character exits the loop when the life dice rolls to 0. How it currently is is all gets looped 100 times. I am not quite sure how I need to go about solving this, any tips would be helpful. My code is below.
function addChar(fname, lname, speed, agility, wep, outfit, mood) {
this.fname = fname;
this.lname = lname;
this.speed = speed;
this.agility = agility;
this.wep = wep;
this.outfit = outfit;
this.mood = mood;
this.special = function(specialMove) {
specialMove();
}
this.jumpKick = function() {
var jmpkckTimes = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write("He jumpkicks " + jmpkckTimes + " times. ");
if (jmpkckTimes > 70) {
document.write("He enters rage mode! ");
} else {
document.write("He does not have enough kicks for rage mode. ");
}
}
this.hits = function() {
var allHits = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write(" He gets attacked for " + allHits + " HP.");
}
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
if (life > 0) {
document.write(" The life dice rolls a " + life + ". You have survived! For now...");
} else {
document.write(" The life dice rolls a " + life + ". You have died!");
}
}
}
var myChar = new addChar('Johhny', 'Kicker', 10, 7, 'Ancient Greataxe', 'Barrows', 'angry');
document.write(myChar.fname + " " + myChar.lname + "'s speed is " + myChar.speed + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s agility is " + myChar.agility + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s weapon of choice is: " + myChar.wep + "<br>");
document.write(myChar.fname + " " + myChar.lname + " feels " + myChar.mood + "<br>");
document.write(myChar.fname + " " + myChar.lname + " attempts his special: ");
myChar.special(myChar.jumpKick)
for (i = 1; i < 101; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
function myOutfit() {
document.getElementById("demo").innerHTML = ("He is wearing " + myChar.outfit)
}
var start = Date.now();
var response = prompt("Do you think my character has what it takes?", "");
var end = Date.now();
var elapsed = (end - start) / 1000;
console.log("You took " + elapsed + " seconds" + " to type: " + response);
You need to have a way to communicate outside of the object, of what is happening inside the object.
For example, when something happens in a function, like lifes() or hits(), you should assign a value to a variable on the object to retain state. That way you can access the state from the for loop.
Example:
this.isAlive = true; // starting condition
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
this.isAlive = (life > 0);
if (this.alive) {
document.write('you survived');
} else {
document.write('you died');
}
Now in your for loop, you can access isAlive:
// loop until 100 attempts or you die, which ever comes first
for (i = 1; i < 101 && myChar.isAlive; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
well in general you can break out of foor loops aswell as prevent further execution of a foor loop and continue the next iteration:
for (var i = 0; i < 10; i++) {
if (i == 4) continue;
if (i == 8) break;
console.log(i);
}
this will basically print: 0, 1, 2, 3, 5, 6, 7
(as you can see it kind of skipped 4)
(it will also work in while / do while loops)
so in your case you could check if the return value of one of your functions is true or false or do some other kind of conditional checking in order to break out of the loop.
or similar to how Rob Brander wrote in his answer:
var maxTurns = 100;
var turns = 0;
while (myChar.isAlive && ++turns <= maxTurns) {
myChar.hits();
myChar.lifes();
}
console.log("character is: " + myChar.isAlive ? "alive" : "dead");
console.log("after: " + turns + " turns.");
I am making a basic game with popup boxes.
My problem is that if you look at the goblinAttack function it will repeat till the goblin is dead but the damage is random.
For example, I hit the goblin 6 damage every time until it dies instead of it being a random number between 1 and 25 and the goblin does 4 damage on me every time it hits. Its boring. I wanted it to be random each hit but repeating the function seems to not give a random number each time.
//VARIABLES
var dmgMultiply = Math.floor(Math.random() * 10 + 1);
var dmg = 10;
var armour = 0;
var hp = 100;
//ENEMY VARIABLES
var dmgGoblin = Math.floor(Math.random() * 10 + 1);
var goblinHP = 100;
//ARRAYS
var choiceArray = ["Type 'sword' equip your sword.",
"Type 'run' if you're scared.",
"Type 'stats' to see your stats."];
var answerArray = ["sword", "run", "stats"];
var outcomeArrayOne = ["You equip your sword.",
"You run away. Game Over."];
var outcomeArrayTwo = ["Sword Equipped."]
//GAME CHOICE
function choice(a, b, c, x, y, z, aa, bb)
{
var answer = prompt(a + "\n" + b + "\n" + c);
if(answer == x)
{
alert(aa);
swordEquipped(outcomeArrayTwo[0]);
}
if(answer == y)
{
alert(bb);
}
if(answer == z)
{
displayStats();
}
}
//EQUIPPED SWORD
function swordEquipped(a)
{
dmg = 25;
dmgMultiply = Math.floor(Math.random() * 25 + 1);
alert(a + "\n" + "DMG : " + dmg);
goblinCombatStart("goblin");
}
//GOBLIN COMBAT START
function goblinCombatStart(g)
{
alert("A wild " + g + " appears!" + "\n" + "The " + g + " has 100 HP!");
goblinAttack("goblin")
}
function goblinAttack(g)
{
alert("The " + g + " swings his axe at you!" + "\n" + "The " + g + " does " + dmgGoblin + " damage to you!");
hp -= dmgGoblin;
var attack = prompt("Type 'attack' to swing your sword at the " + g + "\n" + "HP : " + hp);
if(attack == "attack")
{
alert("You swing your sword at the " + g + "\n" + "You did " + dmgMultiply + " to the " + g);
goblinHP -= dmgMultiply;
alert("The " + g + " is on " + goblinHP + "HP");
if(goblinHP < 0)
{
goblinDead();
}
if(goblinHP > 0)
{
goblinAttack("goblin");
}
}
else
{
alert("You dropped your sword an shouted " + "'" + attack + "'" + " in the goblins face. It wasn't very effective and the goblin choppped your head off");
}
}
function goblinDead()
{
alert("You have slain the puny goblin with only a few scratches!");
}
//GAME START
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
//STATISTICS
function displayStats()
{
var statCheck = confirm("HP : " + hp + "\n" +
"ARMOUR : " + armour + "\n" +
"DMG : " + dmg + "\n" +
"Press OK to continue");
if(statCheck == true)
{
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
}
}
Instead of computing the random damage value only once at the beginning of your script, compute them whenever you need them. That would probably be in your attack function.
Maybe you are misunderstand something here: Math.random doesn't return some special magical value which changes every time it's read. It returns a number and that number doesn't change.
If you want multiple random values, you have to call Math.random multiple times. If you want a different random value whenever the goblin attacks, you have to call Math.random when it attacks.
The problem here is that you're initializing your variables at the beginning as random.
That means that, on every move, it will use the same random number that was generated at the beginning.
If you want it to be random for each time, you have to call Math.random() on every move.
As it stands, dmgMultiply and dmgGoblin are computed randomly once and use the same value on each turn, so you end up getting the same amount of damage taken and dealt each time.
Declare your variables at the beginning:
var dmgMultiply;
var dmgGoblin;
Then, set them to a random number within your attack function so that it computes a random number each turn:
function goblinAttack(g)
{
dmgMultiply = Math.floor(Math.random() * 10 + 1);
dmgGoblin = Math.floor(Math.random() * 10 + 1);
...
}
Demo