Я пытаюсь сделать простую JS-игру на основе рассказа, который я прочитал в старшей школе, про роботов-крабов на маленьком острове. Это будет более или менее симулятор, где игрок задает начальные параметры, затем нажимает кнопку «Старт» и наблюдает, как все разворачивается.
Моя проблема здесь в том, что я не могу изменить innerHTML div mainWindow - проблема, с которой я никогда раньше не сталкивался.
Код не выдает никаких ошибок, но когда я открываю инспектор в своем браузере, он показывает, что div mainWindow просто пуст, несмотря на то, что сам объект-краб работает, как задумано.
Код включен ниже:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Crabs!</title>
<head>
<script>
var theCrabs = [new crab(12, 12, new Vector2(512, 384), "alive")];
var numCrabs = 2;
var islandSizeX = 1024;
var islandSizeY = 768;
var theTime = new clock(12, 0, 0);
var fps = 60;
var go = false;
function Vector2 (_x, _y)
{
this.x = Number(_x);
this.y = Number(_y);
}
function crab (_size, _speedmax, _position, _status = "alive")
{
this.size = _size;
this.speedmax = _speedmax;
this.speed = new Vector2(0, 0)
this.position = _position;
this.target = new Vector2(0, this.position.y)
this.status = _status;
this.xMoment = 0;
this.yMoment = 0;
this.Move = function (_murder = false) {
if (this.status == "alive") {
if (this.position.x > this.target.x) {
this.speed.x = this.speedmax * -1;
} else if (this.position.x < this.target.x) {
this.speed.x = this.speedmax;
} else {
this.speed.x = 0;
}
if (this.position.y > this.target.y) {
this.speed.y = this.speedmax * -1;
} else if (this.position.y < this.target.y) {
this.speed.y = this.speedmax;
} else {
this.speed.y = 0;
}
this.position.x += this.speed.x;
this.position.y += this.speed.y;
}
if (this.position.x < 0) {
this.position.x = 0;
this.target.x = islandSizeX;
}
if (this.position.x > (islandSizeX - this.size)) {
this.position = (this.islandSizeX - this.size);
this.target.x = 0;
}
if (this.position.y < 0) { this.position.y = 0; }
if (this.position.y > (islandSizeY - this.size)) { this.position = (this.islandSizeY - this.size); }
}
this.getColorByStatus = function () {
(REMOVED FOR BREVITY)
}
}
function draw ()
{
//clear the window
document.getElementById("mainWindow").innerHTML = "";
//draw clock
document.getElementById("mainWindow").innerHTML += "<div style='position:relative; left:10px; top:10px; color:black;>" + theTime.getTime() + "</div>";
//draw crabs
for (var i=0; i<theCrabs.length; i++) {
currentCrab = theCrabs[i];
document.getElementById("mainWindow").innerHTML += "<div style='width:" + currentCrab.size + "; height:" + currentCrab.size + "; position:relative; left:" + currentCrab.position.x + "px; top:" + currentCrab.position.y + "px; background-color:" + "rgb(200, 90, 110)" + ";></div>";
}
}
function clock (_h, _m, _s)
{
(REMOVED FOR BREVITY)
}
function tick ()
{
if (go) {
for (var i=0; i<theCrabs.length; i++) {
theCrabs[i].Move();
}
theTime.addTime(0, 0, 10);
draw();
}
}
function FPS () { return Math.round(1000 / fps); }
function startstop()
{
if (!go) {
go = true;
document.getElementById("btnStart").innerHTML = "STOP";
setInterval(tick, FPS());
} else {
go = false;
document.getElementById("btnStart").innerHTML = "START";
clearInterval(tick);
}
}
</script>
<style> body { background-color: rgb(0, 128, 200); } </style>
</head>
<body>
<div id = "foundation" style = "height:100%; width:100%; border: 0px white solid;">
<div id = "mainWindow" style = "height:768px; width:1024px; border: 2px black solid; background-color: rgb(255, 250, 175);">
</div>
<button id = "btnStart" onclick = "startstop()">START</button><br/><br/>
<span style = "font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; font-size: 24pt; color: white;"> Crabs on the island. </span>
</div>
</body>
</html>
Вы уверены, что функция рисования работает? Вы должны проверить это с помощью console.info ('Hello') внутри функции
Ах! Вы правы, @thmsdnnr - я изначально сохранял позицию по-другому, и я, видимо, напортачил при ее изменении. Спасибо!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы пропустили цитату ' перед закрытием добавленного стиля содержимого
document.getElementById("mainWindow").innerHTML += "<div style='position:relative; left:10px; top:10px; color:black;'>" + theTime.getTime(+ "</div>";
просто добавьте его после color:black;', а также ... + "rgb(200, 90, 110)" + ";'></div>";
чтобы избежать других проблем, попробуйте добавить атрибут async к тегу script, используйте
document.querySelector("#mainWindow").innerHTML = "you content ..." или удалите содержимое скрипта и поместите его перед закрытием тега body
</body>
...
<script>
<!--your script-->
</script>
</body>
Я заметил одну вещь: ваша позиция краба была NaN. Ближе к концу метода crab.Move вы перезаписываете переменную положения Vector2 целым числом
this.position = (this.islandSizeX - this.size);иthis.position = (this.islandSizeY - this.size);.