我正在尝试使用HTML / CSS3和Javascript重新创建经典的手机游戏“Snake”。当我运行我在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>
答案 0 :(得分:1)
定义像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