I am trying to compile the following CoffeeScript code into Javascript:
GetCard = ->
do Math.floor do Math.random * 12
Results = ->
do NewGame if prompt "You ended with a total card value of #{UserHand}. Would you like to play again?"
else
alert "Exiting..."
NewGame = ->
UserHand = 0
do UserTurn
UserTurn = ->
while UserHand < 21
if prompt "Would you like to draw a new card?" is "yes"
CardDrawn = do GetCard
UserHand += CardDrawn
alert "You drew a #{CardDrawn} and now have a total card value of #{UserHand}."
else
do Results
break
But the resulting Javascript prints the following errors to the console if you say yes:
Uncaught TypeError: number is not a function BlackJack.js:4
GetCard BlackJack.js:4
UserTurn BlackJack.js:22
NewGame BlackJack.js:14
onclick
CoffeeScript is also not setting UserHand to 0 for some reason. I am fairly new to Javascript and very new to CoffeeScript. I've searched around and read the CoffeeScript docs as well as the CoffeeScript Cookbook and as far as I can tell the CS code looks correct, while the JS doesn't:
var GetCard, NewGame, Results, UserTurn;
GetCard = function() {
return Math.floor(Math.random() * 12)();
};
Results = function() {
return NewGame(prompt("You ended with a total card value of " + UserHand + ". Would you like to play again?") ? void 0 : alert("Exiting..."))();
};
NewGame = function() {
var UserHand;
UserHand = 0;
return UserTurn();
};
UserTurn = function() {
var CardDrawn, _results;
_results = [];
while (UserHand < 21) {
if (prompt("Would you like to draw a new card?") === "yes") {
CardDrawn = GetCard();
UserHand += CardDrawn;
_results.push(alert("You drew a " + CardDrawn + " and now have a total card value of " + UserHand + "."));
} else {
Results();
break;
}
}
return _results;
};
Any help would be greatly appreciated. Thanks!
Update: Thanks for all the answers. I just got a little confused on the double parentheses and mistakenly used the do keyword to replace the parameter parenthesis instead of the function call parenthesis. I'm still confused on the global scope though. I know you can use the var keyword in plain JS, but on the CoffeeScript docs it specifies that you should never need to use it, as it manages scope for you?
Math.floor(Math.random() * 12)()(note the trailing brackets). As to why coffeescript added that, I don't know (I'm not familiar with it). At a guess, maybe because you have 2dokeywords in that line?UserHand, but it is a local variable toNewGame. I guess you intended it to be a global variable. Again, I'm not familiar with coffeescript so I don't know exactly what you need to do there.