gpt4 book ai didi

javascript - 意外 token 错误行 41 -"y:Math.round(Math.random()*(h-cw)/cw);"

转载 作者:行者123 更新时间:2023-11-28 15:55:28 24 4
gpt4 key购买 nike

我正在尝试使用 HTML/CSS3 和 Javascript 重新创建经典手机游戏“贪吃蛇”。当我运行我在 chrome 中的内容时,我在第 41 行收到意外的标记错误。为什么分号是意外的?我目前的代码如下。

    $(document).ready(function(){
//define vars
var canvas = $('#canvas')[0];
var ctx = canvas.getContext("2d");
var w = canvas.width();
var h = canvas.height();
var cw = 15;
var d = "right";
var food;
var score;
var speed = 130;

//Snake Array
var snake_array;

//initalizer
function init(){
create_snake();
create_food();
score = 0;

if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
}

init();

function create_snake(){
var length = 5;
snake_array =[];
for(var i = length-1;i >=0;i--){
snake_array.push({x: i,y :0});
}
}


//Create Food
function create_food(){
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- line 41
};
}




});



HTML CODE
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>


<div class="container">
<div id ="overlay">
Your final score: <span id = "final_score">
</span>
<br>
<a onclick="window.location.reload()" href="#">Click to play again!</a>

</div>

<canvas id="canvas" width="600" height="400">

</canvas>

<div id="stats">
<div class="score"></div>
<div class="score"></div>
<button onclick="resetScore()" id="reset_score">Reset high score</button>

</div>

</div>




<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Main JS -->
<script src="C:\Users\student\Desktop\SnakeGame\script.js"></script>
</body>
</html>

最佳答案

当定义这样的变量时 x:(通常用在对象中)你不能像你那样在最后定义的变量后面放一个 ;:

food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- remove this semi-colon
};

改为这样做

food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw)
};

我希望我能帮到你 :3

关于javascript - 意外 token 错误行 41 -"y:Math.round(Math.random()*(h-cw)/cw);",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41213961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com