Very basic dice game in Javascript - trying to log 'wins' variable - javascript

I'm trying to make a very basic dice game (new to Javascript). On the page load, the 'dice' is 'rolled' three times and the results are displayed, with a message to say whether you managed to roll a 6 or not. I'm trying to put in a permanant message about how many games have been won - problem is, if you look at my code below, the variable I'm using for this 'wins' is incremented each time there is a win, but it only actually displays two values: 0 if the user just lost, and 1 if it was a win. It never gets to a higher number no matter how many times the dice is rolled. Wondering if anyone has a solution/explanation?
Code:
console.log("Dice game. You have 3 tries to roll a 6 - go");
var rolls = 0;
var wins = 0;
function rollDice() {
var dice = Math.random();
if (dice <= .17) {
dice = 1;
}
else if (dice <= .33) {
dice = 2;
}
else if (dice <= .50) {
dice = 3;
}
else if (dice <= .67) {
dice = 4;
}
else if (dice <= .84) {
dice = 5;
}
else if (dice <= 1) {
dice = 6;
}
return dice;
}
function diceGame() {
do {
var dice = rollDice();
console.log(dice);
rolls++;
if (dice === 6) {
console.log("You won!");
wins++;
if (rolls === 1) {
console.log("It took " + rolls + " try");
}
else {
console.log("It took " + rolls + " tries");
}
break;
}
}
while (rolls <= 2);
if (dice !== 6) {
console.log("You lost");
}
}
diceGame();
console.log("Times won: " + wins);

The value 1 will never be hit, because:
The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1) that is, from 0 (inclusive) up to but not
including 1 (exclusive), which you can then scale to your desired
range. The implementation selects the initial seed to the random
number generation algorithm; it cannot be chosen or reset by the user.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

How are you running the code? Each time it runs, it resets the wins variable to 0. You need to call the function with a button, or something so it doesn't have to refresh the code block to run a second time.

Some improvements ;)
Call continue instead of break MDN continue
Change rollDice function Random number from range
anonymous function for create namespace
// namespace for our variables
(function(){
console.log("Dice game. You have 3 tries to roll a 6 - go");
var rolls = 0;
var wins = 0;
function rollDice() {
// simple random from range ( https://stackoverflow.com/a/1527820/2746472 )
return Math.floor(Math.random()*6)+1;
}
function diceGame() {
do {
var dice = rollDice();
console.log(dice);
rolls++;
if (dice === 6) {
console.log("You won!");
wins++;
if (rolls === 1) {
console.log("It took " + rolls + " try");
} else {
console.log("It took " + rolls + " tries");
}
continue; //instead of break!
}
} while (rolls <= 2);
if (dice !== 6) {
console.log("You lost");
}
}
diceGame();
console.log("Times won: " + wins);
})();

Your rollDice function can be simplified to 1 line.
var dice = Math.floor(Math.random() * 6) + 1;

It's because you have a break if you win so it exits the loop after the first win.

Related

How do I make a continuous loop for "confirm" alert in javascript

So I'm kinda new to Javascript, so sorry if this question sounds pretty basic. So I'm trying to make a guessing game where the computer guesses the number the user is thinking. I want to make it so that no matter how many times the user clicks "cancel" a new random number will show up until it the computer "guesses" the number the user was thinking. but i cant figure out how to make a loop out of that.
here's my code:
const guesser = () => {
let min = 0;
let max = 100;
let guess;
alert("Think of a number between 0 and 100");
while (min <= max) {
guess = Math.round((min + max) / 2);
if(confirm("is your number " + guess) == false){
if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false){
if (confirm("is your number " + Math.floor(Math.random() * guess)) == true){
alert("haha got your number!")
}
}
else if (confirm("is your number " + Math.floor((Math.random() * 50) + guess)) == true){
alert("haha got your number!")
}
}
else {
alert("haha got your number!")
}
return;
}
alert("I could not guess your number. I think you are cheating!");
};
You ask the user to tell you if their number is higher or lower than your guess, but you need to do something with that information. Specifically, if their number is greater than the current guess, increase the guess by bringing the minimum up to the current guess. If their number is less than the current guess, decrease the guess by bringing the maximum down to the current guess.
function main() {
var min = 0;
var max = 100;
alert(`Think of a number between ${min} and ${max}`);
while (min<max) {
var guess = Math.round((min + max) / 2);
if(confirm("is your number " + guess)) {
alert("haha got your number!")
return;
} else {
if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'")) {
min = guess+1;
} else {
max = guess-1;
}
}
}
alert("I could not guess your number. I think you are cheating!");
}
main();
Here is another way to achieve what you're looking for:
document.addEventListener("DOMContentLoaded", function(event) {
const guesser = () => {
let min = 0;
let max = 100;
let guess;
alert("Think of a number between 0 and 100");
while (min <= max) {
// initial guess
guess = Math.round((min + max) / 2);
if (confirm("is your number " + guess) == false) {
if (confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false) {
// number is lower than guess
max = guess;
} else {
// number is higer than guess
min = guess
}
} else {
alert("guessed your number!")
return
}
}
}
guesser();
});
<html>
<head>
</head>
<body>
Hello World!
</body>
</html>

How do I pick the closest integer to a random number?

I tried to make a small game were you have to guess which number the computer will pick. The pick that is closer to the number should win. Now I don't know how to write an if/switch that compares the values and chooses the one that is closer to the secretNumber.
This is my current code for evaluating who won. As you can see, I can only work with winners having the exact same number as the secret one.
if (user1Guess == user2Guess && user1Guess == secretGuess) {
console.log(`TIE!`)
} else if (user1Guess == secretNumber && user2Guess !== secretNumber){
console.log(`Player 1 wins!`)
} else if (user1Guess !== secretNumber && user2Guess == secretNumber)
{
console.log(`Player 2 wins!`)
};
Take the absolute value of the difference between each guess and the secretNumber. The closest guess will be the one whose difference is smaller:
const user1Diff = Math.abs(user1Guess - secretGuess);
const user2Diff = Math.abs(user2Guess - secretGuess);
if (user1Diff === user2Diff) {
console.log('Tie');
} else if (user1Diff > user2Diff) {
console.log('Player 2 wins');
} else {
console.log('Player 1 wins');
}
You canuser Math.abs() to get difference between user guesses and secretNumber to compare and decide who wins.
Hope this snippet helps:
const user1Guess = Math.floor(Math.random() * 100) + 1, // Random number between 1-100 to mock user input
user2Guess = Math.floor(Math.random() * 100) + 1, // Random number between 1-100 to mock user input
secretNumber = Math.floor(Math.random() * 100) + 1, // Random number between 1-100 to mock computer pick
user1Diff = Math.abs(user1Guess - secretNumber),
user2Diff = Math.abs(user2Guess - secretNumber);
if (user1Diff === user2Diff) {
console.log(`TIE!`)
} else if (user1Diff < user2Diff) {
console.log(`Player 1 wins!`)
} else if (user1Diff > user2Diff) {
console.log(`Player 2 wins!`)
} else {
console.log(`You broke the game, congrats!`)
}
Btw, you have a typo at first if statement: secretGuess needs to be secretNumber
Let's think about what it means for a guess to be closer.
If x is closer to n than y is. Then the distance from x to n must be less than the distance from y to n.
With numbers, the distance from x to n is abs(n - x), which is the absolute value of the difference. The absolute value is always non-negative number. For example, the absolute value of -3 is 3.
So if x is closer to n than y is, that must mean that the following is also true:
Math.abs(n - x) < Math.abs(n - y)
You can then use these in your if statement conditions.
const user1Distance = Math.abs(secretNumber - user1Guess);
const user2Distance = Math.abs(secretNumber - user2Guess);
if (user1Distance === user2Distance) {
console.log("TIE!");
} else if (user1Distance < user2Distance) {
console.log("Player 1 wins!");
} else {
console.log("Player 2 wins!");
}

How to run a program forever?

I've got got a stupid question, can you help me please?
I want this program to run and run and run. At this moment after each try I have to refresh page to play again and it sucks.
"8. Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number. If the user input matches with guess number, the program will display a message "Good Work" otherwise display a message "Not matched"."
Here's what I've got:
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Looser! The number was " + randomNumber);
};
Put it in an endless loop:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
but, I wouldn't do that. I'd offer a way to get out:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (!guessNumber) { // ***
break; // ***
} // ***
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
If the user presses Esc at the prompt, guessNumber will be "" or null (depending on the browser), both of which are falsy, so you'll break out of the loop.
Side note: "Loser" has only one "o" in it, and control-flow statements with attached blocks don't have ; after the block.
Put all of your code into the while (true) loop.
just make an infinite loop
var run = true
while (run)
{
console.log('foobar');
}
never set run as false and your loop will never stop

want to put javascript code in while loop so that when cphealth or player health is <= 0 the game stops

i am wanting to put a while loop somewhere so the games stops when either you or the computer have 0 or less health and display a message after that saying somebody won but no matter how i try or where i put them i can never seem to get a while loop to work. Please help me :)
$(document).ready(function() {
var health = 100;
var cphealth = 100;
var lightAttacks = -20;
var block = 10;
var Ties = 0;
function randomGen() {
var max = 3;
var min = 1;
var answer = Math.floor(Math.random() * (max - min + 1)) + min;
return answer;
//sets up the random number generator
}
var name = "";
var userChoice = "";
var compChoice = 99;
$("#lightAttack").click(function() {
userChoice = "lightAttack"
compChoice = randomGen();
whoWon(userChoice, compChoice);
});
$("#block").click(function() {
userChoice = "block"
compChoice = randomGen();
whoWon(userChoice, compChoice);
});
$("#heal").click(function() {
userChoice = "heal"
compChoice = randomGen();
whoWon(userChoice, compChoice);
//sets up the random number generator
});
function whoWon(user, comp) {
var winnerMessage = "ERROR";
if (user == 'lightAttack') {
if (comp == 1) { //developer says 1 = attack back
winnerMessage = "Computer attacked back";
(health = health + lightAttacks) && (cphealth = cphealth + lightAttacks)
} else if (comp == 2) { //developer says 2 = block next attack
winnerMessage = "Computer blocked your attack and reflected some damage";
health = health - 5
} else { //developer says 3 = heal and its just else 1 or 2 ot must be 3
winnerMessage = "Computer heals back part of your attack damage";
cphealth = cphealth - 10
}
}
if (user == 'block') {
if (comp == 1) { //developer says 1 = lightAttack
winnerMessage = "You blocked the computer attack and reflected some damage";
cphealth = cphealth - 5
} else if (comp == 2) { //developer says 2 = block
winnerMessage = "Nothing happened because you both blocked";
health = health + 0
} else { //developer says 3 = heal and if its not 1 or 2 ot must be 3
winnerMessage = "Computer heals 10 health";
cphealth = cphealth + 10
}
//sets up the results for if the user picks block
}
if (user == 'heal') {
if (comp == 1) { //developer says 1 = lightAttack
winnerMessage = "Computer attacked";
health = health - 10
} else if (comp == 2) { //developer says 2 = block
winnerMessage = "Computer blocked";
health = health + 10
} else { //developer says 3 = heal and if its not 1 or 2 ot must be 3
winnerMessage = "You both picked heal";
health = health + 10;
cphealth = cphealth + 10;
}
}
if (comphealth <= 0) {
alert("You Win!")
}
document.getElementById("result").innerHTML = winnerMessage;
document.getElementById("myhealth").innerHTML = health;
document.getElementById("comphealth").innerHTML = cphealth;
}
});
If you try using a while loop in Javascript for this your program will get stuck in the while loop forever. Javascript has a single thread of execution so there is no way to run your while loop in parallel with the rest of the game.
One thing you could consider doing instead is to structure your game logic in "turns". Every turn you apply changes to the game state (player moves around a bit, takes damage, deals damage, etc) and at the end of the turn you check to see if their health dropped to zero.

Guess a number game, score counter giving incorrect result

I am making a simple 1 - 10 guess the number game with Javascript.
It can be viewed here Guessing game
To add up score i have a var score = 4 which de-increments each time the number guessed (with a for loop which is smaller than 5) incorrect. I += to var tally and display tally as score.
My problem is score always equals 0, and therefore does not add anything to tally, I am struggling to find a solution.
My javascript is:
var tally;
function play() {
var compNum = (Math.random() * 10).toFixed(0);
var score = 4;
for (var i = 0; i < 4; i++) {
if (i == 0) {
var userNum = prompt("Enter a number between 1 and 10");
} else {
if (userNum < compNum) {
userNum = prompt("Guess higher, you have " + (4 - i) + " turns left ", userNum);
} else if (userNum > compNum) {
userNum = prompt("Guess lower you have " + (4 - i) + " turns left ", userNum);
}
}
score--;
}
tally += score;
$("#score").html("score: " + tally);
if (i >= 3 && userNum != compNum) {
var again = confirm("Sorry you lost. The number was: " + compNum + " Play again?");
} else if (userNum == compNum) {
again = confirm("Well done! play again?");
i <= 5;
}
if (again) {
play();
}
if (userNum == "") {
i <= 5;
}
}
HTML:
<button onclick="play()">PLAY</button>
<div id="score"></div>
Your help is really appreciated
You should check whether the number entered by the use is equal to the random one and if that is the case exit form the for loop.
With your code the loop runs the whole 4 times,
In your loop, you need to check if the user has the right answer and exit the loop if they do.
for (var i = 0; i < 4; i++) {
if (i == 0) {
var userNum = +prompt("Enter a number between 1 and 10");
} else {
if (userNum < compNum) {
userNum = prompt("Guess higher, you have " + (4 - i) + " turns left ", userNum);
} else if (userNum > compNum) {
userNum = prompt("Guess lower you have " + (4 - i) + " turns left ", userNum);
}
}
if (userNum === compNum) {
// they guessed right, so exit the loop
break;
}
score--;
}
In addition, I'd check to see if isNaN(userNum) to check your user actually entered a number. It's up to you if you want to give them another chance if they don't.

Categories