Random number generator and if then statements - javascript

This code is supposed prompt for two player names and generate a random number between 1 and 6 for each player. It is then supposed to compare those two numbers and provide the output of which player has the higher number or display tie if there is a tie. Sometimes this works and sometimes it does the opposite other times it says both numbers match when they don't.
Anyone have any ideas for me?
var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "
main()
function main()
{
do {
getNames()
rollDice()
displayResults()
endProgram()
}
while (end == "yes")
}
function getNames()
{
playerOne = prompt("Please enter the name of Player One: ")
playerTwo = prompt("Please enter the name of Player Two: ")
}
function rollDice()
{
p1Number = Math.floor((Math.random()*6)+1)
p2Number = Math.floor((Math.random()*6)+1)
if (p1Number > p2Number)
{
return playerOne
}
else if (p1Number < p2Number)
{
return playerTwo
}
else
{
return "Sorry no winner, there was a tie"
}
}
function displayResults()
{
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
window.alert("The winner is! " + rollDice())
}
function endProgram()
{
end = prompt("Do you want to play again? Enter yes or no")
if (end == "no")
window.alert("Thank you for playing");
else if (end == "yes")
return end;
}

window.alert("The winner is! " + rollDice())
This line calls rollDice again for a 2nd time. You display the results of the first call then you re-roll and display the return value of the 2nd call (which may be different).
// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
// recall rollDice
window.alert("The winner is! " + rollDice())

In displayResults(), you are showing the values of p1Number and p2Number before assigning values to them (since that happens within rollDice()).
So your program is working, but your diagnostic output is misleading you.

Related

If-else statment not working after else is added

I am trying to write a search fnction for an address book which loops through the array of contacts and shows them in a popup. It first worked fine finding and showing the found contacts. After adding the else statement, only "none found" runs. I've tried switching the order and negating the first statement, but that does not work.
$(document).ready(function(){
newSearch.click(function(){
const inputValue = $('#searchcontacts').val();
for(let i = 0; i < contactList.length; i++){
if(inputValue.toUpperCase() === contactList[i].firstName.toUpperCase()){
resultsContent.text(contactList[i].firstName +
" " + contactList[i].lastName +
" " + contactList[i].phoneNumber +
" " + contactList[i].addressText);
} else {
}
};
resultsContent.text('None found')
});
});
You have always set the resultsContent.text('None found') after for loop is executed.
So even if a contact found and that contact is set to the resultsContent, it will be replaced by the resultsContent.text('None found') line
Following code snippet will do the job for you. But I have seen another issue with this code that only the last found contact will be shown in the resultsContent element since you have not accumulated the found results. If you need to show all the contacts you need to accumulate all of them and show
newSearch.click(function(){
const inputValue = $('#searchcontacts').val();
var hasContacts = false;
for(let i = 0; i < contactList.length; i++){
if(inputValue.toUpperCase() === contactList[i].firstName.toUpperCase()){
resultsContent.text(contactList[i].firstName +
" " + contactList[i].lastName +
" " + contactList[i].phoneNumber +
" " + contactList[i].addressText);
hasContacts = true;
} else {
}
};
if( !hasContacts) {
resultsContent.text('None found');
}
});

Add a refunding function (and a warning that there are no stocks left) in my vending machine project in Javascript

The stock number decreases by one every time a user chooses and buys a soda.
However, if the user keeps on buying on the same code ("A1" in this case) but there are no stocks left, money still subtracts by a certain amount.
How do I warn the user that there are no more stocks left for "A1" and how do I let the user know their money will be refunded?
//Soda Choice with If-Then Statements
sodaChoice.addEventListener("click", function() {
var sodaChoice = window.prompt("Select your code.");
console.log(sodaChoice);
if (sodaChoice == "A1") {
window.alert("You selected Coca-Cola.");
window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
window.alert(sodaPrice[0] <= $money ? "You have enough. Have a nice day." : "You don't have enough. Try again.");
$money -= sodaPrice[0].toFixed(2);
console.log("You now have " + $money.toFixed(2));
while (stockCocaCola !== 0) {
stockCocaCola--;
break; //The break function stops this while loop from rapidly subtracting stockCocaCola by 1 until stockCocaCola reaches 0.
}
console.log("Stock left for Coca-Cola: " + stockCocaCola);
}
Instead of refunding, I would deduct money only if the stock is available, else give alert message. (Removed while loop too as it's not required)
//Soda Choice with If-Then Statements
sodaChoice.addEventListener("click", function() {
var sodaChoice = window.prompt("Select your code.");
console.log(sodaChoice);
if (sodaChoice == "A1") {
window.alert("You selected Coca-Cola.");
window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
window.alert(sodaPrice[0] <= $money ? "You have enough. Have a nice day." : "You don't have enough. Try again.");
if(stockCocaCola > 0) {
$money -= sodaPrice[0].toFixed(2);
console.log("You now have " + $money.toFixed(2));
stockCocaCola--;
}
else{
window.alert("No Stock available for " + sodaChoice );
}
console.log("Stock left for Coca-Cola: " + stockCocaCola);
}

Error in declaring array JavaScript?

Working through an intro JS coursera course. I'm making a simple color guessing game. I've inserted a few alerts at the beginning for troubleshooting, but I can't get this program to get reach the alert("test1"); line in my playGame, which is loading immediately through the body element. Any ideas what I'm doing wrong? I seem to be declaring it just fine...
<!DOCTYPE html>
<html>
<body onload="playGame()">
<p>Welcome to my color guessing game</p>
<script language = "JavaScript">
function inArray(needle, haystack){
for (var i = 0; i <haystack.length(); i++){
if (needle === haystack[i]){
return true;
}
}
return false;
}
function changeBackground(color){
document.body.style.background = color;
}
function playGame(){
var correct = false;
alert("Correct status is: " + correct);
var colorArray = ["cyan", "gold", "green", "gray", "magenta", "blue", "red", "orange", "yellow", "white"];
alert("test1");
for (var i = 0; i < colorArray.length(); i++){
alert("for " + i + " the color is " + colorArray[i]);
}
colorArray = colorArray.sort();
alert("answer index is " + answerIndex);
alert("color array length is " + colorArray.length());
var answerIndex = Math.floor(Math.random()*colorArray.length());
alert("the resulting color from the color array is: " + answerColor);
var answerColor = colorArray[answerIndex];
alert("The correct color is " + answerColor);
var answerList = colorArray.join(", ");
var guessCount = 0;
while(!correct){
var colorGuess = prompt("Welcome to my guessing game! The colors available for your choosing are: " + "\n\n" + answerList + "\n\n" + "Which color am I thinking of?");
guessCount++;
if (!inArray(colorGuess, colorArray)){
alert("Your guess wasn't one of the selections that was available or I otherwise don't recognize it." + "\n\n" + "Please try again!");
}
else{
if (colorArray.indexOf(colorGuess)<color.indexOf(answerColor)){
alert("Your guess was alphabetically before the correct color! Try again.");
}
else if (colorARray.indexOf(colorguess)>color.indexOf(answerColor)){
alert("Your guess was alphabetically after the correct color! Try again.");
}
else{
alert("Your guess is correct!");
correct = true;
changeBackground(answerColor);
}
}
}
alert("Great job!" + "\n\n" + "You took " + guessCount + " guesses to get the correct answer!");
}
</script>
</body>
</html>
I've just tested your code.
alert("answer index is " + answerIndex);
alert("color array length is " + colorArray.length());
var answerIndex = Math.floor(Math.random()*colorArray.length());
alert("the resulting color from the color array is: " + answerColor);
var answerColor = colorArray[answerIndex];
alert("The correct color is " + answerColor);
Here you're trying to alert the variable answerIndex, before you declare it.
In JS length is a property which returns the number of elements in an array. MDN Array Length.
In colorArray.length() replace length() by length.

not getting to my else in jquery javascript

net mvc application and I am trying to do some validation when someone clicks a button. Here is the code.
function productVerify() {
var intQty = $("#txtQty").val();
var strItemName = $("#item_Name").val();
var strItemDescription = $("#item_Description").val();
var intItemID = $("#item_ID").val();
var intItemPrice = $("#item_Price").val();
var strImgUrl = $("item_ImgUrl").val();
var intQty = $("#txtQty").val();
if (intQty < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
}
else {
//post into cart
alert(strItemName + " " + strItemDescription + " " + intItemID + " " + intItemPrice + " " + strImgUrl + " " + intQty + " " + "I got this far.....! good job")
}
}
this works in jsfiddle but for some reason it does not fully work in my mvc application. it does work on the first if because if I put a 0 in my text box I get the first alert, but nothing happens on the else inside my mvc application. This one part seems so easy, but it is killing me any help would be appreciated.
make sure you using a number in your if statement
//if !num
if (parseInt(intQty) == NaN) {
alert("Please enter a number");
return false;
} else {
//if < 1
if (parseInt(intQty) < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
//if >= 1
} else {
//do something
}
}

setInterval going too fast [duplicate]

This question already has an answer here:
Why is my window.setInterval function overlapping itself in the DOM when called multiple times?
(1 answer)
Closed 1 year ago.
I'm new to JS, and decided to start of learning by a making a small game. I am using a setInterval to automate the enemy's attack. For their first attack the interval is correct, but after the second attack it speeds up to attacking almost three times, or more, a second. I'm also having trouble stopping the interval once either the player's or the enemy's health reaches 0.
here is pretty much all the code pertaining my problem. The whole code can be found here
function deadFunct(){
if(yourHealth <= 0){
window.alert("You dead");
clearInterval(fightAuto);
clearInterval(deadAuto);
}
if(enemyHealth <= 0){
window.alert("The enemy is dead");
clearInterval(fightAuto);
clearInterval(deadAuto);
}
}
function nextFunct(){
document.getElementById("nextBtn").disabled=true;
document.getElementById("swordBtn").disabled=false;
document.getElementById("bowBtn").disabled=false;
document.getElementById("hamBtn").disabled=false;
var a=Math.random();
if(a>0.66){
enemy="Knight";
eAcc=.75;
eDmg=5;
eAttackSpeed=2000;
y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
document.getElementById("attack").innerHTML=y;
}else if(a>0.33){
enemy="Archer";
eAcc=.80;
eDmg=3;
eAttackSpeed=1750;
y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
document.getElementById("attack").innerHTML=y;
}else{
enemy="Berserker";
eAcc=.66;
eDmg=7;
eAttackSpeed=2500;
y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
document.getElementById("attack").innerHTML=y;
}
}
function enemyAttackFunct(){
for(var i=0; i<1;i++){
if(enemy == "Archer"){
fightAuto = setInterval(function(){aAttackFunct()},eAttackSpeed);
document.getElementById("test").innerHTML=eAttackSpeed;
}else if(enemy == "Knight"){
fightAuto = setInterval(function(){kAttackFunct()},eAttackSpeed);
document.getElementById("test").innerHTML=eAttackSpeed;
}else{
fightAuto = setInterval(function(){bAttackFunct()},eAttackSpeed);
document.getElementById("test").innerHTML=eAttackSpeed;
}
}
}
You keep calling 'setInterval' again again. Each call is running in parallel.
If you have more than one warrior peer type (archer, knight, etc), create an array that will have a separate set interval for each.
If, as seems the case, you only have one and they play at random each turn, add clearInterval before every setInterval
you should never use setInterval for animations!
Just use requestAnimationFrame instead!
https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
http://css-tricks.com/using-requestanimationframe/

Categories