我是JS的初学者,并且我正在一个学校项目中创建自己的蛇游戏。我想分开我的功能,因此并非所有内容都在一个JS文件中。
例如,我试图将CheckForCollisions函数放到另一个JS文件中,但是如果我启动游戏时它给我一个错误,那snake.Trymove不是函数。这是我的HTML文件:
<html>
<head>
<title> Snake </title>
<meta charset="utf-8"/>
<script src="js/snake.js"></script>
<script src="js/Collisions.js"></script>
<script src="js/EventHandler.js"></script>
<canvas id ="snake" width="960" height="720"></canvas>
</head>
<body>
</body>
</html>
这是我要解析的主要JS文件:
window.onload = function()
{
const cvs = document.getElementById("snake");
const ctx = cvs.getContext("2d");
//here are some variables
window.onclick = function (event)
{...}
var Field = function (cols, rows, areawidth, areaheight) //pole
{...};
var Snake = function()
{
...
this.tryMove = function (deltaTime)
{
this.movedelay += deltaTime;
var maxmovedelay = 1 / this.speed;
if (this.movedelay > maxmovedelay)
return true;
return false;
}
}
this.nextMovement = function ()
{...}
this.move = function ()
{...}
this.grow = function ()
{...}
this.faster = function ()
{...}
this.slower= function ()
{...}
};
var snake = new Snake();
var field = new Field(20, 14, 48, 48);
var score = 0;
var health = 1;
var gameover = true;
var gameovertime = 1;
var seconds = 80;
function start ()
{
document.addEventListener("keydown", onKeyDown);
drawMenu();
newGame();
main(0);
}
function tryNewGame()
{...}
function newGame()
{...}
function continueGame()
{...}
function addHamburger()
{...}
function addBonushealth()
{...}
function addFaster()
{...}
function addSlower()
{...}
function main (thisframe)
{
window.requestAnimationFrame(main);
update(thisframe);
if (click == 0)
drawMenu();
else
{
drawField();
drawSnake();
drawinfoboard();
....
}
}
var lastframe = 0;
function update(thisframe)
{...}
function CheckForCollision(deltaTime)
{
if (snake.tryMove(deltaTime))
{
var nextmove = snake.nextMovement();
var nx = nextmove.x;
var ny = nextmove.y;
}
}
function drawField()
{...}
function drawSnake()
{...}
function drawMenu()
{...}
function randomnumber(min, max)
{...}
function onKeyDown(event)
{...}
start();
}
现在,如果我尝试将CheckForCollisions函数放置在单独的JS文件中,则会给我一个错误:
Uncaught TypeError: snake.tryMove is not a function
at CheckForCollision (Collisions.js:3)
at update (snake.js:453)
at main (snake.js:391)