Javascript-форум (https://javascript.ru/forum/)
-   Ваши сайты и скрипты (https://javascript.ru/forum/project/)
-   -   Cтранное поведение (https://javascript.ru/forum/project/72315-ctrannoe-povedenie.html)

рони 26.01.2018 21:02

Георгий777,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
#output {

  width:400px;
  height:400px;
  border-top: 1px solid gray;
  border-left: 1px solid gray;

}

.inner {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
  width:19px;
  height:19px;
  float: left;
}
  </style>


</head>

<body>
<div id="output"></div>
<script>
"use strict"
let fields = 20 * 20, min = 1, max = 400, i, div, x = 0, y = 0, flag = false, direction = 'right', ar = [];

function createMatrix() {
  let output = document.getElementById('output');

  for(i = 0; i < fields; i+=1) {
    div =  document.createElement('div');
    div.className = 'inner';
    output.appendChild(div);
    ar.push(div);
  }

}

createMatrix();

function setCell(num, val, eat) {
  let output = document.getElementById('output');
  let cell = output.children[num];

  if(val)
  	cell.style.backgroundColor = 'red';
  else
  	cell.style.backgroundColor = 'transparent';
  if(eat)
  	cell.style.backgroundColor = 'green';
}

function getCell(num) {
  return num;
}

//setCell(0, true);

function move() {

 for(i = 0; i < fields; i+=1) {
  	ar[i] = 0;
    setCell(ar[i], false);

    switch (direction) {
      case 'right': ar[i] = ar[i+1]; break;
      case 'left': ar[i] = ar[i-1]; break;
      //case 'up': x -= 20; break;
      //case 'down': x += 20; break;
  	}

    if(ar[i] < 0) ar[i] = 0;
  	if(ar[i] >= fields) ar[i] =  fields - 1;

    if(ar[i] == y) {
    	 setCell(ar[i], true);
       setCell(ar[i+1], true);
    }
    else  setCell(ar[i], true);
 }

}

function generateEat(min, max) {

  y = Math.floor(Math.random() * (max - min) + min);
  setCell(y, false, true);
  return y;
}

setInterval(move,500);

setInterval(generateEat(min,max),500);



document.onkeydown = function(e) {

  switch (e.keyCode) {

  	case 37: direction = 'left';break;
    case 38: direction = 'up';break;
    case 39: direction = 'right';break;
    case 40: direction = 'down';break;
  }
}



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

Георгий777 26.01.2018 22:01

не совсем понял - вы мне прислали код, но все работает также))

рони 26.01.2018 22:44

Цитата:

Сообщение от Георгий777
не совсем понял - вы мне прислали код, но все работает также))

... это была очередная попытка, показать вам правильно оформленный код...

рони 26.01.2018 22:48

игра змейка макет
 
Георгий777,

медитируйте ... окончание игры: когда змея укусит свой хвост... всё только для примера ... вариантов решений много...
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
#output {

  width:400px;
  height:400px;
  border-top: 1px solid gray;
  border-left: 1px solid gray;

}

.inner {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
  width:19px;
  height:19px;
  float: left;
}

.red{
   background-color: #FF0000;
}
.green{
  background-color: #008000;
}
</style>


</head>

<body>
<div id="output"></div>
<script>
"use strict"

var row = 20, col = 20, len = row * col, direction = "down", ar = [], snake = [], eat = [], timer;
function createMatrix() {
  var output = document.getElementById("output"), div, i;
  for (i = 0; i < len; i++) {
    div = document.createElement("div");
    div.className = "inner";
    output.appendChild(div);
    ar.push(div);
  }
}
createMatrix();
function rund(max) {
  return Math.floor(Math.random() * max);
}
function generatePoint() {
  var num = rund(len);
  snake.push(num);
  setCell(num, "red");
}
generatePoint();
function setCell(num, cls) {
  cls ? ar[num].classList.add(cls) : ar[num].className = "inner";
}
function generateEat() {
  var temp = ar.reduce(function(a, b, k) {
    b.classList.contains("red") || b.classList.contains("green") || a.push(k);
    return a;
  }, []);
  var num = temp[rund(temp.length)];
  eat.push(num);
  setCell(num, "green");
}
for (var i = 0; i < 50; i++) {
  generateEat();
}
function move() {
  var pointNext = snake[0];
  if (direction == "right") {
    pointNext += 1;
    if (pointNext % col == 0) {
      pointNext -= col;
    }
  }
  if (direction == "left") {
    if (pointNext % col == 0) {
      pointNext += col - 1;
    } else {
      pointNext -= 1;
    }
  }
  if (direction == "down") {
    pointNext += col;
    if (pointNext > len) {
      pointNext %= len;
    }
  }
  if (direction == "up") {
    pointNext -= col;
    if (pointNext < 0) {
      pointNext += len;
    }
  }
  if (ar[pointNext].classList.contains("green")) {
    eat = eat.filter(function(a) {
      a != pointNext;
    });
    snake.push(0);
  }
  if (ar[pointNext].classList.contains("red")) {
    alert("game over");
    return;
  }
  for (var i = 0; i < snake.length; i++) {
    var point = snake[i];
    setCell(point);
    snake[i] = pointNext;
    setCell(pointNext, "red");
    pointNext = point;
  }
  timer = window.setTimeout(move, 500);
}
move();
document.onkeydown = function(e) {
  switch(e.keyCode) {
    case 37:
      direction = "left";
      break;
    case 38:
      direction = "up";
      break;
    case 39:
      direction = "right";
      break;
    case 40:
      direction = "down";
      break;
  }
};
  </script>
</body>
</html>

Георгий777 28.01.2018 16:08

Здравствуйте, подскажите плиз, почему в функции move не удается ни установить флаг конца игры, ни изменить скорость игры-переменную speed, которая внизу передается как аргумент в setTimeout

<!DOCTYPE html>
[head]

  [style]
  #output {

  width:400px;
  height:400px;
  border-top: 1px solid gray;
  border-left: 1px solid gray;

}

.inner {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
  width:19px;
  height:19px;
  float: left;
}

.red{
   background-color: #FF0000;
}
.green{
  background-color: #008000;
}
[/style]
<body>
<div id="output"></div>
[script]
"use strict"

var row = 20, col = 20, len = row * col, direction = "down", ar = [], snake = [], eat = [], timer, score = 0, speed = 500, game_over = false;
function createMatrix() {
  var output = document.getElementById("output"), div, i;
  for (i = 0; i < len; i++) {
    div = document.createElement("div");
    div.className = "inner";
    output.appendChild(div);
    ar.push(div);
  }
}
createMatrix();
function rand(max) {
  return Math.floor(Math.random() * max);
}
function generatePoint() {
  var num = rand(len);
  snake.push(num);
  setCell(num, "red");
}
generatePoint();
function setCell(num, cls) {
  cls ? ar[num].classList.add(cls) : ar[num].className = "inner";
}
function generateEat() {
  var temp = ar.reduce(function(a, b, k) {
    b.classList.contains("red") || b.classList.contains("green") || a.push(k);
    return a;
  }, []);
  var num = temp[rand(temp.length)];
  eat.push(num);
  setCell(num, "green");
}
for (var i = 0; i < 50; i++) {
  //generateEat();
}
generateEat();
function move() {
  var pointNext = snake[0];
  if (direction == "right") {
    pointNext += 1;
    if (pointNext % col == 0) {
      pointNext -= col;
    }
  }
  if (direction == "left") {
    if (pointNext % col == 0) {
      pointNext += col - 1;
    } else {
      pointNext -= 1;
    }
  }
  if (direction == "down") {
    pointNext += col;
    if (pointNext > len) {
      pointNext %= len;
    }
  }
  if (direction == "up") {
    pointNext -= col;
    if (pointNext < 0) {
      pointNext += len;
    }
  }
  if (ar[pointNext].classList.contains("green")) {
    eat = eat.filter(function(a) {
      a != pointNext;
    });
    snake.push(0);
    generateEat();
    score++;
  }
  
  switch(score) {
    case 2:
      game_over = true;
      break;
    case 20:
      speed = 125;
      break;
    case 30:
      speed = 65;
      break;
  }
  
  
  if (ar[pointNext].classList.contains("red")) {
    game_over = true;
  }
  for (var i = 0; i < snake.length; i++) {
    var point = snake[i];
    setCell(point);
    snake[i] = pointNext;
    setCell(pointNext, "red");
    pointNext = point;
  }
  timer = window.setTimeout(move, speed);
}
move();

if(game_over == true) {
	alert("game over");
}
document.onkeydown = function(e) {
  switch(e.keyCode) {
    case 37:
      direction = "left";
      break;
    case 38:
      direction = "up";
      break;
    case 39:
      direction = "right";
      break;
    case 40:
      direction = "down";
      break;
  }
};
  [/script]
</body>

рони 28.01.2018 16:21

Георгий777,
вы с форматированием так специально? неужели так трудно использовать только один тег, для всей страницы, а не портить все теги.
[HTML run]код вашей страницы, скопируйте вашу страницу целиком, ничего не меняя[/HTML]

Георгий777 28.01.2018 16:25

<!DOCTYPE html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style>
  #output {

  width:400px;
  height:400px;
  border-top: 1px solid gray;
  border-left: 1px solid gray;

}

.inner {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
  width:19px;
  height:19px;
  float: left;
}

.red{
   background-color: #FF0000;
}
.green{
  background-color: #008000;
}
</style>
<body>
<div id="output"></div>
<script>
"use strict"

var row = 20, col = 20, len = row * col, direction = "down", ar = [], snake = [], eat = [], timer, score = 0, speed = 500, game_over = false;
function createMatrix() {
  var output = document.getElementById("output"), div, i;
  for (i = 0; i < len; i++) {
    div = document.createElement("div");
    div.className = "inner";
    output.appendChild(div);
    ar.push(div);
  }
}
createMatrix();
function rand(max) {
  return Math.floor(Math.random() * max);
}
function generatePoint() {
  var num = rand(len);
  snake.push(num);
  setCell(num, "red");
}
generatePoint();
function setCell(num, cls) {
  cls ? ar[num].classList.add(cls) : ar[num].className = "inner";
}
function generateEat() {
  var temp = ar.reduce(function(a, b, k) {
    b.classList.contains("red") || b.classList.contains("green") || a.push(k);
    return a;
  }, []);
  var num = temp[rand(temp.length)];
  eat.push(num);
  setCell(num, "green");
}
for (var i = 0; i < 50; i++) {
  //generateEat();
}
generateEat();
function move() {
  var pointNext = snake[0];
  if (direction == "right") {
    pointNext += 1;
    if (pointNext % col == 0) {
      pointNext -= col;
    }
  }
  if (direction == "left") {
    if (pointNext % col == 0) {
      pointNext += col - 1;
    } else {
      pointNext -= 1;
    }
  }
  if (direction == "down") {
    pointNext += col;
    if (pointNext > len) {
      pointNext %= len;
    }
  }
  if (direction == "up") {
    pointNext -= col;
    if (pointNext < 0) {
      pointNext += len;
    }
  }
  if (ar[pointNext].classList.contains("green")) {
    eat = eat.filter(function(a) {
      a != pointNext;
    });
    snake.push(0);
    generateEat();
    score++;
  }
  
  switch(score) {
    case 2:
      game_over = true;
      break;
    case 20:
      speed = 125;
      break;
    case 30:
      speed = 65;
      break;
  }
  
  
  if (ar[pointNext].classList.contains("red")) {
    game_over = true;
  }
  for (var i = 0; i < snake.length; i++) {
    var point = snake[i];
    setCell(point);
    snake[i] = pointNext;
    setCell(pointNext, "red");
    pointNext = point;
  }
  timer = window.setTimeout(move, speed);
}
move();

if(game_over == true) {
	alert("game over");
}
document.onkeydown = function(e) {
  switch(e.keyCode) {
    case 37:
      direction = "left";
      break;
    case 38:
      direction = "up";
      break;
    case 39:
      direction = "right";
      break;
    case 40:
      direction = "down";
      break;
  }
};
  </script>
</body>

рони 28.01.2018 16:34

Цитата:

Сообщение от Георгий777
не удается ни установить флаг конца игры

флаг устанавливается

Георгий777 28.01.2018 16:37

да, но алерт не выводится и скорость не изменяется, такое ощущение, что switch некорректен

рони 28.01.2018 16:46

Георгий777,
строка 133 никак не связана с изменением флага и с игрой, ей место в конце строки 121 и нужен return иначе бесконечный алерт

Георгий777 28.01.2018 17:39

а тогда что сделать, чтобы после алерта игра заново началась?

рони 28.01.2018 18:04

Георгий777,
строка 124
<!DOCTYPE html>
<html>
<head>

  <style>
  #output {

  width:400px;
  height:400px;
  border-top: 1px solid gray;
  border-left: 1px solid gray;

}

.inner {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
  width:19px;
  height:19px;
  float: left;
}

.red{
   background-color: #FF0000;
}
.green{
  background-color: #008000;
}
</style>
</head>
<body>
<div id="output"></div>
<script>
"use strict"

var row = 20, col = 20, len = row * col, direction = "down", ar = [], snake = [], eat = [], timer, score = 0, speed = 500, game_over = false;
function createMatrix() {
  var output = document.getElementById("output"), div, i;
  for (i = 0; i < len; i++) {
    div = document.createElement("div");
    div.className = "inner";
    output.appendChild(div);
    ar.push(div);
  }
}
createMatrix();
function rand(max) {
  return Math.floor(Math.random() * max);
}
function generatePoint() {
  var num = rand(len);
  snake.push(num);
  setCell(num, "red");
}
generatePoint();
function setCell(num, cls) {
  cls ? ar[num].classList.add(cls) : ar[num].className = "inner";
}
function generateEat() {
  var temp = ar.reduce(function(a, b, k) {
    b.classList.contains("red") || b.classList.contains("green") || a.push(k);
    return a;
  }, []);
  var num = temp[rand(temp.length)];
  eat.push(num);
  setCell(num, "green");
}
for (var i = 0; i < 50; i++) {
  //generateEat();
}
generateEat();
function move() {
  var pointNext = snake[0];
  if (direction == "right") {
    pointNext += 1;
    if (pointNext % col == 0) {
      pointNext -= col;
    }
  }
  if (direction == "left") {
    if (pointNext % col == 0) {
      pointNext += col - 1;
    } else {
      pointNext -= 1;
    }
  }
  if (direction == "down") {
    pointNext += col;
    if (pointNext > len) {
      pointNext %= len;
    }
  }
  if (direction == "up") {
    pointNext -= col;
    if (pointNext < 0) {
      pointNext += len;
    }
  }
  if (ar[pointNext].classList.contains("green")) {
    eat = eat.filter(function(a) {
      a != pointNext;
    });
    snake.push(0);
    generateEat();
    score++;
  }

  switch(score) {
    case 2:
      game_over = true;
      break;
    case 20:
      speed = 125;
      break;
    case 30:
      speed = 65;
      break;
  }
  console.log(score, speed)

if (ar[pointNext].classList.contains("red")) {
    game_over = true;
  }
if(game_over == true) {
  alert("game over");
  game_over = false
  score = 3;  // return;

}
  for (var i = 0; i < snake.length; i++) {
    var point = snake[i];
    setCell(point);
    snake[i] = pointNext;
    setCell(pointNext, "red");
    pointNext = point;
  }
  timer = window.setTimeout(move, speed);
}
move();


document.onkeydown = function(e) {
  switch(e.keyCode) {
    case 37:
      direction = "left";
      break;
    case 38:
      direction = "up";
      break;
    case 39:
      direction = "right";
      break;
    case 40:
      direction = "down";
      break;
  }
};
  </script>
</body>
</html>

Георгий777 28.01.2018 18:20

рони,

Георгий777 28.01.2018 18:22

Но теперь просто выводится постоянный алерт и игра не останавливается и не начинается заново

рони 28.01.2018 18:25

Георгий777,
строка 126 добавлена

Георгий777 28.01.2018 18:31

теперь он вроде начинает заново, но размер змеи - 3, а не один, как должен быть с начала

рони 28.01.2018 18:43

Георгий777,
нужно написать свой resetGame который сотрёт snake

Георгий777 28.01.2018 18:58

if(game_over == true) {
alert("game over");
game_over = false
score = 3; // return;
snake = [];
}

но так не помогает(

рони 28.01.2018 19:13

Георгий777, строка 120
<!DOCTYPE html>
<html>
<head>

  <style>
  #output {

  width:400px;
  height:400px;
  border-top: 1px solid gray;
  border-left: 1px solid gray;

}

.inner {
  border-bottom: 1px solid gray;
  border-right: 1px solid gray;
  width:19px;
  height:19px;
  float: left;
}

.red{
   background-color: #FF0000;
}
.green{
  background-color: #008000;
}
</style>
</head>
<body>
<div id="output"></div>
<script>
"use strict"

var row = 20, col = 20, len = row * col, direction = "down", ar = [], snake = [], eat = [], timer, score = 0, speed = 500, game_over = false;
function createMatrix() {
  var output = document.getElementById("output"), div, i;
  for (i = 0; i < len; i++) {
    div = document.createElement("div");
    div.className = "inner";
    output.appendChild(div);
    ar.push(div);
  }
}
createMatrix();
function rand(max) {
  return Math.floor(Math.random() * max);
}
function generatePoint() {
  var num = rand(len);
  snake.push(num);
  setCell(num, "red");
}
generatePoint();
function setCell(num, cls) {
  cls ? ar[num].classList.add(cls) : ar[num].className = "inner";
}
function generateEat() {
  var temp = ar.reduce(function(a, b, k) {
    b.classList.contains("red") || b.classList.contains("green") || a.push(k);
    return a;
  }, []);
  var num = temp[rand(temp.length)];
  eat.push(num);
  setCell(num, "green");
}
for (var i = 0; i < 50; i++) {
}
generateEat();
function move() {
  var pointNext = snake[0];
  if (direction == "right") {
    pointNext += 1;
    if (pointNext % col == 0) {
      pointNext -= col;
    }
  }
  if (direction == "left") {
    if (pointNext % col == 0) {
      pointNext += col - 1;
    } else {
      pointNext -= 1;
    }
  }
  if (direction == "down") {
    pointNext += col;
    if (pointNext > len) {
      pointNext %= len;
    }
  }
  if (direction == "up") {
    pointNext -= col;
    if (pointNext < 0) {
      pointNext += len;
    }
  }
  if (ar[pointNext].classList.contains("green")) {
    eat = eat.filter(function(a) {
      a != pointNext;
    });
    snake.push(0);
    generateEat();
    score++;
  }
  switch(score) {
    case 2:
      game_over = true;
      break;
    case 20:
      speed = 125;
      break;
    case 30:
      speed = 65;
      break;
  }
  if (ar[pointNext].classList.contains("red")) {
    game_over = true;
  }
  function resetGame() {
    snake.forEach(function(point) {
      setCell(point);
    });
    snake.length = 0;
    eat.forEach(function(point) {
      setCell(point);
    });
    eat.length = 0;
    generatePoint();
    generateEat();
  }
  if (game_over == true) {
    alert("game over");
    game_over = false;
    score = 0;
    resetGame();
  }
  for (var i = 0; i < snake.length; i++) {
    var point = snake[i];
    setCell(point);
    snake[i] = pointNext;
    setCell(pointNext, "red");
    pointNext = point;
  }

  timer = window.setTimeout(move, speed);
}
move();
document.onkeydown = function(e) {
  switch(e.keyCode) {
    case 37:
      direction = "left";
      break;
    case 38:
      direction = "up";
      break;
    case 39:
      direction = "right";
      break;
    case 40:
      direction = "down";
      break;
  }
};
  </script>
</body>
</html>

Георгий777 28.01.2018 19:19

спасибо большое, вы супер)


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