I am currently trying to code this extremely basic text-based golf game for practice. There's no trigonometry to it, there's just a randomness to how hard you hit the ball, and then how many shots it takes to reach the hole. At the end, it will mark your score as "Birdie" or "Par" or whatever. I'm not at that endstage yet though.
So my logic for the program is, start() is called through an onclick HTML attribute, and then we run through things from there. Everything is embodied in start(). The game's intro text is displayed with some DOM innerHTML.
The idea is that once start() has been activated, you can click swing() and it will swing and update the value and therefore the current position.
But I don't get what problem it's having with this nested function and the onclick. The error it says it has is at index.html line 1. But also, line 1 of my index.HTML is . I don't even know what this other index file is.
image 1; images not necessary but might help explain what I'm talking about
In VS Code, the nested function says it never even gets called. Is it just reading the lines and exiting too fast? Should I use setInterval or something to keep it reading?
function start() {
let introText = "It is a beautiful sunny day on Golf Island. The cobalt waters are great. There is no wind. You stand at the tee and get ready to strike. There's only one hole to go.<br>"
document.getElementById("textarea").innerHTML = introText;
holeDistance = 350;
function swing() {
swingValue = Math.floor(Math.random() * 100);
currentValue = String(holeDistance - swingValue);
return document.getElementById("textarea").innerHTML = "Hole position: " currentValue;
}
}
<button id="start" onclick="start()">Start game</button>
<div id="textarea">
<button onclick='swing()'>Swing</button>
</div>
CodePudding user response:
There are a few issues:
- your function is within another function
- you assign values to variables that you have never declared before. A variable needs to be declared with
var
/let
and can only be assigned afterward or at the same instance:
Issues to fix the game:
- You declare a variable within the function of hole distance with 350. Every time you click the button you reset the variable to 350 and roll the dice on that 350. You need to move the variable outside of the function and subtract the randomize shooting distance from the hole distance:
let holeDistance = 350;
function start() {
let introText = "It is a beautiful sunny day on Golf Island. The cobalt waters are great. There is no wind. You stand at the tee and get ready to strike. There's only one hole to go.<br>"
document.getElementById("textarea").innerHTML = introText;
}
function swing() {
let swingValue = Math.floor(Math.random() * 100);
holeDistance = holeDistance - swingValue;
return document.getElementById("textarea").innerHTML = `Hole position: ${holeDistance}`;
}
<button id="start" onclick="start()">Start game</button>
<div id="textarea">
<button onclick='swing()'>Swing</button>
</div>