Javascript-форум (https://javascript.ru/forum/)
-   Оффтопик (https://javascript.ru/forum/offtopic/)
-   -   Помогите разобраться в игре. (https://javascript.ru/forum/offtopic/76113-pomogite-razobratsya-v-igre.html)

Мика 06.12.2018 12:58

Помогите разобраться в игре.
 
Здравствуйте друзья. У меня возникла проблема, решил написать игру ( змейку) использую девственный .JS, но вот не задача, в коде какая-та ошибка. Я очень долго перечитывал код, искал ошибку, прогнал его на всех возможных ресурсах для проверки валидности. Ничего не помогло, решил написать на разных форумах " Письмо Помощи", в надежде что найдутся люди более опытней чем я и помогут найти ошибку в коде.
Вот собственно сам код :
:-?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var width = canvas.width;
var height = canvas.height;

var blockSize = 10;
var widthInBlocks = width / blockSize;
var heightInBlock = height / blockSize;

var score = 0;

var drawBorder = function () {
ctx.fillStyle = "Gray";
ctx.fillRect(0,0,width,blockSize);
ctx.fillRect(0,height - blockSize, width,blockSize);
ctx.fillRect(0,0,blockSize, height);
ctx.fillRect(width - blockSize, 0, blockSize, height);
};

var drawScore = function () {
ctx.font = "20px Courier"
ctx.fillStyle = "Black";
ctx.textAlign = "left";
ctx.textBaseLine = "top";
ctx.fillText ("Score:" + score, blockSize, blockSize);
};

var gameOver = function () {
clearInterval (intervalId);
ctx.font = "60px Courier";
ctx.fillStyle = "Black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText ("Suck my dick", width / 2, height / 2);
};

var circle = function (x,y, radius, fillCircle) {
ctx.beginPath ();
ctx.arc(x,y,radius, 0, Math.PI *2, false);
if (fillCircle) {
ctx.fill ();
} else {
ctx.stroke ();
}
};

var Block = function (col, row) {
this.col = col;
this.row = row;
};

Block.prototype.drawSquare = function (color) {
var x = this.col * blockSize;
var y = this.row * blockSize;
ctx.fillStyle = color;
ctx.fillRect (x, y, blockSize, blockSize);
};

Block.prototype.drawCircle = function (color) {
var conterX = this.col * blockSize + blockSize /2; 
var centerY = this.row * blockSize + blockSize /2;
ctx.fillStyle = color;
circle (centerX, centerY,blockSize / 2, true);
};

Block.prototype.equal = function (otherBlock) {
return this.col === otherBlock.col && this.row === otherBlock.row;
};

var Snake = function () {
this.segments = [
new Block (7, 5),
new Block (6, 5),
new Block (5, 5)
];
this.direction = "right";
this.nextDirection = "right";
};

Snake.prototype.draw = function () {
for (var i = 0; i < this.segments.length; i++) {
this.segments.drawSquare("Blue");
}
};

Snake.prototype.move = function () {
var head = this.segments [0];
var newHead;

this.direction = this.nextDirection;

if (this.direction === "right") {
newHead = new Block(head.col + 1, head.row);
}	else if (this.direction === "down") {
newHead = new Block(head.col, head.row + 1);
}	else if (this.direction ==="left") {
newHead = new Block(head.col - 1, head.row);
}	else if (this.direction ==="up") {
newHead = new Block(head.col, head.row - 1 );
}

if (this.checkCollision(newHead)) {
gameOver();
return;
}
this.segments.unshift (newHead);
if (newHead.equal (apple.position)) {
score++;
apple.move();
} else {
this.segments.pop();
}
};

Snake.prototype.checkCollision = function (head) {
var leftCollision = (head.col === 0);
var topCollision = (head.row === 0);
var rightCollision = (head.col === widthInBlocks - 1 );
var wallCollision = (head.row === heightInBlocks - 1);

var wallCollision = LeftCollision || topCollision ||
rightCollision || bottomCollision;

var selfCollision = false;

for (var i = 0; i < this.segments.length; i++) {
if (head.equal(this.segments)) {	
selfCollision = true;
}
}

return wallCollision || selfCollision;
};

Snake.prototype.setDirection = function (newDirection) {
if (this.direction === "up" && newDirection === "down") {
return;
} else if (this.direction === "right" && newDirection === "left") {
return;
} else if (this.direction === "down" && newDirection === "up") {
return;
} else if (this.direction === "left" && newDirection === "right") {
return;
}
this.nextDirection = newDirection;
};

var Apple = function () {
this.position = new Block (10, 10);
};

Apple.prototype.draw = function () {
this.position.drawCircle ("LimeGreen");
};

Apple.prototype.move = function () {
var randomCol = Math.floor(Math.random () * (widthInBlocks - 2)) + 1;
var randomRow = Math.floor(Math.random () * (heightInBlocks - 2)) + 1;
this.position = new Block(randomCol, randomRow);
};

var snake = new Snake ();
var apple = new Apple ();

var intervalId = setInterval (function () {
ctx.clearRect (0, 0, width, height);
drawScore();
snake.move();
snake.draw();
apple.draw();
drawBorder();
}, 100);

var directions = {
37: "left",
38: "up",
39: "right",
40: "down"
};

$("body").keydown(function (event) {
var newDirection = directions[event.keyCode];
if (newDirection !== underfind) {
snake.setDirection(newDirection);
}
});




Как я юзаю его. Создаю html-файлик и кидаю код туда.
<!DOCTYPE html>
<head>
<title>Snake</title>
</head>
<script>

<----------------- Вот здесь размещаю змеечку --------|

</script>
</body>
</html>

рони 06.12.2018 13:21

Мика,
Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[html run]
... минимальный код страницы с вашей проблемой
[/html]

О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

Nexus 06.12.2018 13:30

https://learn.javascript.ru/devtools

Мика 06.12.2018 14:06

Вот в таком виде пойдёт ?

Мика 06.12.2018 14:20

https://o525.ru/TzXDxLWBOsyi6f2yPbH18_Eqjs4
Ничего не понял =-(

Мика 06.12.2018 14:20

https://o525.ru/j_AMabicI5LwXNlqX_rS-I0AzcM

Nexus 06.12.2018 14:30

Мика, скрипт свой перед </body> вставляйте.

MallSerg 06.12.2018 14:36

посмотри на 9 и 120 строки в твоем сообщении.
И блин меня реально пугает и раздражает код с setInterval ссылка на старую тему

Мика 06.12.2018 15:02

Попробовал, не получилось.

Мика 06.12.2018 15:03

Я не совсем понял что не так в 9 строке.
120 строку исправил, спасибо.

MallSerg 06.12.2018 15:10

А почему не 9 ?
А как же тогда быть со 159й строкой?
Весьма похоже что игру сначала написали а затем в данный код внесли кучу мелких ошибок. это похоже на тест новичков к способности искать ошибки.
Проще взять код и весь переписать =).

Клинки мышкой и управляй клавишами =).
<canvas id="canvas" height=250 width=550></canvas>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var c=document.getElementById("canvas"),d=c.getContext("2d"),e=c.width,f=c.height,h=e/10,l=f/10,m=0;function n(a,b){this.a=a;this.b=b}function p(a,b){return a.a===b.a&&a.b===b.b}function q(){this.c=[new n(7,5),new n(6,5),new n(5,5)];this.g=this.direction="right"}q.prototype.f=function(){for(var a=0;a<this.c.length;a++){var b=this.c[a],g=10*b.a;b=10*b.b;d.fillStyle="Blue";d.fillRect(g,b,10,10)}};
q.prototype.move=function(){var a=this.c[0],b;this.direction=this.g;"right"===this.direction?b=new n(a.a+1,a.b):"down"===this.direction?b=new n(a.a,a.b+1):"left"===this.direction?b=new n(a.a-1,a.b):"up"===this.direction&&(b=new n(a.a,a.b-1));a=0===b.b;var g=b.a===h-1,k=b.b===l-1;a=0===b.a||a||g||k;g=!1;for(k=0;k<this.c.length;k++)p(b,this.c)&&(g=!0);a||g?(clearInterval(r),d.font="60px Courier",d.fillStyle="Black",d.textAlign="center",d.textBaseline="middle",d.fillText("Game Over =(",e/2,f/2)):(this.c.unshift(b),
p(b,t.position)?(m++,t.move()):this.c.pop())};q.prototype.setDirection=function(a){"up"===this.direction&&"down"===a||"right"===this.direction&&"left"===a||"down"===this.direction&&"up"===a||"left"===this.direction&&"right"===a||(this.g=a)};function u(){this.position=new n(10,10)}u.prototype.f=function(){var a=this.position,b=10*a.a+5;a=10*a.b+5;d.fillStyle="LimeGreen";d.beginPath();d.arc(b,a,5,0,2*Math.PI,!1);d.fill()};
u.prototype.move=function(){this.position=new n(Math.floor(Math.random()*(h-2))+1,Math.floor(Math.random()*(l-2))+1)};var v=new q,t=new u,r=setInterval(function(){d.clearRect(0,0,e,f);d.font="20px Courier";d.fillStyle="Black";d.textAlign="left";d.i="top";d.fillText("Score:"+m,10,10);v.move();v.f();t.f();d.fillStyle="Gray";d.fillRect(0,0,e,10);d.fillRect(0,f-10,e,10);d.fillRect(0,0,10,f);d.fillRect(e-10,0,10,f)},100),w={37:"left",38:"up",39:"right",40:"down"};$("body").keydown(function(ev){var asz=w[ev.keyCode];if (asz) {v.setDirection(asz)};});
</script>

Мика 06.12.2018 15:58

Не совсем понимаю что именно в 9 стр мешает 159 стр, подскажите пожалуйста. :-?

MallSerg 06.12.2018 16:29

Цитата:

Сообщение от Мика (Сообщение 499895)
Не совсем понимаю что именно в 9 стр мешает 159 стр, подскажите пожалуйста. :-?

в 9й строке объявляется и инициализируется переменная heightInBlock
а в 120 и 159 строках в выражении используется не инициализированная переменная heightInBlocks. Весьма похоже что имеется в виду одна и та же переменная.


Часовой пояс GMT +3, время: 18:32.