Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.69/13: Рейтинг темы: голосов - 13, средняя оценка - 4.69
8 / 8 / 6
Регистрация: 21.04.2018
Сообщений: 142

"Морской Бой": найти причины возникновения ошибок в коде

15.07.2018, 18:05. Показов 2917. Ответов 22

Студворк — интернет-сервис помощи студентам
Доброго добра Всем тем, кто сейчас зашёл на эту страницу. Помогите понять, почему arr1 и arr2 в вызовах функций Create_table1,2 и Print_table1,2 выдают ошибки. Сам найти не могу:
C++
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
#include<iostream>
#include<ctime>
#include<iomanip>
#include<string>
#include<Windows.h>
using namespace std;
 
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
 
/*
Чутка алгоритма:
 
    1) Рисование таблицы 10х10 (сначала по фасту: важна сама игра пока-что)
    2) Никнеймы игроков
    3) Организация расстановки кораблей первого игрока
    4) Скрывание рассположения кораблей первого игрока
    5) Повтор 1-го и 2-го шагов для второго игрока
    6) Ходы игроков и их условия:
        а) Попадание по кораблю соперника
        б) Попадание "мимо"
        в) Попадание по клетке, которой не существует
        г) Попадание по клетке, которая "заюзана"
    7) Условие победы
    8) Звуки
    9) Дорисовка таблицы (для эстэтики)
    10) Придавание стиля самой игре
 
    Нечётные клетки поля относятся к первому игроку
    Чётные - ко второму
 
 
*/
 
// Имена
 
//void Players_names(char* Player1, char* Player2) {
//
//  cout << "Введите имя";
//  SetConsoleTextAttribute(h, 3);
//  cout << "первого";
//  SetConsoleTextAttribute(h, 7);
//  cout << "игрока() : ";
//
//  cin.ignore(100, '\n');
//  cin.getline(Player1, 100);
//
//  cout << "Введите имя ";
//  SetConsoleTextAttribute(h, 4);
//  cout << "второго";
//  SetConsoleTextAttribute(h, 7);
//  cout << "игрока() : ";
//
//  cin.ignore(100, '\n');
//  cin.getline(Player2, 100);
//}
 
void Create_table1(char arr1[10][10]) {
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            arr1[i][j] = '1';
        }
    }
 
}
 
void Create_table2(char arr2[10][10]) {
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            arr2[i][j] = '2';
        }
    }
}
 
void Set_ships_for_P1(char arr1[10][10]) {
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
 
 
 
 
        }
    }
 
 
}
 
void Set_ships_for_P2(char arr2[10][10]) {
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
 
 
 
 
        }
    }
 
 
}
 
void Print_table1(char arr1[][10]) {
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            cout << arr1[i][j];
        }
        cout << endl;
    }
}
 
void Print_table2(char arr2[][10]) {
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            cout << arr2[i][j];
        }
        cout << endl;
    }
}
 
void Hide_table1(char arr1[]) {
 
}
 
void Hide_table2(char arr2[]) {
 
}
 
void Player1_move(char arr1[], char arr2[]) {
 
}
 
void Player2_move(char arr1[], char arr2[]) {
 
}
 
 
 
 
 
void main()
{
    srand(time(0));
    setlocale(LC_ALL, "Russian");
 
    char arr1[10];
    char arr2[10];
 
    /*char* Player1[100];
    char* Player2[100];
 
    Players_names(*Player1, *Player2);
    
    cout << "Имя первого игрока: " << Player1 << endl;
    cout << "Имя второго игрока" << Player2 << endl;*/
 
    Create_table1(arr1);
    Create_table2(arr2);
    Print_table1(arr1);
    Print_table2(arr2);
 
 
 
 
 
}
Добавлено через 3 минуты
Кстати, и с именами игроков помогите разобраться: ошибки в Players_names.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
15.07.2018, 18:05
Ответы с готовыми решениями:

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

Найти причины возникновения ошибок в коде и исправить эти ошибки
Имеется две формулы (поиск следующего приближения для метода SOR): ...

Найти причины возникновения ошибок в коде и исправить эти ошибки
Уважаемые пользователи просьба помочь с одной проблемой,смысл в том что при создании записи она потом не отображается в выводе,тобишь в...

22
8 / 8 / 6
Регистрация: 21.04.2018
Сообщений: 142
22.07.2018, 12:47  [ТС]
Студворк — интернет-сервис помощи студентам
Такая канитель: в Set_ships сделал я условия несоприкосновения кораблей друг с другом, но оно хоть и работает, но так, что условие диагоналей (первый if с Cell_checker) работает, а торпедные корабли ставятся бесконечно, при том, что amount_of_checked_cells считает кол-во клеток кораблей... Условия с крейсерами и линкорами недоработанно, проблема с торпедными катерами. В чём причина? Я вообще не понимаю....
C++
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#include<iostream>
#include<ctime>
#include<iomanip>
#include<string>
#include<Windows.h>
#include<windows.h>
using namespace std;
 
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
#define _CRT_NO_SECURITY_WARNINGS
 
const int FIELD_SIZE = 10;
 
char Player1[100];
char Player2[100];
 
int amount_of_ship_cells_left_to_drown_P1;
int amount_of_ship_cells_left_to_drown_P2;
 
// [x][y], где x - вертикаль, y - горизонталь
 
char WaterP1 = '~';
char WaterP2 = '~';
char TorpedeP1 = 'Т';
char TorpedeP2 = 'Т';
char DestroyerP1 = 'К';
char DestroyerP2 = 'К';
char CruiserP1 = 'Э';
char CruiserP2 = 'Э';
char BattleshipP1 = 'Л';
char BattleshipP2 = 'Л';
char ShipHitP1 = 'Х';
char ShipHitP2 = 'X';
char HitMissP1 = '*';
char HitMissP2 = '*';
 
void ifP1Win(char* p1) {
    system("cls");
    cout << "Игрок " << p1 << " ПОБЕДИЛ!!! Поздравляем!" << endl;
    system("pause");
}
 
void ifP2Win(char* p2) {
    system("cls");
    cout << "Игрок " << p2 << " ПОБЕДИЛ!!! Поздравляем!" << endl;
    system("pause");
}
 
bool Cell_checker(int PlayerNumber, int asked_cell) {
 
    char T;
    char D;
    char C;
    char BS;
 
    switch (PlayerNumber)
    {
    case 1:
    {
        T = TorpedeP1;
        D = DestroyerP1;
        C = CruiserP1;
        BS = BattleshipP1;
    } break;
 
    case 2:
    {
        T = TorpedeP2;
        D = DestroyerP2;
        C = CruiserP2;
        BS = BattleshipP2;
    } break;
 
    }
 
    if (asked_cell == T || asked_cell == D || asked_cell == C || asked_cell == BS)
        return true;
    else
        return false;
}
 
void Print_table(char arr[][FIELD_SIZE]) {
    for (int i = 0; i < FIELD_SIZE; i++)
    {
        for (int j = 0; j < FIELD_SIZE; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
 
void Print_hidden_table(char arr[][FIELD_SIZE]) {
    for (int i = 0; i < FIELD_SIZE; i++)
    {
        for (int j = 0; j < FIELD_SIZE; j++)
        {
            cout << '~' << " ";
        }
        cout << endl;
    }
}
 
 
void Players_names(char* Player1, char* Player2) {
 
    cout << "Введите имя ";
    SetConsoleTextAttribute(h, 3);
    cout << "первого";
    SetConsoleTextAttribute(h, 7);
    cout << " игрока() : ";
 
    cin >> Player1;
 
    cout << "Введите имя ";
    SetConsoleTextAttribute(h, 4);
    cout << "второго";
    SetConsoleTextAttribute(h, 7);
    cout << " игрока() : ";
 
    cin >> Player2;
 
}
 
void Create_table(char arr[][FIELD_SIZE], char c) {
    for (int i = 0; i < FIELD_SIZE; i++)
    {
        for (int j = 0; j < FIELD_SIZE; j++)
        {
            arr[i][j] = c;
        }
    }
 
}
 
void Pass2AnotherPlayer() {
    system("cls");
    cout << "Переход к другому игроку. И не подглядывайте ;)" << endl;
    Sleep(5000);
    system("cls");
}
 
void Set_ships(char arr[][FIELD_SIZE], int PlayerNumber) {
 
    char PNEnd[5];
    char Torp;
    char Destr;
    char Crui;
    char BShip;
 
    if (PlayerNumber == 1) {
        Torp = TorpedeP1;
        Destr = DestroyerP1;
        Crui = CruiserP1;
        BShip = BattleshipP1;
 
        strcpy_s(PNEnd, "-ый");
    }
    else {
        Torp = TorpedeP2;
        Destr = DestroyerP2;
        Crui = CruiserP2;
        BShip = BattleshipP2;
 
        strcpy_s(PNEnd, "-ой");
    }
 
    int amount_of_checked_cells = 0;
    while (amount_of_checked_cells < 21)
    {
        system("cls");
 
        Print_table(arr);
        int nmb_of_cells_for_current_ship = 1;
        char type_of_ship[100];
 
        if (nmb_of_cells_for_current_ship == 4)
            strcpy_s(type_of_ship, "линкор (4 клетки для размещения)");
 
        if (nmb_of_cells_for_current_ship == 3)
            strcpy_s(type_of_ship, "крейсер (3 клетки для размещения)");
 
        if (nmb_of_cells_for_current_ship == 2)
            strcpy_s(type_of_ship, "эсминец (2 клетки для размещения)");
 
        if (nmb_of_cells_for_current_ship == 1)
            strcpy_s(type_of_ship, "торпедный катер (1 клетка для размещения)");
 
        int plant_choise_x, plant_choise_y;
 
        cout << "Введите порядковый номер клетки, на которую " << PlayerNumber << PNEnd << " игрок хочет поместить кораблик (x,y).";
        cout << endl << "Помещается " << type_of_ship << "." << endl;
        cout << "   Ваши координаты: ";
 
        cin >> plant_choise_x >> plant_choise_y;
 
        if ((Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y] /* само место, куда ставится клетка*/) == false
            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1] /* верхняя правая клетка */) == false
            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1] /* нижняя левая клетка */) == false
            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1] /* верхняя левая клетка */) == false
            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1] /* нижняя правая клетка */) == false)
            ) {
 
            if (
                Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false /* нижняя */
                && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false /* верхняя */
                && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false /* левая */
                && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false /* правая */
                )
            {
                arr[plant_choise_x][plant_choise_y] = Torp;
                amount_of_checked_cells++;
            }
 
            if (amount_of_checked_cells > 4 && amount_of_checked_cells < 12) {
 
                if (nmb_of_cells_for_current_ship == 1)
                    nmb_of_cells_for_current_ship++;
 
                if (arr[plant_choise_x + 1][plant_choise_y] == Destr
                        && (Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false /// choise_cords (1)
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false
 
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 2][plant_choise_y - 1]) == false // [1]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 2][plant_choise_y + 1]) == false // [2]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 2][plant_choise_y]) == false /// choise_cords (2)
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false
                        )
                    ||
                    (arr[plant_choise_x - 1][plant_choise_y] == Destr                               // [2]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false // [1]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false /// choise_cords (1) // низ
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижнелевая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // нижнеправая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false // лево
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false // право
 
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 2][plant_choise_y]) == false /// choise_cords (2) // верх
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 2][plant_choise_y - 1]) == false // верхнелевая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 2][plant_choise_y + 1]) == false // верхнеправая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // левая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // правая
                        )
                    ||
                    (
                        arr[plant_choise_x][plant_choise_y + 1] == Destr                            // ---->
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false // [1][2]
 
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false /// choise_cords (1) // низ
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верх
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижнелевая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхнелевая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false // лево
 
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false /// choise_cords (2) // верх
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // низ
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 2]) == false // верхнеправая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 2]) == false // правая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 2]) == false // нижнеправая
                        )
                    ||
                    (
                        arr[plant_choise_x][plant_choise_y - 1] == Destr // [1]                         // [2][1]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верх (1)
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false // низ
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false // правая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхнеправая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // нижнеправая кллетка
 
                                                                                                            // [2]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 2]) == false // верхнелевая клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 2]) == false // левая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 2]) == false // верхнелевая
                        )
                    ||
                    (
                        Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false // сама клетка
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верхняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false // нижняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false // левая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false // правая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхнелевая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхнеправая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижнелевая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // нижнеправая
                        )
 
                    ) {
                    arr[plant_choise_x][plant_choise_y] = Destr;
                    amount_of_checked_cells++;
                }
 
                if (amount_of_checked_cells >= 12)
                {
                    if (nmb_of_cells_for_current_ship == 2)
                        nmb_of_cells_for_current_ship++;
 
                    /// [1][2][3]
 
                    //[1]
                    if ((arr[plant_choise_x][plant_choise_y + 1] == Crui && arr[plant_choise_x][plant_choise_y + 2] == Crui
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false
 
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верхняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false // нижняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false // левая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхнелевая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижелевая
 
                                                                                                            //[2]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // нижнняя
 
                                                                                                            //[3]
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 2]) == false // верхняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 2]) == false // нижняя
                        && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 3]) == false // правая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 3]) == false // верхнеправая
                        && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 3]) == false // нижнеправая
                        )
                        ||
 
                        /// [3][2][1]
                        (
                            Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false
                            && arr[plant_choise_x][plant_choise_y - 1] == Crui && arr[plant_choise_x][plant_choise_y - 2] == Crui
 
                            // [1]
 
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false // нижняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false // правая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхнеправая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // нижнеправая
 
                                                                                                                // [2]
 
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижняя
 
                                                                                                                // [3]
 
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 2]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 2]) == false // нижняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 3]) == false // левая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 3]) == false // верхнелевая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 3]) == false // нижнелевая
                            )
                        ||
                        (
                            Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false
                            && arr[plant_choise_x][plant_choise_y - 1] == Crui && arr[plant_choise_x][plant_choise_y + 1] == Crui
 
                            /// [2][1][3]
                            // [1]
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y]) == false // нижняя
 
                                                                                                            // [2]
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // нижняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 2]) == false // левая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 2]) == false // верхнелевая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 2]) == false // нижнелевая
 
                                                                                                                // [3]
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // нижняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 2]) == false // правая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 2]) == false // верхнеправая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 2]) == false // нижеправая
                            )
                        ||
                        (
                            /*
                            [1]
                            [2]
                            [3]
                            */
 
                            Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y]) == false
                            && arr[plant_choise_x + 1][plant_choise_y] == Crui && arr[plant_choise_x + 2][plant_choise_y] == Crui
 
                            // [1]
 
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y - 1]) == false // левая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x][plant_choise_y + 1]) == false // правая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y - 1]) == false // верхнелевая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхнеправая
 
                                                                                                                // [2]
 
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y - 1]) == false // левая
                            && Cell_checker(PlayerNumber, arr[plant_choise_x + 1][plant_choise_y + 1]) == false // правая
 
                                                                                                                // [3]
 
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
                            && Cell_checker(PlayerNumber, arr[plant_choise_x - 1][plant_choise_y + 1]) == false // верхняя
 
 
 
                            )
                        ) {
                        arr[plant_choise_x][plant_choise_y] = Crui;
                        amount_of_checked_cells++;
                    }
 
                    if (amount_of_checked_cells == 17)
                    {
                        if (nmb_of_cells_for_current_ship == 3)
                            nmb_of_cells_for_current_ship++;
 
                        arr[plant_choise_x][plant_choise_y] = BShip;
                        break;
                    }
                }
            }
        }
 
        else
        {
            system("cls");
            cout << "Введите правильную ячейку! " << endl;
            Sleep(1250);
        }
 
 
 
 
    }
 
 
}
 
void Player_move(char arr1[][FIELD_SIZE], char arr2[][FIELD_SIZE], int PlayerNumber, char* p1, char* p2)
{
    int choise_x;
    int choise_y;
 
    while (true) {
        system("cls");
        choise_x = 0; choise_y = 0;
 
        if (PlayerNumber == 1) {
 
            Print_table(arr1);
 
            cout << "\n Введите координаты клетки, в которую вы хотите стрельнуть, " << p1 << ": ";
            cout << "\n Вам осталось потопить клеток кораблей: " << amount_of_ship_cells_left_to_drown_P2;
            cin >> arr2[choise_x][choise_y];
 
 
            if ((arr2[choise_x][choise_y] == TorpedeP2
                || arr2[choise_x][choise_y] == DestroyerP2
                || arr2[choise_x][choise_y] == CruiserP2
                || arr2[choise_x][choise_y] == BattleshipP2)
                && arr2[choise_x][choise_y] != ShipHitP2
                && arr2[choise_x][choise_y] != HitMissP2)
            {
                arr2[choise_x][choise_y] = ShipHitP2;
                --amount_of_ship_cells_left_to_drown_P2;
                system("cls");
                cout << "Попадание!" << endl;
                system("pause");
                continue;
            }
 
            else if (arr2[choise_x][choise_y] == ShipHitP2
                || arr2[choise_x][choise_y] == HitMissP2) {
                system("cls");
                cout << "Вы по этой клетке уже попадали!" << endl;
                system("pause");
                continue;
            }
 
            else {
                arr2[choise_x][choise_y] = HitMissP2;
                system("cls");
                Pass2AnotherPlayer();
                break;
            }
        }
 
        else {
            Print_table(arr2);
 
            cout << "\n Введите координаты клетки, в которую вы хотите стрельнуть, " << p2 << ": ";
            cout << "\n Вам осталось потопить клеток кораблей: " << amount_of_ship_cells_left_to_drown_P1;
            cin >> arr1[choise_x][choise_y];
 
            if ((arr1[choise_x][choise_y] == TorpedeP1
                || arr1[choise_x][choise_y] == DestroyerP1
                || arr1[choise_x][choise_y] == CruiserP1
                || arr1[choise_x][choise_y] == BattleshipP1)
                && arr1[choise_x][choise_y] != ShipHitP1
                && arr1[choise_x][choise_y] != HitMissP1)
            {
                arr1[choise_x][choise_y] = ShipHitP1;
                --amount_of_ship_cells_left_to_drown_P1;
                system("cls");
                cout << "Попадание!" << endl;
                system("pause");
                continue;
            }
 
            else if (arr1[choise_x][choise_y] == ShipHitP1
                || arr1[choise_x][choise_y] == HitMissP1) {
                system("cls");
                cout << "Вы по этой клетке уже попадали!" << endl;
                system("pause");
                continue;
            }
 
            else {
                arr1[choise_x][choise_y] = HitMissP1;
                system("cls");
                Pass2AnotherPlayer();
                break;
            }
        }
    }
}
 
bool Win(int ship_cells) {
 
    if (ship_cells == 0)
        return true;
    return false;
}
 
int main()
{
    srand((unsigned)time(0));
    setlocale(LC_ALL, "Russian");
 
    char arr1[FIELD_SIZE][FIELD_SIZE];
    char arr2[FIELD_SIZE][FIELD_SIZE];
 
    Players_names(Player1, Player2);
 
    system("cls");
 
    cout << "Имя первого игрока: " << Player1 << endl;
    cout << "Имя второго игрока: " << Player2 << endl << endl;
 
    system("pause");
 
    Create_table(arr1, WaterP1);
    Set_ships(arr1, 1);
 
    Pass2AnotherPlayer();
 
    Create_table(arr2, WaterP2);
    Set_ships(arr2, 2);
 
    system("pause");
 
    system("cls");
 
    cout << "\t BETA TEST" << endl << endl;
    cout << "Поле игрока с именем (или никнеймом) " << Player1 << endl;
    Print_table(arr1);
 
    cout << endl;
 
    cout << "Поле игрока с именем (или никнеймом) " << Player2 << endl;
    Print_table(arr2);
 
 
 
    while (true)
    {
        Player_move(arr1, arr2, 1, Player1, Player2);
        Player_move(arr1, arr2, 2, Player1, Player2);
        Win(amount_of_ship_cells_left_to_drown_P1);
        Win(amount_of_ship_cells_left_to_drown_P2);
 
        if (Win(amount_of_ship_cells_left_to_drown_P2) == true) {
            ifP1Win(Player1);
        }
 
        else if (Win(amount_of_ship_cells_left_to_drown_P1) == true) {
            ifP2Win(Player2);
        }
 
        cout << "Поле игрока с именем (никнеймом) " << Player1 << endl << endl;
        Print_table(arr1);
 
        cout << endl;
 
        cout << "Поле игрока с именем (никнеймом) " << Player2 << endl << endl;
        Print_table(arr2);
 
        system("pause");
    }
 
 
 
    system("pause");
    return 0;
}
0
8 / 8 / 6
Регистрация: 21.04.2018
Сообщений: 142
26.07.2018, 09:07  [ТС]
Исправились проблемы с поставлением однопалубных кораблей, теперь проблема с двухпалубными. Когда я записываю в x значение 1, а в y 1 -- x делает инкрементирование на 1, а y не меняется; когда я записываю в x 1, а в y 0 - запись идёт и в 10-ый x, и в 0-ой y; при кладке двухпалубок почему-то не работает условие перехода на постройку трёхпалубки; при помещении шести Э поместить Э рядом друг с другом нельзя почему-то. Короче, капут.. Я уже не знаю, как поступать. Ожидаю того, кто может помочь с ошибкой (она где-то в функции Set_ships) Просьба помочь как можно скорее: это моя курсовая работа, которую я должен закончить сегодня, осталось только это условие. Возможно та же ошибка будет и в условии крейсеров... Будьте добры. Видоизменённый код:
Кликните здесь для просмотра всего текста
0
8 / 8 / 6
Регистрация: 21.04.2018
Сообщений: 142
27.07.2018, 22:07  [ТС]
Доброго времени суток всем. Такое дело: после установки шести клеток двухпалубных кораблей (Э) игра не может позволить мне поместить трёхпалубные клетки (К). В чём может быть тут дело? Ошибка расположена либо в функции put_torpede, либо put_cruiser, либо в самом Set_ships. Не пойму, почему. Условия вроде-бы правильны, но блин.. не идёт дальше программа и всё: зацикливается. И ещё кое-что: как мне сделать проверку на клетки Э и Э, К и К, Л и Л, что-бы они не были отделены друг от друга? Сам код будет в файле ниже:

Морской Бой.rar
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
27.07.2018, 22:07

Найти причины возникновения ошибок в коде и исправить эти ошибки
Всем привет, я новичок. Решил попробовать создать простенький класс который выводит данные которые вы ввели, но после того как я ввожу...

Найти причины возникновения ошибок в коде и исправить эти ошибки
не пойму что он от меня хочет #include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;iostream.h&gt; #include &lt;stdlib.h&gt; #include...

Найти причины возникновения ошибок в коде и исправить эти ошибки
Всем хай. Во-первых, vs не видит в мейне V и говорит, что она не инициализирована, но на идеоне оно компилируется и даже работает, НО не...

Найти причины возникновения ошибок в коде и исправить эти ошибки
// Висимских.cpp : Defines the entry point for the console application. #include &quot;stdafx.h&quot; #include &lt;iostream&gt; #include &lt;math.h&gt; ...

Найти причины возникновения ошибок в коде и исправить эти ошибки
Делаю лабу по программированию, всё бы хорошо но проблема с одной строчкой #include &quot;stdafx.h&quot; #include &lt;iostream&gt; ...


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

Или воспользуйтесь поиском по форуму:
23
Ответ Создать тему
Новые блоги и статьи
Где деньги лежат
kumehtar 02.07.2026
Это - японская подводная лодка I-52 (тип C2, кодовое имя Momi) вышла из Японии в марте 1944 года с миссией в оккупированную немцами Францию (Лорьян). Это была одна из «Янаги»-миссий по обмену. . .
Krabik для WoW 3.3.5a, многоязычный
AmbA 02.07.2026
Допилил бота, думаю что окончательно. Изменения: - добавлена многоязычность - добавлено снятие скриншотов - добавлено поддержание бафов хождения по воде (для жреца, дк и шамана) - и так, по. . .
Алиса нашла кучу ошибок компиляции и запуска в проекте, который без проблем компилировался и запускался)))
anaschu 30.06.2026
Я пока посмеюся, но завтра проверю. А вообще интерсно. Дал алисе файл, в котором точно нет ошибок компиляции и запуска, и попросил их найти. Нашла кучу))) Критические ошибки, мешающие компиляции и. . .
сукцессия 16. Общий обзор, в основном что бы другие ии поняли
anaschu 29.06.2026
# Передаточный документ: модель микоризной сукцессии (для нового чата) Этот документ предназначен для того, чтобы новый чат Claude мог продолжить работу без необходимости заново разбираться в. . .
сукцессия 15 неявная схема
anaschu 29.06.2026
Алиса Калибровка параметров симбиотической модели: технический обзор Содержание: Введение Постановка проблемы Технические аспекты реализации Процесс внедрения изменений
сукцессия 14. Обновленная схема модели
anaschu 28.06.2026
ГЛОБАЛЬНАЯ ОПИСАТЕЛЬНАЯ СПЕЦИФИКАЦИЯ ЭКОСИСТЕМНОЙ МОДЕЛИ «SOIL CHEMISTRY & MYCORRHIZA 2. 0» https:/ / ibb. co/ NnkGpfMd Представленная интегрированная схема описывает непрерывную нелинейную. . .
сукцессия 13. Питон модель трехзонного мицелия, пока что в основном арбускулярного
anaschu 28.06.2026
## Разработка агентной модели микоризной сукцессии: от выявления артефактов к созданию комплексной системы ### Аннотация Представлено исследование по разработке агентной модели микоризной. . .
сукцессия 12. краткий список проверок модели перед запуском.
anaschu 27.06.2026
Скрытые отказы в моделях систем динамики (SD-models) экологических систем: два случая из практики Контекст Разбирался прототип модели систем динамики (SD-модели) микоризной сукцессии: пять. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru