简体   繁体   English

需要帮助更新文本,javascript

[英]Need help updating text, javascript

I am making a game in javascript for school but I ran into a problem with updating the counters.我正在为学校用 javascript 制作游戏,但在更新计数器时遇到了问题。 Here is the code I am having trouble with:这是我遇到问题的代码:

 function drawUnits() { ctx.drawImage(log, 380, 5, 32, 32); ctx.textBaseline = "top"; ctx.fillText(logy, 420, 21); ctx.textBaseline = "bottom"; ctx.fillText("Logs", 420, 21); } function Dayend(message) { if (message == 1) { ctx.width = ctx.width; alert("You chopped some trees"); var logy = logy + 4; DrawUnits() } } window.addEventListener('keydown', function(event) { if (event.keyCode == 85) { Dayend(1); } });

With logy being a variable which is defined earlier and log being a picture als defined earlier.其中 logy 是较早定义的变量,而 log 是较早定义的图片。

I don't get what is wrong with the code but as soon as I press the button I do get the alert but the counter doesn't update我不明白代码有什么问题,但只要我按下按钮,我就会收到警报,但计数器没有更新

Thank you all, I used both your answers and changed some unrelated stuff and it magically worked again :)谢谢大家,我使用了你们的答案并更改了一些不相关的东西,它再次神奇地起作用了:)

The code is missing several close brackets, so it is not runnable.代码缺少几个右括号,因此无法运行。 Please fix it.请修复它。 Also, in you comment you mention that logy is defined somewhere before the above code, but you are redefining a local variable with the sam ename in the Dayend() function.此外,在您的评论中,您提到 logy 是在上述代码之前的某处定义的,但是您正在 Dayend() 函数中使用相同的名称重新定义局部变量。 Could that be your issue, that the local logy variable is getting set instead of your global one?那可能是您的问题,本地 logy 变量正在设置而不是全局变量吗? Try chaiging:尝试chaing:

var logy = logy + 4;

to

logy += 4;

You are re-instantiating the variable logy with var .您正在使用var重新实例化变量logy Try replacing the last few lines with this:尝试用这个替换最后几行:

function Dayend(message) {
    if(message == 1){
        ctx.width = ctx.width;
        alert("You chopped some trees");
        logy = logy + 4;
        DrawUnits()
    }
}

You also need to make sure that logy is tracked on the global state, and that you aren't overwriting it somewhere else.您还需要确保在全局状态上跟踪logy ,并且您不会在其他地方覆盖它。 You might be better off passing the value to DrawUnits() .您最好将值传递给DrawUnits()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM