Here is the description of the code i need to write:
Deisgn the logic for a game that simulates rolling two dice by generating two numbers between 1 and 6 inclusive (one number for each die).
The player will choose a number between 2 and 12 (the lowest and highest totals possible for two dice).
The program will then roll the dice three times
-- if the user's guess comes up in one of the rolls the user wins.
-- If the guess does not come up computer wins.
We have not started arrays yet but I am to use a for loop and if else.
It is my if else statement that is not working.
Every roll comes up you lose.
Here is the code:
randNumber = prompt("Please enter a number between 2 and 12");
while (randNumber <= 1 || randNumber >= 13) {
alert("Input was incorrect, try again.");
randNumber = prompt("Please enter a number between 2 and 12");
}
for (var i = 0; i < 3; i++) {
computerRoll = 1 + Math.ceil(Math.random() * 11);
document.write(computerRoll + "<br>");
}
function rollDice() {
var computerRoll = rollDice(2, 12);
}
var computerRoll = rollDice;
if (randNumber == computerRoll) {
document.write("You win.");
} else {
document.write("You lose.");
}
if the computer is trying to roll 2 dice, you need 2 random numbers, both converted to range 0 to 5, and then added, and adding 2. (Try making a function to roll one die, and then calling it twice.)
The rolldice() function does not return a value. And it's computerRoll is independent of the outer computerRoll.
the outer computerRoll is set to a function, which is never equal to a number. This is why you get only losses.
if my translator is correct :
let randNumber, computerRoll
do
{
if (randNumber != undefined) {
alert('Input was incorrect, try again.')
}
randNumber = parseInt(prompt('Please enter a number between 2 and 12')) // bce promt value is string
}
while (!(1<randNumber && randNumber<13)) // to also process NaN values (not a number)
document.write('randNumber -> '+ randNumber + '<br>' )
for (let i=0;i<3;i++)
{
computerRoll = Math.floor(Math.random() *6) +1 // first dice
computerRoll += Math.floor(Math.random() *6) +1 // second dice
document.write('computerRoll -> '+ computerRoll + '<br>' )
if ( computerRoll === randNumber ) break
}
if (randNumber === computerRoll) {
document.write('You win.')
}
else {
document.write('You lose.')
}
Related
hello i am very new to coding and i have no clue on how this codes does not work.
what i need to do is make a random number(the test value is 20) from 0 to 100 and store it in a value then the user must guess it if its higher then the random value the code will say to high and if too lower then it will say to low and if they type -1 or get the number right the code will then break and stop the loop
the problem: i dont know how to loop the code back to the start so it can ask the user the same question
the code its self:
var min = 0
var max = 100
var roll = 20
function start() {
println("hello pick a num between 0 and 100 type -1 if you wanna quit")
var roll = 20
var userguess = readInt("what is your guess: ")
while(userguess > min){
if (userguess > roll){
println("too high you ")
}
if (userguess < roll){
println("to low ")
}
if(userguess == -1 ){
println(" you quit")
break;
}
if(userguess == roll ){
println("wait you got it ")
break;
}
}
}
welcome to the coding world.
In this case, you can use Recursive Functions. If you Google it, you’ll find tutorials that can explain it much better than my answer.
I'll just implement your requirements.
var min = 0
var max = 100
var roll = 20
function start(min, max, roll) {
println("hello pick a num between 0 and 100 type -1 if you wanna quit")
var userguess = readInt("what is your guess: ")
if(userguess == -1 ) {
println("you quit")
return "User exited";
}
if(userguess == roll ) {
println("wait you got it")
return userguess;
}
if(userguess < min && userguess > max) {
println("out of range")
return start(min, max, roll)
}
if (userguess > roll){
println("too high you")
return start(min, max, roll)
}
if (userguess < roll){
println("to low")
return start(min, max, roll)
}
}
I built a function called roll() which handles a roll of a dice. I'm trying to read the value of the roll and check if the roll hit 6 twice in a row so that I can interrupt the player's turn and turn it to the next player.
I can read the dice value alright, I'm having trouble trying to figure out how to check for a 6 twice in a row.
This is my function:
roll = function(){
if (gamePlaying){
// 1. Get a random number
//var dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
var dice = 6;
//2. Display the result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'images/' + 'dice-' + dice + '.png';
//3. Update the roundScore IF the rolled number is not 1
// for type coersion, we need to use !== and not !=
if(dice !== 1) {
//add score
roundScore += dice; // same as roundScore = roundScore + dice
//it outputs to a div of ID = #myId
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
alert('Next Player')
nextPlayer();
}
// Is this right?
for(var i = 1; i >= 2; i++){
if (dice == 6){
console.log('sixes');
}
}
}
}
Being triggered by a button like this:
document.querySelector('.btn-roll').addEventListener('click', function(){
roll();
});
I loaded the game to this CODEPEN
P.S. I put a dice = 6; under the random function so you don't have to play the game until you get two sixes. Just uncomment it and comment out the dice = math function and you'll get nothing but sixes.
I also put a "Is this right?" comment on top of a for loop. What I mean by that is, " is this the right approach?" Should I keep experimenting with a loop or am I way off already?
And by the way, if 2 sixes do come up, the entire score is deleted which is being passed to the score[] But I can do that... I think lol
Many thanks.
You can try something like this, where you make roll() a self invoking function. That way you can store how many times they have rolled a six.
roll = (function(){
var count = 0;
var lastRoll = 0;
return function() {
if (gamePlaying){
// 1. Get a random number
var dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
var thisRoll = dice;
if(dice === 6) {
lastRoll = 6;
count += 1;
} else {
lastRoll = 0;
count = 0;
}
if(thisRoll === 6 && lastRoll === 6 && count === 2) {
alert('You rolled a six twice!');
lastRoll = 0;
count = 0;
// do your stuff for 2 sixes in a row here!
return;
}
//2. Display the result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'http://sitedev.online/repo/' + 'dice-' + dice + '.png';
//3. Update the roundScore IF the rolled number is not 1
// for type coersion, we need to use !== and not !=
if(dice !== 1) {
//add score
roundScore += dice; // same as roundScore = roundScore + dice
//it outputs to a div of ID = #myId
document.querySelector('#current-' + activePlayer).textContent = roundScore;
console.log(dice);
} else {
alert('Next Player')
nextPlayer();
}
}
}
})();
Just for the heck of it, you don't need any global or outside vars to do this. The trick is, remember that functions are objects. You can read and write properties to them; you can even entirely change a function from within the function (which is the trick to an old JS singleton pattern).
Here's an example. If you say feed it "true", it will update the "last" reference values and return two random dice rolls. If you feed it "false", it will NOT update the previous reference values until you pass in true again (but it still returns a fresh roll). That way, you can keep rolling, hold the initial value, and compare it to a new second value all you want.
<html>
<head>
</head>
<body>
<script>
var rollfunc = function ( updateLast ) {
var d1 = Math.floor((Math.random() * 6) + 1);
var d2 = Math.floor((Math.random() * 6) + 1);
if ( updateLast ) {
rollfunc.d1 = d1;
rollfunc.d2 = d2;
}
return {
dice1 : d1,
dice2 : d2,
bothsixes : ( ( d1 + d2 === 6 ) && ( rollfunc.d1 + rollfunc.d2 === 6 ) )
};
}
var result = rollfunc ( true );
// If you pass in true then d1, d2, and rollfunc.d1, rollfunc.d2 will always be the same
console.log ( "Reference updated: ", result, "d1 = " + rollfunc.d1, ", d2 = " + rollfunc.d2 );
var result = rollfunc ( false );
// If you pass in false, the reference won't change, but the new roll will, you can compare the two
console.log ( "Reference left alone: ", result, "d1 = " + rollfunc.d1, ", d2 = " + rollfunc.d2 );
</script>
</body>
</html>
I get this might be overly academic, but it's useful to know JS can do this.
A little late to this game. But I'm new to JavaScript, and currently on a similar project from udemy.com.
Here's a solution I found that apparently works. I verified it on your CodePen, too.
document.querySelector('.btn-roll').addEventListener('click', function() {
if (gamePlaying) {
// 1. Get a random number
dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
thisRoll = dice;
if (dice === 6) {
lastRoll = 6;
count += 1;
} else {
lastRoll = 0;
count = 0;
}
if (thisRoll === 6 && lastRoll === 6 && count === 2) {
alert('You rolled a six twice!');
lastRoll = 0;
count = 0;
nextPlayer();
// do your stuff for 2 sixes in a row here!
return;
}
//2. Display result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'http://sitedev.online/repo/' + 'dice-' + dice + '.png';
//3. Update round score if the rollled number was not a 1
if (dice !== 1) {
//Add score
roundScore += dice;
//roundScore = roundScore + dice
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
Working on the same problem. Found another solution on udemy. Hope it helps...
var lastRoll;
document.querySelector('.btn-roll').addEventListener('click', function() {
// Generating a random variable
var dice = Math.floor(Math.random() * 6) + 1;
// Check for two consecutive 6's'
if ( dice === 6 && lastDice === 6) {
//If consecutive 6's code goes here
}
lastRoll = dice;
});
I'm trying to iterate over this if else statement as many times as someone wants. If the score = counter wins should get +1 each time, same with losses. However every time it goes through this wins and losses will only stay at 1.
var wins1 = 0;
var losses1 = 0;
if(counter == numberToguess)
{
counter = 0
console.log("you win")
randfunction()
randNum();
$(".scoreDiv").text(numberToguess)
losses1 += 1
console.log(wins1)
} else if(counter > numberToguess)
{
counter = 0
console.log("you lose")
randfunction()
randNum()
$(".scoreDiv").text(numberToguess)
losses1 += 1
console.log(losses1)
}
It's hard to tell from the context, but are you declaring win1 and losses1 at the top of your loop? If so then they are going to reset to 0 every time the loop runs, hence the final result of 1.
You have to post what you are using to populate numberToguess so that we can help you finish the script. Ill assume your using a prompt window:
var possibilities = 3;
var wins = 0;
var losses = 0;
var answer = "";
while(answer = prompt("guess a number")) {
var randomNumber = Math.floor(Math.random() * possibilities) + 1;
if(answer == randomNumber) {
wins++;
console.log("You Win");
} else {
losses++;
console.log("You Lose");
}
console.log("wins: " + wins + " - losses: " + losses);
}
var randomNum = Math.round(Math.random() * 100);
guesses = prompt("guess a number between 1 and 100");
var scores = 0;
while (randomNum < 100) {
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guesses === randomNum) {
console.log("great ... that is correct!!")
} else {
console.log("game over ... your guess was right " + scores + " times");
}
}
I have been struggling with the while loop concept for some time now and in order to confront my fears I decided to practice with some tiny exercises like the one above.
You're not incrementing randomNum hence it will always stay in an infinite loop.
You initialize randonNum and guesses at the beginning of your code, but then you never change their values again. So, once you go inside the while loop and the condition starts out to be false, then there is nothing inside the while loop to ever change the outcome of the comparison condition. Thus, the condition is always false and you end up with an infinite loop. Your loop structure boils down to this:
while (randomNum < 100) {
// randomNum never changes
// there is no code to ever break or return out of the loop
// so loop is infinite and goes on forever
}
You can fix the problem by either putting a condition in the loop that will break out of the loop with a break or return or you can modify the value of randomNum in the loop such that eventually the loop will terminate on its own.
In addition, guesses === randomNum will never be true because guesses is a string and randomNum is a number so you have to fix that comparison too.
It's not 100% clear what you want to achieve, but if you're trying to have the user repeatedly guess the number until they get it right, then you need to put a prompt() inside the while loop and a break out of the while loop when they get it right or ask to cancel:
var randomNum = Math.round(Math.random() * 100);
var guess;
var score = 0;
while ((guess = prompt("guess a number between 1 and 100")) !== null) {
// convert typed string into a number
guess = +guess;
if (guess < randomNum) {
console.log(" too low.. continue")
} else if (guess > randomNum) {
console.log("too high ... continue ");
score++;
} else if (guess === randomNum) {
console.log("great ... that is correct!!")
console.log("score was: " + score);
// when we match, stop the while loop
break;
}
}
the below line of code of your assign randomNum only one time hence it doesn't change
var randomNum = Math.round(Math.random() * 100);
so when you are trying to create the while loop the randomNum value remains same
try changing the randomNum value in the while loop
I think this is what you tried to achieve. Retry x number of times
var randomNum = Math.round(Math.random() * 100);
var guesses;
var scores = 0;
var tries = 0
while (tries++ < 3) { // Loop if less than 3 tries, and increment
guesses = prompt("guess a number between 1 and 100");
if (guesses < randomNum) {
console.log(" too low.. continue")
} else if (guesses > randomNum) {
console.log("too high ... continue ");
} else {
// It's not to low, not to high. It must be correct
score++;
console.log("great ... that is correct!!");
randomNum = Math.round(Math.random() * 100);
}
}
console.log("game over ... your guess was right " + scores + " times");
Hello i am very new to javascript and have been trying to make a random number guessing game. I think i almost got it except there is one thing i cant figure out. Everytime i run it i have to type in my number twice and it also only returns Lower no matter what number i type in.
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
{
while (randomNumber != readline())
if (readline() < randomNumber)
{
print("Lower");
}
else if (readline() > randomNumber)
{
print("Higher");
}
else if (readline() == randomNumber)
{
print("Good Job");
}
}
Your problem is you are calling readline multiple times per iteration of your while loop. Here I have stored the value of readline into a variable and use that to test:
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
var hasGuessedCorrectly = false;
while (!hasGuessedCorrectly)
{
var guess = readline();
if (guess < randomNumber)
{
print("Lower");
}
else if (guess > randomNumber)
{
print("Higher");
}
else if (guess == randomNumber)
{
print("Good Job");
hasGuessedCorrectly = true;
}
}