Im doing a JavaScript CodeHS course, but what am I doing wrong? - javascript

Im doing intro to JS in a site called CodeHS. I believe I did the assignment its asking of me right but it says its wrong?
Here is what it wants me to do:
Here is what I did:
Heres what I apparently got wrong:
Ive run this code many times and it worked flawlessly, so why does it give me these errors?

You forgot to add a blank line inside the end of your while block, which also accounts for the line number. You should check the IMPORTANT note on the assignment.

I agree with #Jorge. You need to include the new line character '\n' at the end of the appropriate print statements, for the sake of the marking program. Try it like this:
while(numItems > 0) {
println('We have ' + numItems + ' in inventory.');
var buy = readInt('How many items would you like to buy?');
if(buy <= numItems) {
numItems -= buy;
println('Now we have ' + numItems + ' left.' + '\n');
} else {
println('There is not enough in inventory for that purchase.' + '\n');
}
}

Related

How to setup position with FEN string in stockfish.js?

I want to make a chess puzzle on my website for my student.
I use stockfish.js to play with the engine.
How to change the start position on the board?
I try to change all FEN string but did not work.
Where to look for the function or something?
Anybody can help me, please?
Interacting with the javascript port of Stockfish is (at time of writing) still like communicating with a chess engine that uses/supports UCI (Universal Chess Interface).
The UCI position command should suffice:
var fenString = "rnbqkbnr/ppppp1pp/8/5p2/3P4/8/PPP1PPPP/RNBQKBNR w KQkq - 0 2"
// start UCI
stockfish.postMessage("uci");
// start new game
stockfish.postMessage("ucinewgame");
// set new game position
stockfish.postMessage("position fen " + fenString);
// start search
stockfish.postMessage("go depth 10");
Edited: Updated case for postMessage() function.
I was working on the same thing and figured it out -- it's by no means obvious and within the stockfish example there are lots of little trips and pitfalls. I found a couple questions online and thought I'd give them some answers.
So -- this answer assumes working with the example code found here: https://github.com/nmrugg/stockfish.js/tree/Stockfish11/example.
There are two major modifications that need to happen - first in the index.html file and second in enginegame.js.
First we'll define a helper function which will make it easy to work with the url "search" as it's called:
function searchToObject() {
var pairs = window.location.search.substring(1).split("&"),
obj = {},
pair,
i;
for ( i in pairs ) {
if ( pairs[i] === "" ) continue;
pair = pairs[i].split("=");
obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}
return obj;
}
For ease I just placed that function in both files, within index.html it's at the beginning of the script tag, in enginegame.js it's the very first line. Also btw, I certainly pilfered that from stackoverflow, but I can't seem to find that answer any more, rats.
In index.html the newGame function wants to look like this:
newGame = function newGame() {
var baseTime = parseFloat($('#timeBase').val()) * 60;
var inc = parseFloat($('#timeInc').val());
var skill = parseInt($('#skillLevel').val());
game.reset();
let search = searchToObject();
if (search.player) {
game.setPlayerColor(search.player)
} else {
game.setPlayerColor($('#color-white').hasClass('active') ? 'white' : 'black');
}
if (search.fen) {
game.game.load(search.fen);
game.board.position(game.game.fen());
}
game.setTime(baseTime, inc);
game.setSkillLevel(skill);
game.setDisplayScore($('#showScore').is(':checked'));
game.start();
}
Note the game.game and game.board -- those need to be added in enginegame.js where it's returning an object. If I were writing this I would have done it differently, but I didn't have the patience to rename things.
Next up in enginegame.js we need to adjust prepareMove.
function prepareMove() {
stopClock();
$('#pgn').text(game.pgn());
board.position(game.fen());
updateClock();
var turn = game.turn() == 'w' ? 'white' : 'black';
if (!game.game_over()) {
if (turn != playerColor) {
let search = searchToObject();
if (search.fen) {
uciCmd('position fen ' + search.fen + ' moves ' + get_moves());
} else {
uciCmd('position startpos moves' + get_moves());
uciCmd('position startpos moves' + get_moves(), evaler);
}
evaluation_el.textContent = "";
uciCmd("eval", evaler);
if (time && time.wtime) {
uciCmd("go " + (time.depth ? "depth " + time.depth : "") + " wtime " + time.wtime + " winc " + time.winc + " btime " + time.btime + " binc " + time.binc);
} else {
uciCmd("go " + (time.depth ? "depth " + time.depth : ""));
}
isEngineRunning = true;
}
if (game.history().length >= 2 && !time.depth && !time.nodes) {
startClock();
}
}
}
See, the trick is that if ever there was a fen string to start the game, every subsequent position call needs to be different. I think that's probably what's tripping most people up - that's definitely what got me.
What helped things click for me was reading through the UCI documentation. Before that my board was in some crazy infinite loop.
Also one weird but critical bit I stumbled onto was the game.game.load(<fen string>) function call in the index.html file. I can't find any documentation for that. I don't even remember how I found it. But there it is!

Getting prices with an npm package not working

Actually I think there is an even better way to get the prices using this npm (you can open it to see better how it works):
https://github.com/jaggedsoft/node-binance-api than using the "coin "variable I am trying to use but I don't know how it could be possible, if you guys could help me to figure out with a better idea or the best way to pull prices with this package using discord it would be awesome, I've been already some days sticked to it :/
What I need:
To be able to replace "ticker.XRPBTC" (code below).
For example if I write ETH it should be changed from ticker.XRPBTC to ticker.ETHBTC
var coin = (message.content.toUpperCase()).slice(2) + "BTC";
binance.prices((error, ticker) => {
console.log("Price of " + coin + ":", ticker.XRPBTC);
});
for that I made the variable coin, I thought I could just write ticker.coin but it does not work...
I have tried this:
As an example:
ticker.XRPBTC - This code works, output: the actual price of the currency.
What I am trying:
var coin = XRPBTC
console.log(ticker.coin) - output: undefined
btw. I am writting console.log to test it in the console but I also have an error if I write:
if (msg.startsWith ("eth")) {
message.reply ("Price of " + coin + ":", ticker.TRXBTC);
}
an explanation of what ticker does:
The ticker has the function to get the last price of each currency, it can be for example ETHBTC, XRPBTC, TRXBTC etc. in this case eth, xrp and trx are the currencies. So in the ticker I just need to write it that way so that I can get the price for that pair.
As you can see in the code I sent you above, I am getting the text exactly how the ticker would "need it to look".
So if I write eth, the variable "coin" is transforming it into ETHBTC
Best!
I think you're looking for property access. You might want to check if the coin exists first, e.g.
var coin = message.content.toUpperCase().slice(2) + "BTC";
console.log(coin); // logs e.g. "ETHBTC"
binance.prices((error, ticker) => {
if (coin in ticker) {
var price = ticker[coin]; // <- property access
message.reply("Price of " + coin + ": " + price);
} else {
// handle error, e.g.
message.reply("Coin " + coin + " doesn't exist");
}
});

Javascript syntax error? "Unexpected Indentifier"

sorry I just started with javascrippt and html and I am having trouble finding out what the unexpected identifier is?
here is my function
function fillSearchPlayer(data){
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i]
var item = '<tr><td>'p.firstname + ' ' + p.lastname'</td><td>'p.job'</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>'
$('#searchPlayers tbody').append('item');
}
}
maybe you guys could help me, it's saying its coming from the line that starts with "var item"
'<tr><td>'p.firstname look like you missed a plus sign over there. The other thing is .append('item'); - you probably intented to do .append(item);.
As the guys mentioned in the direct comments above you should try to use some templating engine instead of constructing the strings the way you did it.
I would recommend you to read these pieces:
Handlebars - simple and convenient template engine in JavaScript - give it a try!
Template strings in ES2016 - a cleaner way to do what you did with manual string concatenation
There are several errors. String concatenation works with +, and you're missing a semicolon.
Try:
function fillSearchPlayer(data) {
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i];
var item = '<tr><td>' + p.firstname + ' ' + p.lastname + '</td><td>' + p.job + '</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>';
$('#searchPlayers tbody').append('item');
}
}
The var item = ... item mixes variable and literal definitions without the real concatenation going on. Just put a + between each varying element to achieve your goal.
You need to enclose the concatenation operator around the p.job variable.
Your assignment should look like this...
var item = '<tr><td>'+p.firstname + ' ' + p.lastname+'</td><td>'+p.job+'</td><td><button class="cbtn" onclick=requestPlayer('+ p.identifier + ')>More</button></td></tr>'

problems using the append() within a forloop

With an onclick="throw()" in one of my buttons and the value from a select tag, I want to spawn some dices in a div. so far I have this.
function throw() {
var i = document.getElementById('quantity').value;
for (var b = 1; b <= i; b++) {
$("#dices").append("<canvas class="canvasstyle" id='dice"+b"' height='200' width='200'></canvas>");
}
}
I can't get the (yet still empty) dices to spawn. It keeps giving me
Uncaught SyntaxError: missing ) after argument list, somewhere within the forloop. Anyone who can see the problem?
Ok, first thing is you are trying to use double quotes inside double quoted text; you should be using single quotes. And you are also missing a plus sign as Festive Turnip said. So the line should be
$("#dices").append("<canvas class='canvasstyle' id='dice" + b + "' height='200' width='200'></canvas>");
You are missing a +.
id='dice" + b "' should be id='dice" + b + "'

Can you run a JS if statement and for loop inside a line of JQuery?

I am very new to learning both Javascript and Jquery.
In the website I am creating I am trying to insert a Javascript if statement and a for loop in a line of JQuery. The last confirm does not run. I suspect it is the if statement that is causing the issue. How can I fix this? Here is how my code looks like.
$(document).ready(function() {
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " + lastname);
if (userResponse = "girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
})
});
There's a lot that doesn't make much sense with your code.
First, what is userResponse? Where does this get defined and where is it set? Have you verified under a debugger that it is indeed equal to "girl"?
Second, you probably meant to use a comparison equals not an assignment equals here:
if (userResponse = "girl") { // This should be ==
However, this should not prevent the block from running. In fact, it will force the block to always run since "girl" is true-ish.
Third, what is girlnames? Is it an array? Where is this defined? Have you verified it indeed contains valid items?
Lastly, I believe your for loop is incorrect:
for (var i = 0; i <= girlnames.length; i++) {
Should be:
for (var i = 0; i < girlnames.length; i++) {
Arrays start at 0, thus girlnames[girlnames.length] is not a valid item.
However, considering you don't use the i variable in your loop anywhere, again this should not actually cause any errors.
I would step through your code line by line using a script debugger (usually F12 in modern browsers) and set a break point at:
var lastname = $('#lastnameresponse').val();
Then verified each line is behaving correctly. If that still doesn't work, you'll need to post more of your code so we can get a better idea of what's going on.
UPDATE:
Based on your comment:
Here is where the userResponse variable is defined:
$(document).ready(function(){ $("#girlimg").click(function() { var
userResponse = prompt("Confirm the gender you selected").toLowerCase;
$('html, body').animate({ scrollTop: $(".LastName").offset().top },
2000);
It seems that userResponse gets declared within the click handler for the #girlimg tag:
$("#girlimg").click(function() {
// Everything declared here is local to this function
var userResponse = confirm(); // local variable
});
Thus, it would not be accessible in the click handler for .button3. You'll need to declare userResponse in a scope that is accessible to both functions. Perhaps global (this is frowned upon in JavaScript) or within your $(document).ready() code, provided both click event handlers are defined within that block.
First: it's Your not You're :)
Secondly, userResponse is undefined. Maybe it's defined somewhere else.
For comparison, use == operator.
Are you sure is that what you want to do? I see you also have confirm there.
Use confirm like this:
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
// confirm() returns true or false, depending on the clicked button
is_confirmed = confirm("You're last name is" + " " +lastname);
if (true == is_confirmed) {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}
}
});
girlnames is also not defined here (maybe it's somewhere else). Same for random and randomagain
As for writing JavaScript "in" jQuery: there is no such question. jQuery is a library written in Javascript that provides useful functions to ease development.
Following statement does not contain a proper JavaScript Comparison Operator
equals is written ==
if (userResponse = "girl") {
for reference look here
you forgot to close some arrows, any way when you put :
if (userResponse ="girl"){...}
you set userResponse variable to "girl", and that passes the value to the variable only
to check in the userResponse is equal to "girl" you should put
if (userResponse =="girl")
your final code will look like this
$(document).ready(function(){
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " +lastname);
if (userResponse ="girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}}}
)
});
p.s:you forgot to close too many arrows

Categories