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

Кто может сделать разбор ошибок?

20.05.2019, 19:13. Показов 378. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Решил попробовать написать что-то на js, вчера написал игрушку ''2048'', я в вебе не профи, и уверен что там много "Говно-кода".
Может тут есть те, кто разберет и объяснит, как не нельзя писать и где "Говно-код", какие ошибки, что лучше было бы использовать и тд. Просто хочу прокачаться в этом плане.
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
42
43
44
45
46
47
48
49
50
51
52
53
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JS lessen</title>
    <link rel = "stylesheet" href="css/style.css"/>
  </head>
 
  <body>
    <div class="bod">
 
        <div class="pole" >
            <div class="Sinform"> CЧЕТ <br> <p id="score" class="score">0</p> </div>
            <div class="Rinform"> РЕКОРД <br> <p id="recordScore" class="recordScore">0</p> </div>
            
            <div id="arr0_0" class="array"></div>
            <div id="arr0_1" class="array"></div>
            <div id="arr0_2" class="array"></div>
            <div id="arr0_3" class="array"></div>
            <div id="arr1_0" class="array"></div>
            <div id="arr1_1" class="array"></div>
            <div id="arr1_2" class="array"></div>
            <div id="arr1_3" class="array"></div>
            <div id="arr2_0" class="array"></div>
            <div id="arr2_1" class="array"></div>
            <div id="arr2_2" class="array"></div>
            <div id="arr2_3" class="array"></div>       
            <div id="arr3_0" class="array"></div>
            <div id="arr3_1" class="array"></div>
            <div id="arr3_2" class="array"></div>
            <div id="arr3_3" class="array"></div>
        
        </div>
    </div>
 
    <div id="modal" class="modal2">
        <div class="modal2__overlay">
            <div class="modal2__body">
                <div class="menuSinform"> CЧЕТ <br> <p id="mScore" class="score">0</p> </div>
                <div class="menuRinform"> РЕКОРД <br> <p id="mRecordScore" class="recordScore">0</p> </div>
                    
                <div class="textStart" id="textStart">
                    Попробуй набрать 2048!
                </div>
                <div class="buttonStart">
                    <a href="#" id="buttonStart">НАЧАТЬ ИГРУ!</a>
                </div>
            </div>
        </div>
    </div>
    <script src="js/main.js"></script>
  </body>
</html>
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
var mousX,mousY;
var score = 0, record =0 ;
var gameOver = true;
var noMove = false;
 
    document.getElementById('modal').classList.add("show");
    //document.getElementById('modal').classList.remove("show");
 
document.getElementById('buttonStart').onclick = function(){
gameOver = false;
document.getElementById('modal').classList.remove("show");
}
 
 
function calcDirect(){
    var initX, initY, fourth, direct;
    initX = mouseupX - mousedownX;
    initY = mouseupY - mousedownY;
 
    if ((initX < 20 && initX > -20) && (initY < 20 && initY > -20)){
        
    return false;
    }
 
    if (initX >= 0 && initY >= 0){
        fourth = 4;
 
 
        if (initX <= initY){
            direct = 3;
        } else {
            direct = 2;
        }
    } else 
 
    if (initX <= 0 && initY >= 0){
        fourth = 2;
        if (initX *-1 <= initY){
            direct = 3;
        } else {
            direct = 4;
        }
    }else 
 
    if (initX <= 0 && initY <= 0){
        fourth = 3;
        if (initX* -1 <= initY* -1){
            direct = 1;
        } else {
            direct = 4;
        }
    }else 
 
    if (initX >= 0 && initY <= 0){
        fourth = 1;
        if (initX <= initY*-1){
            direct = 1;
        } else {
            direct = 2;
        }
    }
    return direct;
}
 
 
 
 
function fixEvent(e) {
            // получить объект событие для IE
            e = e || window.event
 
            // добавить pageX/pageY для IE
            if ( e.pageX == null && e.clientX != null ) {
                var html = document.documentElement
                var body = document.body
                e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0)
                e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0)
            }
 
            // добавить which для IE
            if (!e.which && e.button) {
                e.which = e.button & 1 ? 1 : ( e.button & 2 ? 3 : ( e.button & 4 ? 2 : 0 ) )
            }
 
            return e
        }
 
function mouseMove(event){
    event = fixEvent(event);
    mousX = event.pageX;
    mousY = event.pageY;
}
 
document.onmousemove = mouseMove
 
var mousedownX, mousedownY, mouseupX, mouseupY;
 
var arr_1 = new Array();
var arr_2 = new Array();
var arr_3 = new Array();
var arr_4 = new Array();
 
 
for (var i = 0; i<4;i++) arr_1[i]= 0;
for (var i = 0; i<4;i++) arr_2[i]= 0;
for (var i = 0; i<4;i++) arr_3[i]= 0;
for (var i = 0; i<4;i++) arr_4[i]= 0;
var arr = new Array(arr_1,arr_2,arr_3,arr_4);
 
function randomInteger(min, max) {
    var rand = min - 0.5 + Math.random() * (max - min + 1)
    rand = Math.round(rand);
    return rand;
}
 
function reloadGame (){
    score = 0;
    for (var i = 0; i < 4; i++){
        for (var j = 0; j < 4; j++){
            arr[i][j] = 0;
        }
    }
    document.getElementById('score').innerHTML = '0';
    document.getElementById('score').style.fontSize = '32px';
    fullingObj();
    print();
} 
 
function checkGameOver(){
 
    var countMove = 0;
    for (var k = 1; k<4;k++){
        for (var j = 0; j<4;j++){
 
            if (arr[k][j] !=  0 && arr[k-1][j] == 0 ){
                countMove++;
            } else if (arr[k][j] !=  0 && arr[k-1][j] ==  arr[k][j]){
                countMove++;
            }
 
            if (arr[j][k] !=  0 && arr[j][k-1] == 0 ){
                countMove++;
            } else if (arr[j][k] !=  0 && arr[j][k-1] ==  arr[j][k]){
                countMove++;
            }
        }
    }
 
 
    if (countMove == 0 ) {
        console.log("GAME OVER");
        document.getElementById('textStart').innerHTML = "Game Over";
        document.getElementById('textStart').fontSize = '40px';
        document.getElementById('buttonStart').innerHTML = "Начать заново!";
        document.getElementById('modal').classList.add("show");
        document.getElementById('mScore').innerHTML = score;
        document.getElementById('mRecordScore').innerHTML = record;
 
        gameOver = true;
        reloadGame ();
        
    }
}
 
 
function searchFull(){
    var countObj = 0;
    for (var i = 0; i < 4;i++){
        for (var j = 0; j< 4;j++){
            if (arr[i][j] != 0 ){
                countObj++
            }
        }
    }
    console.log('check   ' + countObj);
    if (countObj == 16){
        checkGameOver()
    }
    return countObj;
}
 
function fullingObj(){
    var rNum_1,rNum_2;
    var flag = false;
    if (searchFull() < 16) {
        while (flag == false){
            rNum_1 = randomInteger(0, 3);
            rNum_2 = randomInteger(0, 3);
            if  (arr[rNum_1][rNum_2] == 0){
                arr[rNum_1][rNum_2] = 2;
                score = score + 2;
                flag = true;
            } else {
                flag = false;
            }
        }
    }
}
 
 
var checkMove = false;
function moveObj(direct){
 
    for (var i = 0; i < 3;i++){
        for (var k = 1; k<4;k++){
            for (var j = 0; j<4;j++){
                if (direct == 1){
                    if (arr[k][j] !=  0 && arr[k-1][j] == 0 ){
                        arr[k-1][j] = arr[k][j];
                        arr[k][j] = 0;
                        checkMove = true;
 
                    } else if (arr[k][j] !=  0 && arr[k-1][j] ==  arr[k][j]){
                        arr[k-1][j] = arr[k][j] * 2;
                        arr[k][j] = 0;
                        checkMove = true;
                        score = score + (arr[k-1][j]);
                    }
                } else if (direct == 4){
                    if (arr[j][k] !=  0 && arr[j][k-1] == 0 ){
                        arr[j][k-1] = arr[j][k];
                        arr[j][k] = 0;
                        checkMove = true;
                    } else if (arr[j][k] !=  0 && arr[j][k-1] ==  arr[j][k]){
                        arr[j][k-1] = arr[j][k] * 2;
                        arr[j][k] = 0;
                        checkMove = true;
                        score = score + (arr[j][k-1])
                    }
                }   else if (direct == 3){
                    if (arr[3-k][j] !=  0 && arr[3-k+1][j] == 0 ){
                        arr[3-k+1][j] = arr[3-k][j];
                        arr[3-k][j] = 0;
                        checkMove = true;
                    } else if (arr[3-k][j] !=  0 && arr[3-k+1][j] ==  arr[3-k][j]){
                        arr[3-k+1][j] = arr[3-k][j] * 2;
                        arr[3-k][j] = 0;
                        checkMove = true;
                        score = score + (arr[3-k+1][j])
                    }
                }   else if (direct == 2){
                    if (arr[j][3-k] !=  0 && arr[j][3-k+1] == 0 ){
                        arr[j][3-k+1] = arr[j][3-k];
                        arr[j][3-k] = 0;
                        checkMove = true;
                    } else if (arr[j][3-k] !=  0 && arr[j][3-k+1] ==  arr[j][3-k]){
                        arr[j][3-k+1] = arr[j][3-k] * 2;
                        arr[j][3-k] = 0;
                        checkMove = true;
                        score = score + (arr[j][3-k+1])
                    }
                }
            }   
        }
    }
}
 
function print(){
    for (var i = 0; i < 4; i++){
        for (var j = 0; j < 4; j++){
            if (arr[i][j] != 0){
                document.getElementById('arr'+i+'_'+j+'').innerHTML = arr[i][j];        
            }else {
                document.getElementById('arr'+i+'_'+j+'').innerHTML = "";
                document.getElementById('arr'+i+'_'+j+'').style.background = "#C7BAAE";
 
            }
            if (arr[i][j] > 4){
            document.getElementById('arr'+i+'_'+j+'').style.color = "#fff";}
            else{ document.getElementById('arr'+i+'_'+j+'').style.color = "#68645B";}
 
 
            if (arr[i][j] > 128 && arr[i][j] < 1024){
                document.getElementById('arr'+i+'_'+j+'').style.fontSize = '18px';}
             else if (arr[i][j] > 512){document.getElementById('arr'+i+'_'+j+'').style.fontSize = '14px'
            }else 
                {document.getElementById('arr'+i+'_'+j+'').style.fontSize = '22px'}
 
 
            if (arr[i][j] == 2){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#E7DED4";
            } else if (arr[i][j] == 4){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#F1E3CA";
            }else if (arr[i][j] == 8){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#FFB278";         
            }else if (arr[i][j] == 16){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#FF9560";
            }else if (arr[i][j] == 32){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#FF7B5C";
            }else if (arr[i][j] == 64){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#FF7B5C";
            }else if (arr[i][j] == 128){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#F9D06D";
            }else if (arr[i][j] == 256){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#F8CA41";
            }else if (arr[i][j] == 512){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#E8A826";
            }else if (arr[i][j] == 1024){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#5DD38E";
            }else if (arr[i][j] == 2048){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#579DE0";
            }else if (arr[i][j] == 4096){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#127DC8";
            }else if (arr[i][j] == 8192){
                document.getElementById('arr'+i+'_'+j+'').style.background = "#9200F8";
            }
        }
    }
}
 
function printScore (){
    document.getElementById('score').innerHTML = score;
 
    if (record <= score){
    record = score;
    document.getElementById('recordScore').innerHTML = record;
    }
 
    if (score > 999){
        document.getElementById('score').style.fontSize = '26px';
        document.getElementById('recordScore').style.fontSize = '26px';
    } else if (score > 9999){
        document.getElementById('score').style.fontSize = '22px' ;
        document.getElementById('recordScore').style.fontSize = '22px' ;
 
    }
 
}
 
fullingObj();
print();
 
 
document.onmousedown = function() {
    mousedownX = mousX;
    mousedownY = mousY;
    
   // document.getElementById('mouseY').value = mousedownY;
 
}
 
 document.onmouseup = function(){
    mouseupX = mousX;
    mouseupY = mousY;
    
        calcDirect();
        moveObj(calcDirect());
 
    
    
 
        if (calcDirect() >0 ){
            
            fullingObj();
            checkMove = false;
            print();
            printScore();
        }
}
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
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
body{
    margin: 0;
        -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}
 
.bod{
    text-align: center;
    height: 100%
    width:100%;
 
}
 
.pole{
    display: inline-block;
    text-align: center;
    margin: 250px; 
    padding: 4px;
 
    width: 208px;
    height: 208px;
    border-radius: 3px;
    background-color: #B3A699;
}
 
.array{
    line-height:50px;
    font-size: 22px;
    float: left;
    width: 50px;
    height: 50px;
    margin: 1px;
    background-color: #C7BAAE;
    display: block;
    border-radius: 3px;
    text-align: center;
    color: #68645B;
    vertical-align: middle;
    
 
}
 
.Sinform{
    display: block;
    text-align: center;
    margin: -68px 0 0 106px; 
    border-radius: 6px;
    font-size: 17px;
    color: #fff;
    background-color: #B5A79B;
    height: 60px;
    width: 105px;
}
 
.Rinform{
    display: block;
    text-align: center;
    margin: -60px 0px 0 -4px; 
    border-radius: 6px;
    font-size: 17px;
    color: #fff;
    background-color: #B5A79B;
    height: 60px;
    width: 105px;
}
.recordScore{
    font-size: 32px;
    margin-top: 0px;
}
#score{
    font-size: 32px;
    margin-top: 0px;
}
#mScore {
    font-size: 32px;
    margin-top: 0px;
}
 
.modal2 {
    text-align: center;
    display: none;
    z-index: 1000;
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}
 
.modal2__overlay {
    background: rgba(0,0,0,0.8);
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}
 
.modal2__body {
    display: inline-block;
    text-align: center;
    width: 350px;
    height: 200px;
    position: fixed;
    left: 50%;
    top: 50%;
    background: #fff;
    margin-left: -175px;
    margin-top: -200px;
    border-radius: 5px;
    box-shadow: 0 0 50px black;
}
 
.show {
    display: block !important;
}
 
.menuSinform{
 
    display: inline-block;
    text-align: center;
    margin: 5px 0 0 0px; 
    border-radius: 6px;
    font-size: 17px;
    color: #fff;
    background-color: #B5A79B;
    height: 60px;
    width: 105px;
}
.menuRinform{
    display: inline-block;
    text-align: center;
    margin: 5px 0px 0 0px; 
    border-radius: 6px;
    font-size: 17px;
    color: #fff;
    background-color: #B5A79B;
    height: 60px;
    width: 105px;
}
 
.buttonStart{
    line-height:35px;
    display: inline-block;
    text-align: center;
    margin: 10px 30px;
    width: 200px;
    height: 35px;
    background: #F9D06D;
    border-radius: 5px;
    color: #68645B;
}
 
.textStart{
    display: inline-block;
    width: 250px;
    height: 35px;
    color: #68645B;
    font-size: 25px;
    text-align: center;
}
a{
    text-decoration: none;
    color: #68645B;
    font-size: 16px;
}
#buttonStart{
    
    width: 200px;
    height: 35px;
}
Вот ссылка на код: http://jsfiddle.net/kzmxheba/
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
20.05.2019, 19:13
Ответы с готовыми решениями:

Кто может сделать календарь?
с элементами просмотра месяцев выпадающий с кнопками вперёд/назад и полем ввода для года и тоже с...

Не могу сделать, посмотрите может кто знает как сделать
построить формулу для определения зависимости y от x с использованием логических функций: и, или,...

Кто может сделать проект по курсовой. Нужно сделать программу на сжатие картинки
Нужен полный проэкт (исходники и exe)

1
 Аватар для Leo Leo
25 / 19 / 6
Регистрация: 19.05.2019
Сообщений: 38
20.05.2019, 19:33
Недурно сделано. Поначалу немного непонятно как начать играть, потом ясно стало. Делалось для тач-девайсов? Можно добавить сохранение рекордов в localstorage или куку ради разнообразия
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
20.05.2019, 19:33
Помогаю со студенческими работами здесь

Кто может сделать?
Описать статический массив. Реализовать 2 способа инициализации массива (пользователь может сам...

кто может сделать?
Учусь на индивидуальном, толком нам ничего не розсказали, а задания дали сделать до понедельника,...

кто может сделать?
Язык форума - русский. читайте правила форума. 1.4.Официальными языками форума являются русский и...

Может кто сделать?
Может кто сделать примеры на sql название таблиц можете от себя придумать 1)Выбрать всю...

При компиляции программа не выдаёт ошибок, но в итоге ничего не может сделать
Добрый день! Пишу программу на Delphi. Почему-то при запуске появляется форма со всеми...


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

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а привычная функция main(). . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru