Created a lottery number guesser sort of program that takes a number 1-10 and has the user guess the number, a total of 3 times, to win a "prize". In the lottery part of the program, I was able to get no problem but can't get the program to count the number of guesses and display the correct prize amount.
Here is the code I have:
<script>
var randomNum1 = Math.floor((Math.random() * 9) + 1);
var randomNum2 = Math.floor((Math.random() * 9) + 1);
var randomNum3 = Math.floor((Math.random() * 9) + 1);
console.log(randomNum1);
console.log(randomNum2);
console.log(randomNum3);
console.log(x);
var firstNum = false;
var secondNum = false;
var thirdNum = false;
var x = 0;
var moneyWon = 0;
firstNum = parseInt(prompt("Guess the first number."));;
secondNum = parseInt(prompt("Guess the second number."));;
thirdNum = parseInt(prompt("Guess the third number."));;
if((firstNum == randomNum1) || (firstNum == randomNum2) || (firstNum == randomNum3))
{
firstNum == true;
}
if(firstNum == true)
{
moneyWon = 100;
x++;
}
else{
moneyWon = 0;
}
if((secondNum == randomNum2) || (secondNum == randomNum1) || (secondNum == randomNum3))
{
secondNum == true;
}
if(secondNum == true)
{
moneyWon = 200;
x++;
}
else{
moneyWon = 100;
}
if((thirdNum == randomNum2) || (thirdNum == randomNum1) || (thirdNum == randomNum3))
{
thirdNum == true;
}
if(thirdNum == true)
{
moneyWon = 500;
x++;
}
else{
moneyWon = 200;
}
alert("The computer's numbers are " + randomNum1 + " " + randomNum2 + " " + randomNum3 +
"\nYour guesses were " + firstNum + " " + secondNum + " " + thirdNum +
"\nYou got " + console.log(x) + " right" +
"\nYou've won $" + moneyWon);
</script>
First thing im noticing:
You got " + console.log(x) + " right" +
You dont want the console.log() here, just the x
The second thing, you dont want to set moneyWon every time in the ifs, but rather do moneyWon += amount, just like you are doing with the x
Also, in the else (indicating the guess was incorrect), you dont want to set nor add to the amount (I would suggest deleting these 3 elses altogether):
else{ moneyWon = 0; }
and a minor thing - give meaningful names to properties, ie
var firstNum = false should be more like (is)firstNumberGuessed (the is indicates that this is a boolean
I see you are on the right track re this, but its good to learn not to be lazy about this stuff asap
EDIT: you can also throw out assigning true to firstNum, secondNum, thirdNum and just have this:
if((firstNum == randomNum1) || (firstNum == randomNum2) || (firstNum == randomNum3))
{
moneyWon += 100;
x++;
}
Well, I don't need to tell you what are the errors and what are causing them, as my friend Dejan already included them in his answer. In my answer, I am trying to implement his answer as well as some useful javascript methods which may make your work a lot more easier and faster as well.
First of all, arrays are your friend. I have made arrays for user inputs as well as random numbers and populating them using a for loop.
Next, as we are using arrays, we can use the includes() method to find the values among the random numbers. It reduces your if else conditions.
Next, I am using string interpolation to get the output message.
let randoms = [];
let nums = [];
let numbers = ["first", "second", "third"];
let winPrize = [100, 200, 500];
let losePrize = [0, 100, 200];
for(let i=0; i<3; i++){
randoms.push(Math.floor((Math.random() * 9) + 1));
nums.push(parseInt(prompt(`Guess the ${numbers[i]} number.`)));
}
let x = 0;
let moneyWon = 0;
for(let i=0; i<3; i++){
if(randoms.includes(nums[i])){
x++;
moneyWon+=winPrize[i];
}else{
moneyWon+=losePrize[i];
}
}
alert(`The computer's numbers are ${randoms[0]}, ${randoms[1]} and ${randoms[2]}. \nYour guesses were ${nums[0]}, ${nums[1]} and ${nums[2]}. \nYou got ${x} right. \nYou've won $${moneyWon}`);
I believe that if we follow such practices, our code will remain short as well as easily readable and maintainable.
Related
completely new to javascript as of an hour ago. Trying to get a button to call a function. It was working fine like 20 minutes ago, but all of a sudden it's being touchy and deciding now to work, what am I missing here?
function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1), "");
numsArray[i] = nums;
document.write(numsArray[i] + " ");
}
if (nums == "x") break; // if user enters x, break loop
}
<p> Click the button to enter and display an array of numbers!</p>
<button onclick="sortFunction()">Click Me</button>
As previously commented, the if statement needs to be just after var nums = prompt line. We also use return most often to exit out of functions.
More importantly, rather than limiting the incorrect option to 'x', why not adjust it to:
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1), "");
if (typeof nums === "number") {
numsArray[i] = nums;
document.write(numsArray[i] + " ");
} else {
return;
}
}
all you have to do is put "if" inside of the function
function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1), "");
numsArray[i] = nums;
document.write(numsArray[i] + " ");
if (nums == "x") break; // if user enters x, break loop
}
}
<p> Click the button to enter and display an array of numbers!</p>
<button onclick="sortFunction()">Click Me</button>
The problem here is with if condition it was placed outside the for loop.
So this might work for you putting condition inside and will break the loop on value x
function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1),
if (nums == "x"){
break;
}
else{
numsArray[i] = nums;
document.write(numsArray[i] + " ");
}
}
}
I am a novice programmer. I am creating a 2D battleship game. I have successfully randomised the spawn points of said ships and I have an idea on how to proceed next.
I am using a 2D ship array to store the ships coordinates and the last address in each row would be its status: 0=floats, 1=single hit, 2=two hits and so on. But I ran into a problem and need help. I seem to be unable to store anything to said array. as you can see in my code board[][] works but ship[][] doesn't.
I am having an error in this segment:
var z = 1; //set to 1 for debugging purposes. z is supposed to be the length of each battleship.
ship[c][z] = 1; // for debug only. line to be removed during final iteration
console.log("c z = " + c + " " + z);
console.log("ship c z = " + ship[c][z]);
if(c == 0)
{
for(z = 0; z < 4; z++)// this for loop is for battlehsip. more for loops to be added one for each ship type.
{
console.log("a b = " + a + " " + b);
ship[c][z] = ("" + a + b);
console.log("sketchy array " + ship[c][z]);
a++;
console.log("Z = " + z);
}
}
and this is the console output(trimmed):
Loop start
i = 0
rn = 7
rn = 0
x y =7 0
board x y = 1
Board 7 0
C = 0
rng = 0
VH = 0
c z = 0 1
ship c z = undefined
a b = 7 0
sketchy array undefined
Z = 0
a b = 8 0
sketchy array undefined
Z = 1
a b = 9 0
sketchy array undefined
Z = 2
a b = 10 0
sketchy array undefined
Z = 3
This is my full code. Maybe this will clear out what I am trying to achieve. feel free to correct my existing logic.
var vhposition = 0;
var x = 0;
var y = 0;
var guess;
var guesses
var fsunk;
var userchoices = [];
var board = [];
var ship = []; //ship array. converted to 2D array to hold ship status and X
Y coordinates.
function createboard()
{
for (var i = 0; i < 10; i++)
{
board[i] = [];
}
return board;
}
function fleet()
{
for(var i = 0; i < 10; i ++)
ship[i] = [];
}
function rng() //Generates Random Numbers
{
var rn = Math.floor(Math.random() * 10);
console.log("rn = " + rn);
return rn;
}
function rngesus()
{
var rng = Math.floor(Math.random() * 2);
console.log("rng = " + rng);
return rng;
}
function play() // onclick function
{
console.log("game start");
bhit = 0; //battleship hit counter set to zero
c1hit = 0; //cruiser hit counter set to zero
//console.log("sunk array = " + sunk[0] + " " + sunk[1]);
fsunk = 0; //fleet status
createboard();
fleet();
var i = 0;
while(i < 10) // generates random points for ship spawn
{
ship[i] = 0; //overkill to ensure no residual data
console.log("Loop start"); //makes reading console easier
console.log("i = " + i);
spawn(i); //i acts as the ship id that is being worked on
i++;
}
//game();
}
function spawn(j) // ship positon generated, i think
{
x = rng();
y = rng();
console.log("x y =" + x +" "+ y);
board[x][y] = 1;
console.log(" board x y = " + board[x][y]);
position(x, y, j);
}
function position(a,b,c)
{
console.log("Board " + a + " " + b);
console.log("C = " + c);
vhposition = rngesus(); //returns 0 or 1 for ship orienetation. maybe later will add 4 way
console.log("VH = " + vhposition);
var z = 1; //set to 1 for debugging purposes. z is supposed to be the length of each battleship.
ship[c][z] = 1; // for debug only. line to be removed during final iteration
console.log("c z = " + c + " " + z);
console.log("ship c z = " + ship[c][z]);
if(c == 0)
{
for(z = 0; z < 4; z++)// this for loop is for battleship. more for loops to be added one for each ship type.
{
console.log("a b = " + a + " " + b);
ship[c][z] = ("" + a + b);
console.log("sketchy array " + ship[c][z]);
a++;
console.log("Z = " + z);
}
}
}
//function game()
{
//to be continued...
}
function userinput()// this works fine
{
guess = prompt("Enter the grid coordinates. Do not use space. X-coordinates 0-6, Y-coordinates 0-6.");
console.log("users input = " + guess);
while(guess < 0 || guess > 99 || userchoices.includes(guess)) //checks user input for repeated strikes or out of range. Suggest better way if possible. this is just bad code
{
alert("You have entered an invalid coordinate.");
guess = prompt("Try Again!");
}
guesses++; //increments no of guessess
userchoices.push(guess); //add users guess to array
return guess;
}
Sorry for the long question/post.
Thank you.
function position is called from spawn, spawn is called from play and in play you assign 0 to ship[i] ? So the ship is no longer a 2D array.
I'm supposed to do a math exercise with subtractions for a basic Javascript course. The exercise has to contain 5 exercises with 5 prompt-windows (e.g "10-7=", "5-1=" etc). The first number has to be bigger than the second one.
Therefore, I need to create a function that generates two random numbers and then returns them in an array. Before it returns, it has to make sure that the number in position 0 is bigger than the number in position 1, the random numbers has to be between 1-10. If the person answers the question right, an alert window should pop up and say "Right!" and the same if it's wrong.
My code so far is this, and I'm aware that it's not completely right. What's wrong? How can I make it right?
function number ()
{
var array = [a, b];
var numbers = Math.floor(Math.random()*10)+1;
array[0] = a ;
array[1] = b ;
if (a <= b)
a = a+b;
b = a-b;
a = a-b;
return a + b;
}
var mathQuestion = a + " - " + b +" = ";
var answer = a - b;
for(var i =0; i<6; i++) {
var yourAnswer = parseInt(prompt(mathQuestion));
if (yourAnswer === answer) {
alert("Right!");
}
else {
alert("Wrong!");
}
}
I'm not really sure what you are trying to achieve but I considered to have a look at your code to kind of improve it.
This code is working fine, so please have a look :)
function getTask() {
var array = [];
var numberA = getRandomNumber()
var numberB = getRandomNumber()
if (numberA > numberB) {
array[0] = numberA;
array[1] = numberB;
} else {
array[0] = numberB;
array[1] = numberA;
}
return array;
}
function getRandomNumber() {
return Math.floor(Math.random() * 10) + 1;
}
let questionCount = 1;
for (var i = 0; i < questionCount; i++) {
let numbers = getTask()
var mathQuestion = numbers[0] + " - " + numbers[1] + " = ";
var answear = numbers[0] - numbers[1];
var yourAnswear = parseInt(prompt(mathQuestion));
if (yourAnswear === answear)
alert("Right!");
else
alert("Wrong!");
}
Note: The problems was that you were missing the declaration of a and b. Put the keyword var before the values.
You can impress your teacher with ternary operators, join and sort array methods and arrow functions
Codepen demo
const getRandom = () => Math.floor(Math.random() * 10) + 1
const ask = () => {
const numbers = [getRandom(), getRandom()].sort((a, b) => b - a)
alert(
prompt(numbers.join(' - ') + ' = ') == numbers[0] - numbers[1] ?
'Right!' : 'Wrong!'
)
}
for (var i = 0; i < 6; i++) {
ask();
}
I'm not quite sure why my code is not working here. It is supposed to filter out odd and even numbers and put them into an array but I think my (lack of) understanding is on getting the numbers into the array how I want.
function oddAndEven(numbers) {
var odd = [];
var even = [];
for (num = 0; num < numbers.length; numbers++) {
if (numbers[num] % 2 == 0) {
even.push(numbers[num]);
} else if (numbers[num] % 2 == 1) {
odd.push(numbers[num]);
}
}
console.log(odd + "is odd and " + even + " is even");
}
iqTest(11221122);
function oddAndEven(numbers) {
var odd = [];
var even = [];
for (num = 0; num < numbers.length; num++) { // numbers is array, num is counter variable
if (numbers[num] % 2 == 0) {
even.push(numbers[num]);
} else if (numbers[num] % 2 == 1) {
odd.push(numbers[num]);
}
}
console.log(odd + " is odd and " + even + " is even");
}
oddAndEven([10,5,6,4,5]); // pass array as you are traversing though it
Incrementing the loop variable was not done in your case. Please try this.
function oddAndEven(numbers){
var odd = [];
var even = [];
for(num = 0; num < numbers.length; num++){
if(numbers[num] % 2 == 0){ //Even
even.push(numbers[num]);
}else { // Odd
odd.push(numbers[num]);
}
}
console.log(odd + "is odd and " + even + " is even");
}
Try this,
function oddAndEven(numbers) {
var odd = [];
var even = [];
for (num = 0; num < numbers.length; numbers++) {
if (numbers[num] % 2 == 0) {
even[num]=numbers[num];
} else if (numbers[num] % 2 == 1) {
odd[num]=numbers[num];
}
}
console.log(odd + "is odd and " + even + " is even");
}
You seem to improve your practice more.
function oddAndEven(numbers) {
var odd = [];
var even = [];
console.log ("length is " , numbers.length);
for (num = 0; num < numbers.length; num++) {
if (numbers[num] % 2 == 0) {
even.push(numbers[num]);
} else if (numbers[num] % 2 == 1) {
odd.push(numbers[num]);
}
}
console.log(odd + "is odd and " + even + " is even");
}
oddAndEven("82938411221122919239");
You missed num++, and you may want to send the input "82938411221122919239"
As A.T suggested, you shall send [8,2,9,....] as an input also.
function oddAndEven(numbers) {
var odd = [];
var even = [];
// a bit of optimization here, accessing `length` property only once
for (index = numbers.length - 1 ; index >= 0; index--) {
let current = numbers[index];
if (current%2 == 0) {
even.push(current);
} else {
odd.push(current);
}
}
console.log(odd + "is odd and " + even + " is even");
}
Fiddle: https://jsfiddle.net/zhaem/po12voLL/1/
I wrote a script that lets me specific the number of random numbers I want to display, and the max value any of those numbers can be. Like so:
var randomLimit = 100000
var numberCount = 20
var counter = 0;
document.write("<h1>" + numberCount + " random numbers. Max value of " + randomLimit + "</h1>" );
function randomNumber(limit) {
return Math.floor( Math.random() * limit ) + 1;
}
while ( counter < numberCount ) {
document.write(randomNumber(randomLimit) + "<br>");
counter++;
}
I'm trying to figure out how I can evaluate all these numbers and identify the largest one (and make that line item bold).
I tried to do it by checking if the current "randomNum" is greater than the others, but doesn't work and doesn't seem like quite the right approach anyway as it seems like it needs to wait for all the numbers to be generated before picking the biggest? Would love any ideas.
while ( counter < numberCount ) {
var randomNum = randomNumber(randomLimit)
if (this.randomNum > randomNum) {
document.write("<strong>" + randomNum + "</strong>" + " ");
} else {
document.write(randomNum + " ");
}
counter++;
}
You can have a variable that keeps track of the largest number and update it if the current number is greater than the largest number. When you're done generating all the random numbers, find that number and bold it.
var randomLimit = 100000
var numberCount = 20
var counter = 0;
var largestNumber = -1;
document.write("<h1>" + numberCount + " random numbers. Max value of " + randomLimit + "</h1>" );
function randomNumber(limit) {
return Math.floor( Math.random() * limit ) + 1;
}
while ( counter < numberCount ) {
var currNumber = randomNumber(randomLimit);
document.write("<span>" + currNumber + "</span><br>");
if (currNumber > largestNumber)
largestNumber = currNumber;
counter++;
}
var list = document.getElementsByTagName("span");
for (var i = 0; i < list.length; i++) {
if (list[i].innerHTML == largestNumber) {
list[i].innerHTML = "<strong>" + largestNumber + "</strong>";
}
}
<body>
<div id="layer1">
</div>
<script src="randomNum.js"></script>
</body>
Generate all numbers in a array, find the max, then write them all as in this code.
It is not not the best solution, because it need 3 iterations over the array (one for generate, one for find the max, and the last one print the numbers) but I think it is clear, and I always err to readability over performance.
You can not resolve this problem with less than 2 iterations, because you can never know if the next value (being random) will be larger than the previous.
var randomLimit = 100000
var numberCount = 20
var counter = 0;
document.write("<h1>" + numberCount + " random numbers. Max value of " + randomLimit + "</h1>" );
function randomNumber(limit) {
return Math.floor( Math.random() * limit ) + 1;
}
// Generate random numbers
var randomNumbers = []
for( counter = 0; counter < numberCount; counter++ )
randomNumbers.push(randomNumber(randomLimit))
// Find max value
var maxValue = Math.max.apply(this, randomNumbers)
// Write values
randomNumbers.forEach(function(value) {
str = value;
if(value == maxValue) str = "<strong>" + value + "</strong>";
document.write(str + "<br />");
})
Depending on your application, and how lazy you feel you could generate the big number from a higher set and randomly insert it. Not random.
Otherwise the Mozilla Developer Network says use Math.max.apply or the 'spread operator'. Spread operator as per example.
var randomNums = []
while ( counter < numberCount ) {
randomNums.push(randomNumber(randomLimit));
counter++;
}
var maxIs = Math.max(...randomNums), i;
for (i=0; i<numberCount; ++i) {
var num = randomNums[i];
if (num == maxIs) {
document.write('<b>' + num + '</b><br/>');
} else {
document.write(num + '<br/>')
}
}