Форум программистов, компьютерный форум, киберфорум
JavaScript
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/3: Рейтинг темы: голосов - 3, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 01.06.2022
Сообщений: 5

Игра Змейка(на grid). Не могу понять, как добавить яблоки на поле и как их спавнить потом

20.06.2023, 13:44. Показов 639. Ответов 1

Студворк — интернет-сервис помощи студентам
Не могу понять, как добавить яблоки на поле и как их спавнить потом.
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Snake</title>
  <link rel="stylesheet" href="style.css">
</head>
<div class="game_over">
  <div class="wind">
    <h1>GAME OVER</h1>
    <p>Score: <span>0</span></p>
    <button>Restart</button>
  </div>
</div>
<div class="game">
 
</div>
 
<body>
  
  <div class="btn">
    <h2>Score: <span>0</span></h2>
    <button class="start">Start</button>
    <button class="stop">Stop</button>
  </div>
  <script src="classes.js"></script>
  <script src="script.js"></script>
</body>
 
</html>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
.game {
  position: relative;
  margin: 0 auto;
  padding: 2px;
  width: 600px;
  aspect-ratio: 1/1;
  border: 1px solid black;
 
  display: grid;
  grid-template-columns: repeat(21, 1fr);
  gap: 2px;
}
 
.cell {
  border: 3px solid gray;
  aspect-ratio: 1/1;
}
.cell-body {
  border-color: greenyellow;
  background-color: rgb(109, 160, 32);
}
.cell-apple {
  border-color: crimson;
  background-color: rgb(179, 20, 51);
}
.cell-poison {
  border-color: rgb(163, 20, 220);
  background-color: rgb(132, 14, 168);
}
.btn{
  display: flex;
  margin: 0 auto;
  margin-bottom: 10px;
  font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-size: 1.1em;
  display: flex;
  justify-content:center;
  width: 100%;
}
 
.start, .stop{
  padding: 12px;
  background-color: aquamarine;
  font-size: 1.2em;
  border-radius: 15%;
  margin: 10px;
  cursor: pointer;
  
}
 
.start:hover, .stop:hover{
  box-shadow: inset 0 0 2px;
  background-color: chartreuse;
}
 
.game_over{
  display: none;
  justify-content: center;
  position: absolute;
  flex-direction: column;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 255, 0.37);
  color: red;
  z-index: 1;
}
 
.wind{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 0 auto;
  font-size: 2em;
 
}
 
.wind > button{
  padding: 15px;
  background-color: rgb(17, 186, 130);
  width: 380px;
  cursor: pointer;
}
 
.wind > button:hover{
  box-shadow: inset 0 0 2px;
  background-color: chartreuse;
  
}
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const SIZE = 21;
 
 
const gameDiv = document.querySelector('.game');
 
let temp = '';
for (let i = 0; i < SIZE * SIZE; i++) {
  temp += '<div class="cell"></div>';
}
gameDiv.innerHTML = temp;
 
let cells = [];
for (let i = 0; i < SIZE; i++) {
  let temp = [];
  for (let j = 0; j < SIZE; j++) {
    temp.push(gameDiv.children[SIZE * i + j]);
  }
  cells.push(temp);
}
let field = new Field(SIZE, cells);
setInterval(() => {
  field.do();
}, 100);
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
let hor = 0;
let vert = -1;
let WIDTH = 21
let HEIGHT = 21
let add = false;
 
window.addEventListener('keydown', e => {
  if (e.code === 'KeyW' && vert === 0) { vert = -1; hor = 0; }
  if (e.code === 'KeyS' && vert === 0) { vert = 1; hor = 0; }
 
  if (e.code === 'KeyA' && hor === 0) { hor = -1; vert = 0; }
  if (e.code === 'KeyD' && hor === 0) { hor = 1; vert = 0; }
 
  if (e.code === 'KeyZ') add = true;
 
});
 
window.addEventListener('keyup', e => {
  if (e.code === 'KeyZ') add = false;
})
 
class BodyPart {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.lx = x;
    this.ly = y;
  }
}
 
class Snake {
  constructor(x, y, size) {
    this.parts = [new BodyPart(x, y)];
    this.head = this.parts[0];
    this.tail = this.parts[0];
    this.size = size;
  }
  
  move() {
    let newX = this.head.x + hor;
    let newY = this.head.y + vert;
 
    if (newX === this.size) newX = 0;
    else if (newX === -1) newX = this.size - 1;
    else if (newY === this.size) newY = 0;
    else if (newY === -1) newY = this.size - 1;
 
    for (let part of this.parts) {
      part.lx = part.x;
      part.ly = part.y;
 
      part.x = newX;
      part.y = newY;
 
      newX = part.lx;
      newY = part.ly;
    }
  }
 
  addPart() {
    let t = new BodyPart(this.tail.lx, this.tail.ly);
    this.tail = t;
    this.parts.push(t);
  }
 
 /* appleCon(){
    if (this.head === (this.apX, this.apY )){
      add= true 
      this.addPart()
    } 
  }*/
}
 
class Field {
 
  constructor(size, cells) {
    this.size = size;
    this.snake = new Snake(Math.floor(size / 2), Math.floor(size / 2), size);
    this.cells = cells;
   /* this.apple = new Apple(getRandomInt(1,21), getRandomInt(1,21), size)*/
    this.draw();
  }
 
  update() {
    this.snake.move();
 
    if (add) this.snake.addPart();
  }
 
  draw() {
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < this.size; j++) {
        this.cells[i][j].className = 'cell';
      }
    }
    this.snake.parts.forEach(part => {
      this.cells[part.y][part.x].classList.add('cell-body');
    });
  }
 
  do() {
    this.update();
    this.draw();
  }
}
 
class Apple{
  constructor(x, y, size) {
    this.apple = new ApplePart(x, y)
    this.size = size
  }}
 /* createNewApple(){
    let apple = new Apple(getRandomInt(1,21), getRandomInt(1,21));
}
}
 
 
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
  */
class ApplePart {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
20.06.2023, 13:44
Ответы с готовыми решениями:

Не могу понять почему останавливается игра Змейка
Здравствуйте! Написал змейку, весьма каряво, но как то написал. Нет только условия, если змейка врежется сама в себя. В общем проблема...

Змейка: Как сделать так, чтобы одни яблоки можно было есть, а вторые нет
void PlusJabloko(Game &amp;g) //Функция разброски яблок { int i,x,y; int n = g.gaduka.PCount; do { x = rand() % 56+3; // ...

Игра "змейка" - как рандомно размещать еду на поле
Привет! Я пытаюсь сделать змейку и змейка как ни странно ходит, шаг равен 120 пикселей(или как эта мера называется) и получается она ходит...

1
0 / 0 / 0
Регистрация: 01.06.2022
Сообщений: 5
26.06.2023, 09:33  [ТС]
Игра Змейка(на grid). Не могу понять, как добавить яблоки на поле. Выбивает нескончаемый список ошибок
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Snake</title>
  <link rel="stylesheet" href="style.css">
</head>
<div class="game_over">
  <div class="wind">
    <h1>GAME OVER</h1>
    <p>Score: <span>0</span></p>
    <button>Restart</button>
  </div>
</div>
<div class="stop_g">
  <div class="wind">
    <h1>YOU STOPED THE GAME</h1>
    <p>Score: <span id='score'>0</span></p>
    <button id="restart">Restart</button>
  </div>
</div>
<div class="game">
 
</div>
<div class="level"><h1>LEVEL <span id="level">1</span></h1></div>
 
<body>
  
  <div class="btn">
    <h2>Score: <span>0</span></h2>
    <button class="start">Start</button>
    <button class="stop">Stop</button>
   
  </div>
  <script src="classes.js"></script>
  <script src="script.js"></script>
</body>
 
</html>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
.game {
  position: relative;
  margin: 0 auto;
  padding: 2px;
  width: 600px;
  aspect-ratio: 1/1;
  border: 1px solid black;
 
  display: grid;
  grid-template-columns: repeat(21, 1fr);
  gap: 2px;
}
 
.cell {
  border: 3px solid gray;
  aspect-ratio: 1/1;
}
.cell-body {
  border-color: greenyellow;
  background-color: rgb(109, 160, 32);
}
.cell-apple {
  border-color: crimson;
  background-color: rgb(179, 20, 51);
}
.cell-poison {
  border-color: rgb(163, 20, 220);
  background-color: rgb(132, 14, 168);
}
.btn{
  display: flex;
  margin: 0 auto;
  margin-bottom: 10px;
  font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-size: 1.1em;
  display: flex;
  justify-content:center;
  width: 100%;
}
 
.start, .stop{
  padding: 12px;
  background-color: aquamarine;
  font-size: 1.2em;
  border-radius: 15%;
  margin: 10px;
  cursor: pointer;
  
}
 
.start:hover, .stop:hover{
  box-shadow: inset 0 0 2px;
  background-color: chartreuse;
}
 
.game_over{
  display: none;
  justify-content: center;
  position: absolute;
  flex-direction: column;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 255, 0.37);
  color: red;
  z-index: 1;
}
 
.wind{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 0 auto;
  font-size: 2em;
 
}
 
.wind > button{
  padding: 15px;
  background-color: rgb(17, 186, 130);
  width: 380px;
  cursor: pointer;
}
 
.wind > button:hover{
  box-shadow: inset 0 0 2px;
  background-color: chartreuse;
  
}
 
.level{
  display: flex;
  justify-content: center;
  align-items: center;
  font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
 
.stop_g{
  display: none;
  justify-content: center;
  position: absolute;
  flex-direction: column;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 255, 0.37);
  color: red;
  z-index: 1;
}
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
let hor = 0;
let vert = -1;
let WIDTH = 21
let HEIGHT = 21
let add = false;
let score = 0
let level = document.querySelector("#level")
let Score = document.querySelector("#score")
const Restart = document.querySelector('#restart')
const Start = document.querySelector('.start')
const Stop = document.querySelector('.stop')
 
window.addEventListener('keydown', e => {
  if (e.code === 'KeyW' && vert === 0) {
    vert = -1;
    hor = 0;
  }
  if (e.code === 'KeyS' && vert === 0) {
    vert = 1;
    hor = 0;
  }
 
  if (e.code === 'KeyA' && hor === 0) {
    hor = -1;
    vert = 0;
  }
  if (e.code === 'KeyD' && hor === 0) {
    hor = 1;
    vert = 0;
  }
 
 
});
 
 
 
class BodyPart {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.lx = x;
    this.ly = y;
  }
}
 
class Snake {
  constructor(x, y, size) {
    this.parts = [new BodyPart(x, y)];
    this.head = this.parts[0];
    this.tail = this.parts[0];
    this.size = size;
  }
 
  move() {
    let newX = this.head.x + hor;
    let newY = this.head.y + vert;
 
    if (newX === this.size) newX = 0;
    else if (newX === -1) newX = this.size - 1;
    else if (newY === this.size) newY = 0;
    else if (newY === -1) newY = this.size - 1;
 
    for (let part of this.parts) {
      part.lx = part.x;
      part.ly = part.y;
 
      part.x = newX;
      part.y = newY;
 
      newX = part.lx;
      newY = part.ly;
    }
  }
 
  addPart() {
    let t = new BodyPart(this.tail.lx, this.tail.ly);
    this.tail = t;
    this.parts.push(t);
  }
 
  /*appleCon() {
    if (this.head === this.apple) {
      add = true
      this.addPart()
      score += 1
      Score = score
 
    }
    if (score === 10) {
      score = 0
      level += 1
    }
 
  }*/
  isAteSelf() {
    let isDead = false
    this.parts.forEach(tail => {
      if (this.tail != 0 && tail.x === this.parts[0].x && tail.y === this.parts[0].y) {
        isDead = true
        window.classList.add('.game_over')
      }
    })
  }
}
 
class Field {
 
  constructor(size, cells) {
    this.size = size;
    this.snake = new Snake(Math.floor(size / 2), Math.floor(size / 2), size);
    this.cells = cells;
    this.apple = new Apple(Math.round(Math.random() * (WIDTH - 1)), Math.round((Math.random() * (HEIGHT - 1)), size))
    this.draw();
    this.apples = [new ApplePart(Math.round(Math.random() * (WIDTH - 1)), Math.round((Math.random() * (HEIGHT - 1)), size))];
    setInterval(this.createApple.bind(this), 3000);
  }
 
  createApple() {
    // случайные координаты
    this.apples.x = Math.round(Math.random() * (WIDTH - 1))
    this.apples.y = Math.round((Math.random() * (HEIGHT - 1)), size)
    // создаешь яблоко 
    this.apples.push(new ApplePart(this.apples.x , this.apples.y))
  }
 
  update() {
    this.snake.move();
     for (this.apple in this.apples) {
     if (this.apple == this.snake){
        this.snake.addPart()
      delete this.apple
     
     }
    // если столкнулся с яблоком:
    //                удаляешь яблоко
    //                увеличиваешь змейку
  }
 
  draw(){
    // for apples draw apple
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < this.size; j++) {
        this.cells[i][j].className = 'cell';
      }
    }
    this.snake.parts.forEach(part => {
      this.cells[part.y][part.x].classList.add('cell-body');
    });
   /* for (let i = 0; i < 10; i++) {
      this.apple = new Apple(Math.round(Math.random() * (WIDTH - 1)), Math.round((Math.random() * (HEIGHT - 1))))
    }*/
    /* this.apple.forEach(this.apple =>{
 
     })*/
 
  }
 
  do(){
    this.update();
    this.draw()
  }
}
 
class Apple {
  constructor(x, y, size) {
    this.apple = new ApplePart(x, y)
    this.size = size
  }
 /* createNewApple() {
    for (let i = 0; i < 10; i++) {
      this.apple = new Apple(Math.random(WIDTH), Math.random(HEIGHT))
    }
  }*/
 
}
 
 
 
class ApplePart {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
 
 
Start.addEventListener('onclick', () => {
 
})
 
 
 
const SIZE = 21;
 
 
const gameDiv = document.querySelector('.game');
 
let temp = '';
for (let i = 0; i < SIZE * SIZE; i++) {
  temp += '<div class="cell"></div>';
}
gameDiv.innerHTML = temp;
 
let cells = [];
for (let i = 0; i < SIZE; i++) {
  let temp = [];
  for (let j = 0; j < SIZE; j++) {
    temp.push(gameDiv.children[SIZE * i + j]);
  }
  cells.push(temp);
}
let field = new Field(SIZE, cells);
setInterval(() => {
  field.do();
}, 100);
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
26.06.2023, 09:33
Помогаю со студенческими работами здесь

Игра змейка, как добавить функцию "Начать игру заново"?
from tkinter import * import random # ширина экрана WIDTH = 800 # высота экрана HEIGHT = 600 # размер сегмента змейки ...

Игра "Змейка". Как добавить ей тело и чтобы оно равно количеству съеденной цифры
Всем доброе время суток) пишу программу на c# змейка и никак не могу понять как добавить ей тело и чтоб змейки была равно количеству...

Сайт на Ucoze, не могу понять как добавить код
Всем привет, в веб программирование я полный ноль) Прошу помочь http://1a-med.ru/publ/vrachi/vrachi/khalilova_oksana_romanovna/18-1-0-38 ...

Не могу понять как добавить id в одной таблице в другую
У меня есть две таблицы, мне нужно id с одной таблицы добавить в другую таблицу при нажатии другой кнопки, если быть точнее есть страница...

Игра змейка. Не выводится еда на поле
Почемуто не выводится еда на поле из класса &quot;food&quot; #include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;cstring&gt; using...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США. Нашел на реддите интересную статью под названием «Кто-нибудь знает, где получить бесплатный компьютер или. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru