making a point counter for a dice game in javascript - javascript

I am trying to make a dice game point counter where you are awarded points based on how close your guess of what you thought the number was going to be to what the number rolled is. My current code looks like this
function continueL(e){
if (e.keyCode == Keyboard.letter('L')){
add(copter);
var evorod = readInt("What number do you think it's going to be? You are guessing ");
println("Please click the die to roll a number");
mouseClickMethod(contin);
}
}
function contin(e){
var num = Randomizer.nextInt(1,12);
println("The number rolled is.... " + num);
var numText = new Text("The number rolled is...." + num, "20pt Arial");
numText.setPosition(50, 200);
numText.setColor(Color.red);
add(numText);
if (num == evorod){
println("Congrats! You Win! Here is 100 points");
} else {
if(num == evorod - 1 || num == evorod + 1){
println("So close! Here is 80 points!");
} else {
if(num == evorod - 2 || num == evorod + 2){
println("Almost got it. Take 60 points!");
} else {
if(num == evorod - 3 || num == evorod + 3){
println("Nice try. Take 40 points!");
} else {
if(num == evorod - 4 || num == evorod + 4){
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
}
}
}
}
remove(copter);
}
But it only displays the final else no matter what your guess was vs the number rolled.
edit: evorod is a global variable

evorod needs global scope, right now it only exists inside the continueL() function so will be undefined when you try to use it in contin(). Fix that by declaring it outside the function.
Meanwhile your if statements could be simplified to this, instead of a bunch of separate nested conditionals:
if (num == evorod) {
println("Congrats! You Win! Here is 100 points"); // there is no println in javascript, I'll assume you've coded your own equivalent
} else if (num == evorod - 1 || num == evorod + 1) {
println("So close! Here is 80 points!");
} else if (num == evorod - 2 || num == evorod + 2) {
println("Almost got it. Take 60 points!");
} else if (num == evorod - 3 || num == evorod + 3) {
println("Nice try. Take 40 points!");
} else if (num == evorod - 4 || num == evorod + 4) {
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}

Try a switch statement instead. There are 6 possible outcomes per throw. If you guessed less or more than the actual outcome you lose 20 points per digit away from the true outcome.
First of all, let's find how off your prediction was from the roll. We do that by subtracting (excuse my shabby math).
int outcome = ...
int guess = ...
int difference;
if(outcome > guess)
difference = outcome - guess;
else if(outcome < guess)
difference = guess - outcome;
switch(difference)
{
case 0:
{
System.out.println("100 Wondred points!");
break;
}
case 1:
{
System.out.println("You get 80 hamsters!");
break;
}
}
And so on it goes, with a difference of 5 being the lowest score because it means you were 5 numbers away from the outcome.

Related

I have an error in my school javascript project

I have multiple errors in my code. When I run the code, it gives an error saying that there is an unexpected identifier. Here is the full error, "SyntaxError: Unexpected identifier at /script.js:46:16". However, when I check through lines 46 through 16, I cant find any unclosed functions or methods. When I comment the if statement on line 46, it just gives an error on the other if statement. Can someone help me?
Heres the code:
function print(str){
console.log(str)
}
function farhToKelvin(far){
const cel = Math.floor(far / (9/5) - 32)
const kel = cel + 273
return kel
}
function farhToCelsius(far){
const cel = Math.floor(far / (9/5) - 32)
return cel
}
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(far / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(far / (9/5) - 32)
}
}
while (farh != "exit"){
var farh = prompt("enter a farhanhite tempature: ")
var type = prompt("convert it to celsius, or kelvin")
type.toLowerCase()
if (type == "celsius"){
const c = farhToCelsius(farh)
var val = convertToFarh(c)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
else if(type == "kelvin"){
const k = farhToKelvin(farh)
var val = convertToFarh(k)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
}
if (val > 50 or val == 50){
In Javascript, instead of or, we use ||. If you have a similar problem again, you might want to take a look at What does this symbol mean in JavaScript?
change
if (val > 50 or val == 50)
to this
if (val > 50 || val == 50)
or better to this
if (val >= 50)
there are similar problems on line 50 and 60 and 64
you need to update them all.
logically line 46 and 50 are the same. based on you print message the line 50 should be
if (val > 50 ) but line 45 should be if ( val <= 50)
so you have both syntax and semantic problems in your code to address
Here's a complete list of the issues you have in your code:
Using or instead of || (as others have stated)
Using incorrect variable name in the convertToFarh function
Omitting type parameter when calling convertToFarh
Attempting to call String.toLowerCase() on a number variable
Misspelling fahrenheit
Using or instead of || (Logical OR)
In your code, I believe you are intending to indicate if (val > 50 || val == 50) { instead of using or as used in other programming languages.
Before:
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
After:
if (val > 50 || val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 || val == 50){
print("it is hot, you should wear a tank top")
}
This logic also doesn't make sense. Perhaps you mean value < 50 in the first one and val >= 50 in the second?
You also repeat yourself whether you're converting to/from Kelvin or Celsius, so that code could be extracted out into its own function or just reduce the if..else blocks down to only affect the necessary variables and perform the comparison after these blocks.
Using incorrect variable name in convertToFarh function
In the convertToFarh function, you reference a variable named far, but there's no variable by that name. So you either mean to reference the val argument or you are trying to reference the fahr variable declared outside the function. In my code, I assume the former is the case val and rename it as follows:
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(val / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(val / (9/5) - 32)
}
}
Omitting type parameter when calling convertToFarh
In both function calls to convertToFarh, you use the c or k variable as the value of the val parameter, but you don't indicate the type. I have fixed this to indicate the type for each part:
var val = convertToFarh("celsius", c);
var val = convertToFarh("kelvin", k);
Attempting to call String.toLowerCase() on a number variable
In the convertToFarh function, you are attempting to call the String.toLowerCase() method on a number type (val) which gives an error. In my code, I simply commented this out and confirmed it can safely be removed.
Misspelling fahrenheit
It might not seem like a big deal, but making sure variables have proper spelling helps when others are reviewing your code (whether bug-fixing or general code review). I have fixed function names, variable names, and any references to fahrenheit in your code to be the proper spelling. This includes:
"enter a fahrenheit temperature: "
function fahrToKelvin and function calls
function fahrToCelsius and function calls
function convertToFahr and function calls
The variable named farh to fahr
Function parameters named far were changed to val to avoid variable name collision
Full code
function print(str) {
console.log(str);
}
function fahrToKelvin(val) {
const cel = (val - 32) / (9 / 5);
return Math.floor(cel + 273.15);
}
function fahrToCelsius(val) {
const cel = Math.floor((val - 32) * 5 / 9);
return cel;
}
function convertToFahr(type, val) {
if (type == "kelvin") {
return Math.floor(val / (5 / 9) - 459.67);
} else if (type == "celsius") {
return Math.floor(val / (9 / 5) + 32);
}
}
var fahr = prompt("enter a fahrenheit tempature: ");
var type = prompt("convert it to celsius, or kelvin");
type = type.toLowerCase();
if (type == "celsius") {
const c = fahrToCelsius(fahr);
var val = convertToFahr("celsius", c);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
} else if (type == "kelvin") {
const k = fahrToKelvin(fahr);
var val = convertToFahr("kelvin", k);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
}

checkPrime function returns incorrect values

numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num in numbers) {
if (num % i === 0) return num + ' is not prime';
else {
return num + ' is prime';
}
return num !== 1;
} else {
return num + ' is not in range';
}
}
}
console.log(checkPrime(27));
Hi.
In the above code, I tried to create a function which returns information about whether a number is prime or not.
However, it fails in some cases. Like eg. in the case of 27 or 145, it returns the values are prime, which obviously is false. How can I amend this program to make it work?
Also, what is the smartest way of merging the case for number 2 and the rest prime numbers?
Thanks in advance and sorry if this is too basic, I could not find the right answer anywhere else.
You are putting the 'else' clause that states the number is prime before having finished to check all numbers until itself -1.
To be optimal, you don't need to loop until the number ( < num). Just until the square root of the number. (even better than looping until num/2) For example : 167 can be seen that is prime when the loop has reached 13. 13*13 = 169 > 167 so you can stop and safely afirm that 167 is prime.
For number 2 it is correct to have a sepparate case.
Below is the code for checking a single value if it is prime:
function checkPrime(num) {
if (num == 1 || num === 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < Math.sqrt(num); i++) {
if (num % i === 0) return num + ' is not prime';
}
return num + ' is prime';
}
alert(checkPrime(27));
I have rewritten the code to provide the right answer
numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
// check this condition outside the loop
if (!(num in numbers)) {
return num + ' is not in range';
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return num + ' is not prime';
}
}
return num + ' is prime';
}
console.log(checkPrime(27));
I've rewritten your code and made a couple of changes.
The reason you were having your problem is that you were returning in the for loop meaning all odd numbers would declare themselves as prime numbers.
I've fixed this but also I've I rearranged things a little, to be as efficient as possible it's good to bail as soon as possible so I do a couple of checks to bail initially I check if the number is in range, if not bail.
I've commented the code so it makes sense but if you don't understand why I've done something feel free to ask.
// make an array of all numbers between 0 and 10000
numbers = [];
for (x = 0; x <= 1e4; x++) {
numbers.push(x)
}
function checkPrime(num) {
// return if input number is not in numbers array
if (numbers.indexOf(num) == -1) return num + ' is not in range'
// return if number is 0 or 1
if (num <= 1) return 'It is a separate case'
// check all numbers between 2 and input number
// return if any number devides neatly
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
// if you get this far it's prime
return num + ' is prime';
}
console.log(checkPrime(27));
Personally, for the range, I wouldn't have an array of all the values but I've left this in just in case there was some other reasoning we don't know about.
EDIT:
As you've said the initial array is not important I've remade the code to work without it, I've not included comments this time (to save space) but that code does the same thing and is mostly unchanged.
function checkPrime(num) {
if (num < 0 || num > 1e4) return num + ' is not in range'
if (num <= 1) return 'It is a separate case'
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
return num + ' is prime';
}
console.log(checkPrime(27));
Anyway, I hope you find this helpful 🙂

Prime Number Function in Javascript ...multiple statements

So I'm tasked with making program that can tell whether a number is prime or not. I want to solve this problem using a multiple if-statement. The one that I came up with is awkward. So i just want some feedback on how to make it better.:
function primenumber(num) {
if (num / num === 1 && num % 2 !== = 0 || num % 3 !== = 0 | num % 5 !== = 0 | num % 7 !== = 0) {
return true;
} else {
return false
}
}
I figured these numbers are the lowest common denominators. So a number is prime if these numbers don't divide evenly into it. Any feedback is greatly appreciated. Keep in mind that I am new to Javascript.
I figured it out:
If((num === 1) || (num === 2) || (num === 3) || (num === 5) || (num === 7))
{ return true;
}
If((num%2===0) || (num%3===0) || (num%5===0) || (num%7===0)){
return false;}
}
return true;
}
It may not be the most sophisticated coding but it's mine and it works perfectly.. at least according to coderbyte

Javascript Fizzbuzz Issue

I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.
I tried the following:
for (var i = 1; i <= 100; i ++)
{
if (i%3 !== 0 || i%5 !== 0){
console.log(i);
}
}
This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!
I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).
The typical answer to FizzBuzz is:
if( i%3 == 0 && i%5 == 0) FizzBuzz
elseif( i % 3 == 0) Fizz
elseif( i % 5 == 0) Buzz
else number
So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)
Here's a quite simple FizzBuzz function that accepts a range of numbers.
function fizzBuzz(from, to) {
for(let i = from; i <= to; i++) {
let msg = ''
if(i % 3 == 0) msg += 'Fizz'
if(i % 5 == 0) msg += 'Buzz'
if(msg.length == 0) msg = i
console.log(msg)
}
}
fizzBuzz(1, 25)
As for a more complex solution, that's one way you could define a higher order function which generates customized FizzBuzz functions (with additional divisors and keywords)
function fizzBuzzFactory(keywords) {
return (from, to) => {
for(let i = from; i <= to; i++) {
let msg = ''
Reflect.ownKeys(keywords).forEach((keyword) => {
let divisor = keywords[keyword]
if(i % divisor == 0) msg += keyword
})
if(msg.length == 0) msg = i
console.log(msg)
}
}
}
// generates a new function
const classicFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5 })
// accepts a range of numbers
classicFizzBuzz(1, 25)
const extendedFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 })
extendedFizzBuzz(1, 25)
I attacked this the same was as Niet the Dark Absol:
for (var n = 1; n <= 100; n++) {
if (n % 3 == 0 && n % 5 == 0)
console.log("FizzBuzz");
else if (n % 3 == 0)
console.log("Fizz");
else if (n % 5 == 0)
console.log("Buzz");
else
console.log(n);
}
However, you can also do it this way:
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.

Math calculation issue with Javascript

I am having a bit of trouble with a few math calculation in javascript.
The goal of this calculation is to generate a value when the user clicks on a text field.
For example:
1 Kilogram costs 32 cents to ship to America and the user wants to find out what 10KG will cost him which is $3.20. For this I have the following piece of javascript code:
function calculate(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) multiplyBy = 0.32;
if(num == 2) multiplyBy = 0.14;
if(num == 3) multiplyBy = 0.24;
if(num == 4) multiplyBy = 0.53;
var sum = parseInt(document.getElementById('weight'+num).value) * multiplyBy;
if(isNaN(sum)) return false;
price.value = sum;
}
The above code works perfectly fine, however when I reverse the process (someone has $3.20 and wants to find out how much KG he/she can ship with that (which is 10KG) the script returns: 9.375KG
The following code is used for this calculation:
function reverse(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) divideBy = 0.32;
if(num == 2) divideBy = 0.14;
if(num == 3) divideBy = 0.24;
if(num == 4) divideBy = 0.53;
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
if(isNaN(sum)) return false;
weight.value = sum;
}
I honestly don't grasp why it is failing, It would be much appreciated if someone could help me out with this.
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
You are forcing price into an integer before dividing it. So if price is 3.20, you are actually dividing 3 / 0.32, which is 9.375.
Don't force it into an integer.

Categories

Resources