Форум программистов, компьютерный форум, киберфорум
C для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.58/19: Рейтинг темы: голосов - 19, средняя оценка - 4.58
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
1

Консольный "Морской бой"

31.05.2020, 03:48. Показов 3845. Ответов 13

Author24 — интернет-сервис помощи студентам
Доброго времени суток господа. Не так давно узнал что моя сладкая жизнь на первокурсника после сессии так просто не заканчивается. И на мою голову упал курсач по проге .В общем я взял свою волю в кулак и 2 дня смотрел обучающие уроки по теме "Морской бой в консоли СИ". По итогам я написал 285 строчек кода, больше я наверное в жизни в ручную сам не писал.
И на удивление код работает, вот только как сделать дальше я так понять и не могу, в этими обзорами влез в темы, о которых ни малейшего понятия не имею, а сроки горят
Осталось доделать:
1) Логоритм генерации кораблей "&". ( На данный момент он записан статично void ship_generate)
2) Изменения символа при выстреле (нажатии Enter). По идеи для реализации нужно еще 2 массива по типу p1_data
3) Ну и в идеале нужно что бы ход второго игрока делал компьютер, но я честно говоря даже представить на данный момент не могу, как это реализовать
Если у кого есть несколько минут свободного времени, помогите пожалуйста
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
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/*
 
.....ABCDEFGHIJ........ABCDEFGHIJ
....*----------*......*----------*
...0|..........|.....0|..........|
...1|..........|.....1|..........|
...2|..........|.....2|..........|
...3|..........|.....3|..........|
...4|..........|.....4|..........|
...5|..........|.....5|..........|
...6|..........|.....6|..........|
...7|..........|.....7|..........|
...8|..........|.....8|..........|
...9|..........|.....9|..........|
....*----------*......*----------*
 
*/
typedef enum
{
 INIT = 0
 ,DRAW
 ,PROCESSING
 ,EXIT
}eGameState;
typedef enum
{
 EMPTY = 0
 ,SHOT
 ,STRIKE
 ,KILL
 ,SHIP
 ,EFILD_INFO_END
}eFieldInfo;
 
char draw_symbol[EFILD_INFO_END]=
{
     ' ' //EMPTY
    ,'*' //SHOT
    ,'X' //STRIKE
    ,'#' //KILL
    ,'&' //SHIP
 
};
#define PLAYER_1 0
#define PLAYER_2 ~PLAYER_1
 
#define ARROW_KEY_PRESSED   0xE0
#define KEY_ENTER           13
#define KEY_UP              72
#define KEY_RIGHT           77
#define KEY_DOWN            80
#define KEY_LEFT            75
 
#define TARGET             '+'
 
#define N_Lines 13
#define FIELD_SIZE 10
char *FIELD [] =
{
 "  ABCDEFGHIJ        ABCDEFGHIJ "
," *----------*      *----------*"
,"0|          |     0|          |"
,"1|          |     1|          |"
,"2|          |     2|          |"
,"3|          |     3|          |"
,"4|          |     4|          |"
,"5|          |     5|          |"
,"6|          |     6|          |"
,"7|          |     7|          |"
,"8|          |     8|          |"
,"9|          |     9|          |"
," *----------*      *----------*"
};
 
void draw_field(eFieldInfo *, unsigned short);
void ship_generate(eFieldInfo *);
unsigned char get_target_position(unsigned char*, unsigned char*);
//--------------------------------------------------------
int main()
{
    eGameState game_state = INIT;
    unsigned char isRun = 1;
 
    int player = PLAYER_1;
 
    eFieldInfo p1_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    //eFieldInfo p1_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    //eFieldInfo p2_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo *tmp;
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
    unsigned short shot_position = 0;
 
    while(isRun)
    {
        switch (game_state)
        {
        case INIT:
            {
                ship_generate(p1_data);
                ship_generate(p2_data);
 
                p1_data [0] = KILL;
 
                game_state = DRAW;
                break;
            }
        case DRAW:
            {
                system("cls");
 
                tmp = (player == PLAYER_1) ? p1_data : p2_data;
 
                draw_field(tmp, shot_position);
 
                if(get_target_position(&target_x, &target_y))
                {
                    game_state = PROCESSING;
                }
                shot_position = (target_y << 8) | (target_x);
                break;
            }
        case PROCESSING:
            {
                //processing
 
                player = ~player;
 
                game_state = DRAW;
                break;
            }
        case EXIT:
            {
                break;
            }
        }
    }
 
 
 
    return 0;
}
 
void draw_field(eFieldInfo *ap_data, unsigned short a_target)
{
    printf("%s\n",FIELD[0]);
    printf("%s\n",FIELD[1]);
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
 
    target_x = a_target;
    target_y = a_target >> 8;
 
    for(int i=0; i < 10; ++i)
    {
        printf("%c%c",FIELD[i + 2][0],FIELD[i + 2][1]);
 
        for(int j=0; j < FIELD_SIZE; ++j) // print field 1 data
           {
               printf("%c", draw_symbol [ ap_data[i * FIELD_SIZE + j]]);
           }
 
        for(int j=12; j < 20; ++j)
           printf("%c",FIELD[i + 2][j]);
 
         for(int j=0; j < FIELD_SIZE; ++j) // print field 2 data
           {
 
               if (i == target_y && j== target_x)
                 printf("%c", TARGET);
               else
               {
                printf(" ");
                 //printf("%c", draw_symbol [ ap_ener1[i * FIELD_SIZE + j]]);
               }
           }
 
        printf("%c\n",FIELD[i + 2][30]);
    }
 
    printf("%s\n",FIELD[N_Lines - 1]);
}
 
//void ship_generate(eFieldInfo *ap_enter1)
//if
 
void ship_generate(eFieldInfo *ap_data)
{
    /*
      0123456789
    0|&    &  & |
    1|  &  &    |
    2|  &  &   &|
    3|         &|
    4|      &   |
    5|&        &|
    6|&         |
    7|&     &&&&|
    8|&         |
    9|   &&  && |
 
    */
    // i*n+j
    //Эту шляпу заменить на логоритм
        // line 0
    ap_data[0 * 10 + 0] = SHIP;
    ap_data[0 * 10 + 5] = SHIP;
    ap_data[0 * 10 + 8] = SHIP;
 
        // line 1
    ap_data[1 * 10 + 2] = SHIP;
    ap_data[1 * 10 + 5] = SHIP;
 
        // line 2
    ap_data[2 * 10 + 2] = SHIP;
    ap_data[2 * 10 + 5] = SHIP;
    ap_data[2 * 10 + 9] = SHIP;
       // line 3
    ap_data[3 * 10 + 9] = SHIP;
       // line 4
    ap_data[4 * 10 + 6] = SHIP;
       // line 5
    ap_data[5 * 10 + 0] = SHIP;
    ap_data[5 * 10 + 9] = SHIP;
       // line 6
    ap_data[6 * 10 + 0] = SHIP;
       // line 7
    ap_data[7 * 10 + 0] = SHIP;
    ap_data[7 * 10 + 6] = SHIP;
    ap_data[7 * 10 + 7] = SHIP;
    ap_data[7 * 10 + 8] = SHIP;
    ap_data[7 * 10 + 9] = SHIP;
 
       // line 8
    ap_data[8 * 10 + 0] = SHIP;
 
       // line 9
    ap_data[9 * 10 + 3] = SHIP;
    ap_data[9 * 10 + 4] = SHIP;
    ap_data[9 * 10 + 7] = SHIP;
    ap_data[9 * 10 + 8] = SHIP;
}
//---------------------------------------------------------
unsigned char get_target_position(unsigned char *ap_x, unsigned char *ap_y)
{
   int key = 0;
   key = getch();
   switch (key)
   {
      case ARROW_KEY_PRESSED:
         {
             switch (getch())
             {
               case KEY_DOWN:
                 {
                  if(*ap_y < (FIELD_SIZE - 1))
                      (*ap_y)++;
                   return 0;
                }
               case KEY_UP:
                {
                   if(*ap_y > 0 )
                      (*ap_y)--;
                   return 0;
                }
               case KEY_LEFT:
                {
                   if(*ap_x > 0 )
                      (*ap_x)--;
                   return 0;
                }
               case KEY_RIGHT:
                {
                  if(*ap_x < (FIELD_SIZE - 1))
                      (*ap_x)++;
                   return 0;
                }
            }
         }
        case KEY_ENTER:
         return 1;
   }
   return 0;
}
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
31.05.2020, 03:48
Ответы с готовыми решениями:

Консольный морской бой
Ребят, срочно прошу помощи, нужен примитивный морской бой в консоли на СИ с обычными правилами. 1...

Консольный Морской бой на Си
Доброго времени суток, форумчане. Выдали задание написать консольный морской бой на Си. И имею...

Морской бой на СИ
Пишу программку на Си (это задание на экзамен) морской бой, не используя классы (мы ещё их не...

Расстановка кораблей Морской бой
Помогите расставить корабли в игре морской бой. Уже 2ю ночь не сплю ошибки выдаёт. Задаю массив...

13
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
02.06.2020, 02:38  [ТС] 2
Может у кто-то есть желание помочь не бесплатно. 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
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
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/*
 
.....ABCDEFGHIJ........ABCDEFGHIJ
....*----------*......*----------*
...0|..........|.....0|..........|
...1|..........|.....1|..........|
...2|..........|.....2|..........|
...3|..........|.....3|..........|
...4|..........|.....4|..........|
...5|..........|.....5|..........|
...6|..........|.....6|..........|
...7|..........|.....7|..........|
...8|..........|.....8|..........|
...9|..........|.....9|..........|
....*----------*......*----------*
 
*/
typedef enum
{
 INIT = 0
 ,DRAW
 ,PROCESSING
 ,EXIT
}eGameState;
typedef enum
{
 EMPTY = 0
 ,SHOT
 ,STRIKE
 ,KILL
 ,SHIP
 ,EFILD_INFO_END
}eFieldInfo;
 
char draw_symbol[EFILD_INFO_END]=
{
     ' ' //EMPTY
    ,'*' //SHOT
    ,'X' //STRIKE
    ,'#' //KILL
    ,'&' //SHIP
 
};
#define PLAYER_1 0
#define PLAYER_2 ~PLAYER_1
 
#define ARROW_KEY_PRESSED   0xE0
#define KEY_ENTER           13
#define KEY_UP              72
#define KEY_RIGHT           77
#define KEY_DOWN            80
#define KEY_LEFT            75
 
#define TARGET             '+'
 
#define N_Lines 13
#define FIELD_SIZE 10
char *FIELD [] =
{
 "  ABCDEFGHIJ        ABCDEFGHIJ "
," *----------*      *----------*"
,"0|          |     0|          |"
,"1|          |     1|          |"
,"2|          |     2|          |"
,"3|          |     3|          |"
,"4|          |     4|          |"
,"5|          |     5|          |"
,"6|          |     6|          |"
,"7|          |     7|          |"
,"8|          |     8|          |"
,"9|          |     9|          |"
," *----------*      *----------*"
};
 
void draw_field(eFieldInfo *,eFieldInfo *, unsigned short);
void ship_generate(eFieldInfo *);
void ship_enter(eFieldInfo *,unsigned short a_target);
unsigned char get_target_position(unsigned char*, unsigned char*);
//--------------------------------------------------------
int main()
{
    eGameState game_state = INIT;
    unsigned char isRun = 1;
 
    int player = PLAYER_1;
 
    eFieldInfo p1_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo p1_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo *tmp,*kil;
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
    unsigned short shot_position = 0;
 
    while(isRun)
    {
        switch (game_state)
        {
        case INIT:
            {
                ship_generate(p1_data);
                ship_generate(p2_data);
 
                p1_data [0] = KILL;
 
                game_state = DRAW;
                break;
            }
        case DRAW:
            {
                system("cls");
 
                tmp = (player == PLAYER_1) ? p1_data : p2_data;
                kil = (player == PLAYER_1) ? p1_enter : p2_enter;
 
                draw_field(tmp,kil, shot_position);
 
                if(get_target_position  (&target_x, &target_y) )
                {
                    game_state = PROCESSING;
                }
                shot_position = (target_y << 8) | (target_x);
                break;
            }
        case PROCESSING:
            {
                ship_enter(p1_enter,shot_position );
                ship_enter(p2_enter,shot_position );
                //processing
 
                player = ~player;
 
                game_state = DRAW;
                break;
            }
        case EXIT:
            {
                break;
            }
        }
    }
 
 
 
    return 0;
}
 
void draw_field(eFieldInfo *ap_data,eFieldInfo *ap_enter, unsigned short a_target)
{
    printf("%s\n",FIELD[0]);
    printf("%s\n",FIELD[1]);
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
 
    target_x = a_target;
    target_y = a_target >> 8;
 
    for(int i=0; i < 10; ++i)
    {
        printf("%c%c",FIELD[i + 2][0],FIELD[i + 2][1]);
 
        for(int j=0; j < FIELD_SIZE; ++j) // print field 1 data
           {
               printf("%c", draw_symbol [ ap_data[i * FIELD_SIZE + j]]);
 
           }
 
        for(int j=12; j < 20; ++j)
           printf("%c",FIELD[i + 2][j]);
 
         for(int j=0; j < FIELD_SIZE; ++j) // print field 2 data
           {
 
               if (i == target_y && j== target_x)
                 printf("%c", TARGET);
               else
               {
                //printf(" ");
                printf("%c", draw_symbol [ ap_enter[i * FIELD_SIZE + j]]);
               }
           }
 
        printf("%c\n",FIELD[i + 2][30]);
    }
 
    printf("%s\n",FIELD[N_Lines - 1]);
}
 
void ship_enter(eFieldInfo *ap_enter,unsigned short a_target)
{
    //shot_position = (target_y << 8) | (target_x);
 
//    a_target = target_x ;
  //  a_target >> 8 = target_y ;
 
ap_enter[a_target >> 8 * 10 + a_target] = STRIKE;
 
 
//ap_enter[&target_y * 10 + &target_x] = STRIKE;
 
}
 
 
void ship_generate(eFieldInfo *ap_data)
{
    /*
      0123456789
    0|&    &  & |
    1|  &  &    |
    2|  &  &   &|
    3|         &|
    4|      &   |
    5|&        &|
    6|&         |
    7|&     &&&&|
    8|&         |
    9|   &&  && |
 
    */
    // i*n+j
    //блеярн щрни ькъош мсфем кюцнпхрл
        // line 0
    ap_data[0 * 10 + 0] = SHIP;
    ap_data[0 * 10 + 5] = SHIP;
    ap_data[0 * 10 + 8] = SHIP;
 
        // line 1
    ap_data[1 * 10 + 2] = SHIP;
    ap_data[1 * 10 + 5] = SHIP;
 
        // line 2
    ap_data[2 * 10 + 2] = SHIP;
    ap_data[2 * 10 + 5] = SHIP;
    ap_data[2 * 10 + 9] = SHIP;
       // line 3
    ap_data[3 * 10 + 9] = SHIP;
       // line 4
    ap_data[4 * 10 + 6] = SHIP;
       // line 5
    ap_data[5 * 10 + 0] = SHIP;
    ap_data[5 * 10 + 9] = SHIP;
       // line 6
    ap_data[6 * 10 + 0] = SHIP;
       // line 7
    ap_data[7 * 10 + 0] = SHIP;
    ap_data[7 * 10 + 6] = SHIP;
    ap_data[7 * 10 + 7] = SHIP;
    ap_data[7 * 10 + 8] = SHIP;
    ap_data[7 * 10 + 9] = SHIP;
 
       // line 8
    ap_data[8 * 10 + 0] = SHIP;
 
       // line 9
    ap_data[9 * 10 + 3] = SHIP;
    ap_data[9 * 10 + 4] = SHIP;
    ap_data[9 * 10 + 7] = SHIP;
    ap_data[9 * 10 + 8] = SHIP;
}
//---------------------------------------------------------
unsigned char get_target_position(unsigned char *ap_x, unsigned char *ap_y)
{
   int key = 0;
   key = getch();
   switch (key)
   {
      case ARROW_KEY_PRESSED:
         {
             switch (getch())
             {
               case KEY_DOWN:
                 {
                  if(*ap_y < (FIELD_SIZE - 1))
                      (*ap_y)++;
                   return 0;
                }
               case KEY_UP:
                {
                   if(*ap_y > 0 )
                      (*ap_y)--;
                   return 0;
                }
               case KEY_LEFT:
                {
                   if(*ap_x > 0 )
                      (*ap_x)--;
                   return 0;
                }
               case KEY_RIGHT:
                {
                  if(*ap_x < (FIELD_SIZE - 1))
                      (*ap_x)++;
                   return 0;
                }
            }
         }
        case KEY_ENTER:
         return 1;
   }
   return 0;
}
Миниатюры
Консольный "Морской бой"  
0
2305 / 1131 / 702
Регистрация: 25.04.2016
Сообщений: 3,222
03.06.2020, 06:06 3
Алгоритм расстановки кораблей в случайном порядке. Тупой как пробка, просто расставляет случайным образом, никакой оптимизации, и да, под ваш код не писал, поскольку заниматься еще и интеграцией никакого желания нет:
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
 
enum { HORIZONTAL=777, VERTICAL=666 };  // направление, просто для удобочитаемости
 
struct ship {
    int x;          // расположение корабля по x (от 0 до N-1)
    int y;          // расположение корабля по y (от 0 до N-1)
    int direction;  // положение корабля: 777 - horizontal, 666 - vertical
    int len;        // количество палуб корабля (от 1 до 4)
};
 
void draw_filed (int field[][N]);                           // выводим поле
void generate_battlefield (int field[][N]);                 // заполняем корытцами
int check_field (int field[][N], struct ship boat);         // есть ли место на поле?
int check_horizontal (int field[][N], struct ship boat);    // место по горизонтали?
int check_vertical (int field[][N], struct ship boat);      // а по вертикали?
 
int main (void) {
    srand( (unsigned int)time(NULL)/2 );
    int field[N][N] = {0};          // заполняем поле нулями
    generate_battlefield(field);    // генерируем корабли и расставляем на поле
    draw_filed(field);              // поле на экран
    return 0;
}
// ------------------------------------------------------------
void draw_filed (int field[][N]) {
    // ничего не значащая функция, просто выводит поле на экран
    puts("");
    for (int i=0; i<N; ++i)     // номера позиций
        printf("%d", (i+1)%N);
    puts("");
 
    for (int i=0; i<N; ++i)     // верхняя граница
        printf("-");
    puts("");
 
    for (int i=0; i<N; ++i, puts(""))
        for (int k=0; k<N; ++k) {
            printf("%c", (field[i][k] == 1)? '#' : ' ');    // поле
            if (k == N-1) printf("| %d", (i+1)%N);          // номера позиций
        }
 
    for (int i=0; i<N; ++i)     // нижняя граница
        printf("-");
    puts("");
}
// ------------------------------------------------------------
void generate_battlefield (int field[][N]) {
    int ship_count;     // количество кораблей в зависимости от длины корыта
    struct ship boat;
    for (int i=4; i>0; --i) {   // количество палуб
        ship_count = 5 - i;
        for (int k=0; k<ship_count; ++k) {      // количество кораблей
            boat.len = i;
            // проверяем, есть ли место для корабля:
            do {
                boat.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( boat.direction == HORIZONTAL ) {
                    boat.y = rand() %N;
                    boat.x = rand() %( (i==1)? N : N-i );
                }
                if( boat.direction == VERTICAL ) {
                    boat.y = rand() %( (i==1)? N : N-i );
                    boat.x = rand() %N;
                }
            } while ( check_field(field, boat) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if ( boat.direction == HORIZONTAL ){
                for (int x=0; x<boat.len; ++x)
                    field[boat.y][boat.x+x] = 1;
            }
            if( boat.direction == VERTICAL ) {
                for (int y=0; y<boat.len; ++y)
                    field[boat.y+y][boat.x] = 1;
            }
        }
    }
}
// ------------------------------------------------------------
int check_field (int field[][N], struct ship shp) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( shp.direction == HORIZONTAL )
        check = check_horizontal(field, shp);
    if( shp.direction == VERTICAL )
        check = check_vertical(field, shp);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct ship shp)
{
    int check = 1;  // true
    int from_x = (shp.x == 0)? shp.x : shp.x-1;
    int to_x = (shp.x + shp.len >= N)? N-1 : shp.x + shp.len;
    int from_y = (shp.y == 0)? shp.y : shp.y-1;
    int to_y = (shp.y+1 >= N)? N-1 : shp.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct ship shp)
{
    int check = 1;      // true
    int from_x = (shp.x == 0)? shp.x : shp.x-1;
    int to_x = (shp.x+1 >= N)? N-1 : shp.x+1;
    int from_y = (shp.y == 0)? shp.y : shp.y-1;
    int to_y = (shp.y + shp.len >= N)? N-1 : shp.y + shp.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
1
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
03.06.2020, 06:08  [ТС] 4
Больше спасибо, сегодня попробую интегрировать в свой код
0
2305 / 1131 / 702
Регистрация: 25.04.2016
Сообщений: 3,222
03.06.2020, 08:23 5
Цитата Сообщение от Keitaro_Fox Посмотреть сообщение
нужно что бы ход второго игрока делал компьютер
Допустим в массиве filed[10][10] записаны наши корабли, где 0 - означает пустое место, а 1 - палубу корабля.

Тут есть два способа реализации, либо мы создаем параллельный массив shots[10][10], где 0 - ячейка, куда мы можем выстрелить, а 1 - ячейка, куда мы уже стреляли. Либо мы используем сразу массив field[][], считая что можем стрелять по ячейкам с 0 или 1, и отмечая выстрелы другим числом, например, 3 - для попадания в пустое место, и 4 - для попадания по кораблю.

Также нам понадобится переменная, в которой мы будем считать количество сделанных выстрелов.

Теперь генерируем случайную позицию x и y выстрела, от 0 до 10
Если количество выстрелов не равно 10*10 и если в ячейке shots[y][x] стоит 1, т.е. мы уже стреляли по этим координатам, повторяем цикл.

Проверяем можем ли сделать выстрел, стреляем, проверяем попадание по кораблю, ставим shots[y][x] в 1 и увеличиваем число выстрелов на 1.

Добавлено через 1 минуту
Вообще рекомендую почитать для общего развития.
0
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
05.06.2020, 03:40  [ТС] 6
Доброй ночи, сегодня наконец то у меня спала депрессия после прошлых неудач и я осилил интеграцию вашей части кода. И я очень вам благодарен
Что касается "второй игрок компьютер" я решил забить, так как и сам уже с трудом понимаю что к чему в моем уже наверное "быдло коде"
Осталась последняя просьба к вам, и последняя преграда на моем пути Не могу понять, как мне менять поля на игровом поле ( где стреляют )
P.s. наглеть не буду, но было бы не плохо если бы у вас был код такой же как как и для генерации , только для выстрелов на игровом поле
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
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
/*
 
.....ABCDEFGHIJ........ABCDEFGHIJ
....*----------*......*----------*
...0|..........|.....0|..........|
...1|..........|.....1|..........|
...2|..........|.....2|..........|
...3|..........|.....3|..........|
...4|..........|.....4|..........|
...5|..........|.....5|..........|
...6|..........|.....6|..........|
...7|..........|.....7|..........|
...8|..........|.....8|..........|
...9|..........|.....9|..........|
....*----------*......*----------*
 
*/
enum { HORIZONTAL=777, VERTICAL=666 };
struct ship {
    int x;          // расположение корабля по x (от 0 до N-1)
    int y;          // расположение корабля по y (от 0 до N-1)
    int direction;  // положение корабля: 777 - horizontal, 666 - vertical
    int len;        // количество палуб корабля (от 1 до 4)
};
typedef enum
{
 INIT = 0
 ,DRAW
 ,PROCESSING
 ,EXIT
}eGameState;
typedef enum
{
 EMPTY = 0
 ,SHOT
 ,STRIKE
 ,KILL
 ,SHIP
 ,EFILD_INFO_END
}eFieldInfo;
 
char draw_symbol[EFILD_INFO_END]=
{
     ' ' //EMPTY
    ,'&' //SHIP
    ,'X' //STRIKE
    ,'#' //KILL
    ,'*' //SHOT
 
};
#define PLAYER_1 0
#define PLAYER_2 ~PLAYER_1
 
#define ARROW_KEY_PRESSED   0xE0
#define KEY_ENTER           13
#define KEY_UP              72
#define KEY_RIGHT           77
#define KEY_DOWN            80
#define KEY_LEFT            75
 
#define TARGET             '+'
 
#define N_Lines 13
#define FIELD_SIZE 10
#define N 10
char *FIELD [] =
{
 "  ABCDEFGHIJ        ABCDEFGHIJ "
," *----------*      *----------*"
,"0|          |     0|          |"
,"1|          |     1|          |"
,"2|          |     2|          |"
,"3|          |     3|          |"
,"4|          |     4|          |"
,"5|          |     5|          |"
,"6|          |     6|          |"
,"7|          |     7|          |"
,"8|          |     8|          |"
,"9|          |     9|          |"
," *----------*      *----------*"
};
int check_field (int field[][N], struct ship boat);         // есть ли место на поле?
int check_horizontal (int field[][N], struct ship boat);    // место по горизонтали?
int check_vertical (int field[][N], struct ship boat);      // а по вертикали?
void draw_field(eFieldInfo *,eFieldInfo *, unsigned short);
void ship_generate(int field[][N]);
void ship_enter(eFieldInfo *,unsigned short a_target);
unsigned char get_target_position(unsigned char*, unsigned char*);
//--------------------------------------------------------
int main()
{
    eGameState game_state = INIT;
    unsigned char isRun = 1;
 
    int player = PLAYER_1;
 
    eFieldInfo p1_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo p1_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo *tmp,*kil;
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
    unsigned short shot_position = 0;
 
    while(isRun)
    {
        switch (game_state)
        {
        case INIT:
            {
                ship_generate(p1_data);
                ship_generate(p2_data);
 
               // p1_data [0] = KILL;
 
                game_state = DRAW;
                break;
            }
        case DRAW:
            {
                system("cls");
 
                tmp = (player == PLAYER_1) ? p1_data : p2_data;
                kil = (player == PLAYER_1) ? p1_enter : p2_enter;
 
                draw_field(tmp,kil, shot_position);
 
                if(get_target_position  (&target_x, &target_y) )
                {
                    game_state = PROCESSING;
                }
                shot_position = (target_y << 8) | (target_x);
                break;
            }
        case PROCESSING:
            {
                ship_enter(p1_enter,shot_position );
                ship_enter(p2_enter,shot_position );
                //processing
 
                player = ~player;
 
                game_state = DRAW;
                break;
            }
        case EXIT:
            {
                break;
            }
        }
    }
 
 
 
    return 0;
}
 
void draw_field(eFieldInfo *ap_data,eFieldInfo *ap_enter, unsigned short a_target)
{
    printf("%s\n",FIELD[0]);
    printf("%s\n",FIELD[1]);
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
 
    target_x = a_target;
    target_y = a_target >> 8;
 
    for(int i=0; i < 10; ++i)
    {
        printf("%c%c",FIELD[i + 2][0],FIELD[i + 2][1]);
 
        for(int j=0; j < FIELD_SIZE; ++j) // print field 1 data
           {
               printf("%c", draw_symbol [ ap_data[i * FIELD_SIZE + j]]);
 
           }
 
        for(int j=12; j < 20; ++j)
           printf("%c",FIELD[i + 2][j]);
 
         for(int j=0; j < FIELD_SIZE; ++j) // print field 2 data
           {
 
               if (i == target_y && j== target_x)
                 printf("%c", TARGET);
               else
               {
                //printf(" ");
                printf("%c", draw_symbol [ ap_enter[i * FIELD_SIZE + j]]);
               }
           }
 
        printf("%c\n",FIELD[i + 2][30]);
    }
 
    printf("%s\n",FIELD[N_Lines - 1]);
}
 
void ship_enter(eFieldInfo *ap_enter,unsigned short a_target)
{
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
 
    target_x = a_target;
    target_y = a_target >> 8;
 
ap_enter[target_y * 10 + target_x] = STRIKE;
 
}
 
 
void ship_generate(int field[][N])
{
    /*
      0123456789
    0|&    &  & |
    1|  &  &    |
    2|  &  &   &|
    3|         &|
    4|      &   |
    5|&        &|
    6|&         |
    7|&     &&&&|
    8|&         |
    9|   &&  && |
 
    */
    // i*n+j
int ship_count;     // количество кораблей в зависимости от длины корыта
    struct ship boat;
    for (int i=4; i>0; --i) {   // количество палуб
        ship_count = 5 - i;
        for (int k=0; k<ship_count; ++k) {      // количество кораблей
            boat.len = i;
            // проверяем, есть ли место для корабля:
            do {
                boat.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( boat.direction == HORIZONTAL ) {
                    boat.y = rand() %N;
                    boat.x = rand() %( (i==1)? N : N-i );
                }
                if( boat.direction == VERTICAL ) {
                    boat.y = rand() %( (i==1)? N : N-i );
                    boat.x = rand() %N;
                }
            } while ( check_field(field, boat) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if ( boat.direction == HORIZONTAL ){
                for (int x=0; x<boat.len; ++x)
                    field[boat.y][boat.x+x] = 1;
            }
            if( boat.direction == VERTICAL ) {
                for (int y=0; y<boat.len; ++y)
                    field[boat.y+y][boat.x] = 1;
            }
        }
    }
}
//---------------------------------------------------------
unsigned char get_target_position(unsigned char *ap_x, unsigned char *ap_y)
{
   int key = 0;
   key = getch();
   switch (key)
   {
      case ARROW_KEY_PRESSED:
         {
             switch (getch())
             {
               case KEY_DOWN:
                 {
                  if(*ap_y < (FIELD_SIZE - 1))
                      (*ap_y)++;
                   return 0;
                }
               case KEY_UP:
                {
                   if(*ap_y > 0 )
                      (*ap_y)--;
                   return 0;
                }
               case KEY_LEFT:
                {
                   if(*ap_x > 0 )
                      (*ap_x)--;
                   return 0;
                }
               case KEY_RIGHT:
                {
                  if(*ap_x < (FIELD_SIZE - 1))
                      (*ap_x)++;
                   return 0;
                }
            }
         }
        case KEY_ENTER:
         return 1;
   }
   return 0;
}
// ------------------------------------------------------------
int check_field (int field[][N], struct ship shp) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( shp.direction == HORIZONTAL )
        check = check_horizontal(field, shp);
    if( shp.direction == VERTICAL )
        check = check_vertical(field, shp);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct ship shp)
{
    int check = 1;  // true
    int from_x = (shp.x == 0)? shp.x : shp.x-1;
    int to_x = (shp.x + shp.len >= N)? N-1 : shp.x + shp.len;
    int from_y = (shp.y == 0)? shp.y : shp.y-1;
    int to_y = (shp.y+1 >= N)? N-1 : shp.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct ship shp)
{
    int check = 1;      // true
    int from_x = (shp.x == 0)? shp.x : shp.x-1;
    int to_x = (shp.x+1 >= N)? N-1 : shp.x+1;
    int from_y = (shp.y == 0)? shp.y : shp.y-1;
    int to_y = (shp.y + shp.len >= N)? N-1 : shp.y + shp.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
Миниатюры
Консольный "Морской бой"  
0
2305 / 1131 / 702
Регистрация: 25.04.2016
Сообщений: 3,222
05.06.2020, 18:07 7
я уже говорил вам про интеграцию, вот вам пример обстрела всего поля с кораблями:
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
enum { HORIZONTAL=777, VERTICAL=666 };
struct ship {
    int x;          // расположение корабля по x (от 0 до N-1)
    int y;          // расположение корабля по y (от 0 до N-1)
    int direction;  // положение корабля: 777 - horizontal, 666 - vertical
    int len;        // количество палуб корабля (от 1 до 4)
};
 
void draw_filed (int field[][N]);                           // выводим поле
void generate_battlefield (int field[][N]);                 // заполняем корытцами
int check_field (int field[][N], struct ship boat);         // есть ли место на поле?
int check_horizontal (int field[][N], struct ship boat);    // место по горизонтали?
int check_vertical (int field[][N], struct ship boat);      // а по вертикали?
 
int main (void) {
    srand( (unsigned int)time(NULL)/2 );
    int field[N][N] = {0};
    generate_battlefield(field);
    draw_filed(field);
 
    // постейший алгоритм стрельбы:
    int shots = 0;          // сколько выстрелов было сделано
    int shot_x, shot_y;     // координаты выстрела
 
    while (shots < 100) {   // пока на поле есть место куда стрелять
 
        do {    // стреляем
            shot_x = rand() %N;     // случайные координаты выстрела
            shot_y = rand() %N;
        } while (field[shot_x][shot_y] == 2 || field[shot_x][shot_y] == 3);
 
        shots += 1;                 // увеличиваем число сделанных выстрелов
        if( field[shot_x][shot_y] == 1 ) field[shot_x][shot_y] = 2; // попал
        if( field[shot_x][shot_y] == 0 ) field[shot_x][shot_y] = 3; // мимо
        // field[shot_x][shot_y] = ( field[shot_x][shot_y] == 1 )? 2 : 3;
        draw_filed(field);          // выводим поле после выстрела на экран
    }
 
    return 0;
}
// ------------------------------------------------------------
void draw_filed (int field[][N]) {
    for (int i=0; i<N; ++i)     // номера позиций
        printf("%c", i+'A');
    puts("");
 
    for (int i=0; i<N; ++i)     // верхняя граница
        printf("-");
    printf("+\n");
 
    // char symbol;
    char legend[] = " &* ";     // легенда карты, заменяет пачку if(..) symbol =..
    for (int i=0; i<N; ++i, puts(""))
        for (int k=0; k<N; ++k) {
            //if( field[i][k] == 0 ) symbol = ' ';      // пустое место
            //if( field[i][k] == 1 ) symbol = '&';      // корабль
            //if( field[i][k] == 2 ) symbol = '*';      // подбитый корабль
            //if( field[i][k] == 3 ) symbol = ' ';      // попадание в 'молоко'
            //printf("%c", symbol);
            printf("%c", legend[ field[i][k] ]);
            if (k == N-1) printf("| %-2d", i+1);        // номера позиций
        }
 
    for (int i=0; i<N; ++i)     // нижняя граница
        printf("-");
    printf("+\n\n");
}
// ------------------------------------------------------------
void generate_battlefield (int field[][N]) {
    int ship_count;     // количество кораблей в зависимости от длины корыта
    struct ship boat;
    for (int i=4; i>0; --i) {   // количество палуб
        ship_count = 5 - i;
        for (int k=0; k<ship_count; ++k) {      // количество кораблей
            boat.len = i;
            // проверяем, есть ли место для корабля:
            do {
                boat.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( boat.direction == HORIZONTAL ) {
                    boat.y = rand() %N;
                    boat.x = rand() %( (i==1)? N : N-i );
                }
                if( boat.direction == VERTICAL ) {
                    boat.y = rand() %( (i==1)? N : N-i );
                    boat.x = rand() %N;
                }
            } while ( check_field(field, boat) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if( boat.direction == HORIZONTAL ){
                for (int x=0; x<boat.len; ++x)
                    field[boat.y][boat.x+x] = 1;
            }
            if( boat.direction == VERTICAL ) {
                for (int y=0; y<boat.len; ++y)
                    field[boat.y+y][boat.x] = 1;
            }
        }
    }
}
// ------------------------------------------------------------
int check_field (int field[][N], struct ship shp) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( shp.direction == HORIZONTAL )
        check = check_horizontal(field, shp);
    if( shp.direction == VERTICAL )
        check = check_vertical(field, shp);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct ship shp) {
    int check = 1;      // true
    int from_x  = (shp.x == 0)? shp.x : shp.x-1;
    int to_x    = (shp.x + shp.len >= N)? N-1 : shp.x + shp.len;
    int from_y  = (shp.y == 0)? shp.y : shp.y-1;
    int to_y    = (shp.y+1 >= N)? N-1 : shp.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct ship shp) {
    int check = 1;      // true
    int from_x  = (shp.x == 0)? shp.x : shp.x-1;
    int to_x    = (shp.x+1 >= N)? N-1 : shp.x+1;
    int from_y  = (shp.y == 0)? shp.y : shp.y-1;
    int to_y    = (shp.y + shp.len >= N)? N-1 : shp.y + shp.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
Добавлено через 1 минуту
строка 39 заменяет строки 37, 38
0
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
05.06.2020, 18:25  [ТС] 8
Благодарю, сейчас надеюсь солянка заработает )
0
2305 / 1131 / 702
Регистрация: 25.04.2016
Сообщений: 3,222
05.06.2020, 19:29 9
В таком виде компьютер будет стрелять по нашим кораблям.. вернее по полю до тех пор, пока на поле есть хотя бы 1 клетка, по которой он еще не стрелял. Как минимум нам стоит изменить условие, т.е. чтобы компьютер стрелял до тех пор, пока на поле есть хотя бы одна непотопленная палуба, т.е. нам нужно повторять цикл до тех пор, пока в массиве field[][] есть хотя бы одна ячейка со значением 1:
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
enum { HORIZONTAL=777, VERTICAL=666 };
struct ship {
    int x;          // расположение корабля по x (от 0 до N-1)
    int y;          // расположение корабля по y (от 0 до N-1)
    int direction;  // положение корабля: 777 - horizontal, 666 - vertical
    int len;        // количество палуб корабля (от 1 до 4)
};
 
void draw_filed (int field[][N]);                           // выводим поле
void generate_battlefield (int field[][N]);                 // заполняем корытцами
int check_field (int field[][N], struct ship boat);         // есть ли место на поле?
int check_horizontal (int field[][N], struct ship boat);    // место по горизонтали?
int check_vertical (int field[][N], struct ship boat);      // а по вертикали?
int we_can_shoot (int field[][N]);                          // можем ли мы стрелять?
 
int main (void) {
    srand( (unsigned int)time(NULL)/2 );
    int field[N][N] = {0};
    generate_battlefield(field);
    draw_filed(field);
 
    // постейший алгоритм стрельбы:
    int shot_x, shot_y;     // координаты выстрела
 
    while( we_can_shoot(field) == 1 ) {
        // пока на поле есть место куда стрелять, т.е. пока на поле есть
        // хотя бы одна необстрелянная палуба корабля:
 
        // генерируем случайные координаты выстрела:
        do {
            shot_x = rand() %N;     // случайные координаты выстрела
            shot_y = rand() %N;
        } while( field[shot_x][shot_y] == 2 || field[shot_x][shot_y] == 3 );
        // ^^^ если в эту клетку мы уже стреляли, гененрируем снова ^^^
 
        // стреляем:
        //if( field[shot_x][shot_y] == 1 ) field[shot_x][shot_y] = 2;   // попал
        //if( field[shot_x][shot_y] == 0 ) field[shot_x][shot_y] = 3;   // мимо
        field[shot_x][shot_y] = ( field[shot_x][shot_y] == 1 )? 2 : 3;
 
        // выводим поле после выстрела на экран:
        draw_filed(field);
    }
 
    printf("Your fleet was destroyed\n");
 
    return 0;
}
// ------------------------------------------------------------
void draw_filed (int field[][N]) {
    for (int i=0; i<N; ++i)     // номера позиций
        printf("%c", i+'A');
    puts("");
 
    for (int i=0; i<N; ++i)     // верхняя граница
        printf("-");
    printf("+\n");
 
    char legend[] = " &* ";     // легенда карты
    for (int i=0; i<N; ++i, puts(""))
        for (int k=0; k<N; ++k) {
            printf("%c", legend[ field[i][k] ]);
            if (k == N-1) printf("| %d", i+1);      // номера позиций
        }
 
    for (int i=0; i<N; ++i)     // нижняя граница
        printf("-");
    printf("+\n\n");
}
// ------------------------------------------------------------
void generate_battlefield (int field[][N]) {
    int ship_count;     // количество кораблей в зависимости от длины корыта
    struct ship boat;
    for (int i=4; i>0; --i) {   // количество палуб
        ship_count = 5 - i;
        for (int k=0; k<ship_count; ++k) {      // количество кораблей
            boat.len = i;
            // проверяем, есть ли место для корабля:
            do {
                boat.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( boat.direction == HORIZONTAL ) {
                    boat.y = rand() %N;
                    boat.x = rand() %( (i==1)? N : N-i );
                }
                if( boat.direction == VERTICAL ) {
                    boat.y = rand() %( (i==1)? N : N-i );
                    boat.x = rand() %N;
                }
            } while ( check_field(field, boat) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if( boat.direction == HORIZONTAL ){
                for (int x=0; x<boat.len; ++x)
                    field[boat.y][boat.x+x] = 1;
            }
            if( boat.direction == VERTICAL ) {
                for (int y=0; y<boat.len; ++y)
                    field[boat.y+y][boat.x] = 1;
            }
        }
    }
}
// ------------------------------------------------------------
int check_field (int field[][N], struct ship shp) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( shp.direction == HORIZONTAL )
        check = check_horizontal(field, shp);
    if( shp.direction == VERTICAL )
        check = check_vertical(field, shp);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct ship shp) {
    int check = 1;      // true
    int from_x  = (shp.x == 0)? shp.x : shp.x-1;
    int to_x    = (shp.x + shp.len >= N)? N-1 : shp.x + shp.len;
    int from_y  = (shp.y == 0)? shp.y : shp.y-1;
    int to_y    = (shp.y+1 >= N)? N-1 : shp.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct ship shp) {
    int check = 1;      // true
    int from_x  = (shp.x == 0)? shp.x : shp.x-1;
    int to_x    = (shp.x+1 >= N)? N-1 : shp.x+1;
    int from_y  = (shp.y == 0)? shp.y : shp.y-1;
    int to_y    = (shp.y + shp.len >= N)? N-1 : shp.y + shp.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int we_can_shoot (int field[][N]) {
    int check = 0;      // false
    for (int y = 0; y < N && !check; ++y)
        for (int x = 0; x < N && !check; ++x)
            if( field[y][x] == 1 ) check = 1;   // true
    return check;
}
// ------------------------------------------------------------
При этом нам совершенно не важно сколько выстрелов мы сделали, поскольку наш алгоритм проверяет уже обстрелянные клетки поля, и не позволит выстрелить в одну и ту же клетку дважды.

Конечно, в таком виде испоьзовать этот алгоритм как какое-то подобие ИИ не стоит, посокльку после попадания по кораблю, компьютеру необходимо хотя бы обстрелять соседние клетки и удостовериться, что он полностью потопил корабль.. ну как минимум.

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

Тогда можно просто пробегать по массиву кораблей и смотреть есть ли еще неповрежденные палубы, тогда и проверка на возможность сделать выстрел сокращается в разы, поскольку опросить массив из 10 кораблей куда быстрее, чем все игровое поле 10 на 10.

И я уж молчу про какую-то продвинутую логику, вроде деления поля на клетки 4х4, 3х3 и т.д. и планомерный и целеноправленный их обстрел.

Добавлено через 29 минут
Как вариант, нам известно сколько у нас кораблей и сколько у них палуб, так что мы можем посчитать общее количество палуб всех кораблей на поле и просто стрелять, пока количество поврежденных палуб не станет равным общему числу палуб флота:
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
enum { HORIZONTAL=777, VERTICAL=666 };
struct ship {
    int x;          // расположение корабля по x (от 0 до N-1)
    int y;          // расположение корабля по y (от 0 до N-1)
    int direction;  // положение корабля: 777 - horizontal, 666 - vertical
    int len;        // количество палуб корабля (от 1 до 4)
};
 
void draw_filed (int field[][N]);                           // выводим поле
void generate_battlefield (int field[][N]);                 // заполняем корытцами
int check_field (int field[][N], struct ship boat);         // есть ли место на поле?
int check_horizontal (int field[][N], struct ship boat);    // место по горизонтали?
int check_vertical (int field[][N], struct ship boat);      // а по вертикали?
 
int main (void) {
    srand( (unsigned int)time(NULL)/2 );
    int field[N][N] = {0};
    generate_battlefield(field);
    draw_filed(field);
 
    // постейший алгоритм стрельбы:
    int fleet_decks = 20;   // общее число палуб = 4*1 + 3*2 + 2*3 + 1*4 = 4+6+6+4 = 20
    int decks = 0;          // количество поврежденных палуб
    int shot_x, shot_y;     // координаты выстрела
 
    while( decks < fleet_decks ) {
    // пока на поле есть хотя бы одна неповрежденная палуба корабля:
 
        // генерируем случайные координаты выстрела:
        do {
            shot_x = rand() %N;     // случайные координаты выстрела
            shot_y = rand() %N;
        } while( field[shot_y][shot_x] == 2 || field[shot_y][shot_x] == 3 );
 
        // стреляем:
        field[shot_y][shot_x] = ( field[shot_y][shot_x] == 1 )? 2 : 3;
        if( field[shot_y][shot_x] == 2 ) ++decks;   // если попали
 
        // выводим поле после выстрела на экран:
        draw_filed(field);
    }
 
    printf("Your fleet was destroyed\n");
 
    return 0;
}
// ------------------------------------------------------------
void draw_filed (int field[][N]) {
    for (int i=0; i<N; ++i)     // номера позиций
        printf("%c", i+'A');
    puts("");
 
    for (int i=0; i<N; ++i)     // верхняя граница
        printf("-");
    printf("+\n");
 
    char legend[] = " &* ";     // легенда карты
    for (int i=0; i<N; ++i, puts(""))
        for (int k=0; k<N; ++k) {
            printf("%c", legend[ field[i][k] ]);
            if (k == N-1) printf("| %d", i+1);      // номера позиций
        }
 
    for (int i=0; i<N; ++i)     // нижняя граница
        printf("-");
    printf("+\n\n");
}
// ------------------------------------------------------------
void generate_battlefield (int field[][N]) {
    int ship_count;     // количество кораблей в зависимости от длины корыта
    struct ship boat;
    for (int i=4; i>0; --i) {   // количество палуб
        ship_count = 5 - i;
        for (int k=0; k<ship_count; ++k) {      // количество кораблей
            boat.len = i;
            // проверяем, есть ли место для корабля:
            do {
                boat.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( boat.direction == HORIZONTAL ) {
                    boat.y = rand() %N;
                    boat.x = rand() %( (i==1)? N : N-i );
                }
                if( boat.direction == VERTICAL ) {
                    boat.y = rand() %( (i==1)? N : N-i );
                    boat.x = rand() %N;
                }
            } while ( check_field(field, boat) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if( boat.direction == HORIZONTAL ){
                for (int x=0; x<boat.len; ++x)
                    field[boat.y][boat.x+x] = 1;
            }
            if( boat.direction == VERTICAL ) {
                for (int y=0; y<boat.len; ++y)
                    field[boat.y+y][boat.x] = 1;
            }
        }
    }
}
// ------------------------------------------------------------
int check_field (int field[][N], struct ship shp) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( shp.direction == HORIZONTAL )
        check = check_horizontal(field, shp);
    if( shp.direction == VERTICAL )
        check = check_vertical(field, shp);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct ship shp) {
    int check = 1;      // true
    int from_x  = (shp.x == 0)? shp.x : shp.x-1;
    int to_x    = (shp.x + shp.len >= N)? N-1 : shp.x + shp.len;
    int from_y  = (shp.y == 0)? shp.y : shp.y-1;
    int to_y    = (shp.y+1 >= N)? N-1 : shp.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct ship shp) {
    int check = 1;      // true
    int from_x  = (shp.x == 0)? shp.x : shp.x-1;
    int to_x    = (shp.x+1 >= N)? N-1 : shp.x+1;
    int from_y  = (shp.y == 0)? shp.y : shp.y-1;
    int to_y    = (shp.y + shp.len >= N)? N-1 : shp.y + shp.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
0
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
05.06.2020, 20:48  [ТС] 10
ИИ это вещь интересная, правда у меня почему то не получается интегрировать вывод символов.
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
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
/*
 
.....ABCDEFGHIJ........ABCDEFGHIJ
....*----------*......*----------*
...0|..........|.....0|..........|
...1|..........|.....1|..........|
...2|..........|.....2|..........|
...3|..........|.....3|..........|
...4|..........|.....4|..........|
...5|..........|.....5|..........|
...6|..........|.....6|..........|
...7|..........|.....7|..........|
...8|..........|.....8|..........|
...9|..........|.....9|..........|
....*----------*......*----------*
 
*/
enum { HORIZONTAL=777, VERTICAL=666 };
struct ship {
    int x;          // расположение корабля по x (от 0 до N-1)
    int y;          // расположение корабля по y (от 0 до N-1)
    int direction;  // положение корабля: 777 - horizontal, 666 - vertical
    int len;        // количество палуб корабля (от 1 до 4)
};
typedef enum
{
 INIT = 0
 ,DRAW
 ,PROCESSING
 ,EXIT
}eGameState;
typedef enum
{
 EMPTY = 0
 ,SHOT
 ,STRIKE
 ,KILL
 ,SHIP
 ,EFILD_INFO_END
}eFieldInfo;
 
char draw_symbol[EFILD_INFO_END]=
{
     ' ' //EMPTY
    ,'&' //SHIP
    ,'X' //STRIKE
    ,'#' //KILL
    ,'*' //SHOT
 
};
#define PLAYER_1 0
#define PLAYER_2 ~PLAYER_1
 
#define ARROW_KEY_PRESSED   0xE0
#define KEY_ENTER           13
#define KEY_UP              72
#define KEY_RIGHT           77
#define KEY_DOWN            80
#define KEY_LEFT            75
 
#define TARGET             '+'
 
#define N_Lines 13
#define FIELD_SIZE 10
#define N 10
char *FIELD [] =
{
 "  ABCDEFGHIJ        ABCDEFGHIJ "
," *----------*      *----------*"
,"0|          |     0|          |"
,"1|          |     1|          |"
,"2|          |     2|          |"
,"3|          |     3|          |"
,"4|          |     4|          |"
,"5|          |     5|          |"
,"6|          |     6|          |"
,"7|          |     7|          |"
,"8|          |     8|          |"
,"9|          |     9|          |"
," *----------*      *----------*"
};
int we_can_shoot (int field[][N]);                          // можем ли мы стрелять?
int check_field (int field[][N], struct ship boat);         // есть ли место на поле?
int check_horizontal (int field[][N], struct ship boat);    // место по горизонтали?
int check_vertical (int field[][N], struct ship boat);      // а по вертикали?
void draw_field(eFieldInfo *,eFieldInfo *, unsigned short);
void ship_generate(int field[][N]);
void ship_enter(eFieldInfo *,unsigned short a_target);
unsigned char get_target_position(unsigned char*, unsigned char*);
//--------------------------------------------------------
int main()
{
    eGameState game_state = INIT;
    unsigned char isRun = 1;
 
    int player = PLAYER_1;
    srand( (unsigned int)time(NULL)/2 );
   //int field[N][N] = {0};
 
    eFieldInfo p1_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_data [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo p1_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
    eFieldInfo p2_enter [FIELD_SIZE * FIELD_SIZE] = {EMPTY};
 
    eFieldInfo *tmp,*kil;
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
    unsigned short shot_position = 0;
 
    while(isRun)
    {
        switch (game_state)
        {
        case INIT:
            {
                ship_generate(p1_data);
                ship_generate(p2_data);
 
               // p1_data [0] = KILL;
 
                game_state = DRAW;
                break;
            }
        case DRAW:
            {
                system("cls");
 
                tmp = (player == PLAYER_1) ? p1_data : p2_data;
                kil = (player == PLAYER_1) ? p1_enter : p2_enter;
 
                draw_field(tmp,kil,shot_position);
 
                if(get_target_position  (&target_x, &target_y) )
                {
                    game_state = PROCESSING;
                }
                shot_position = (target_y << 8) | (target_x);
                break;
            }
        case PROCESSING:
            {
 
                ship_enter(p1_enter,shot_position );
                player = ~player;
                ship_enter(p2_enter,shot_position );
 
                game_state = DRAW;
                break;
            }
        case EXIT:
            {
                break;
            }
        }
    }
 
 
 
    return 0;
}
 
void draw_field(eFieldInfo *ap_data,eFieldInfo *ap_enter, unsigned short a_target)
{
    printf("%s\n",FIELD[0]);
    printf("%s\n",FIELD[1]);
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
 
    target_x = a_target;
    target_y = a_target >> 8;
 
    for(int i=0; i < 10; ++i)
    {
        printf("%c%c",FIELD[i + 2][0],FIELD[i + 2][1]);
 
        for(int j=0; j < FIELD_SIZE; ++j) // print field 1 data
           {
               printf("%c", draw_symbol [ ap_data[i * FIELD_SIZE + j]]);
 
           }
 
        for(int j=12; j < 20; ++j)
           printf("%c",FIELD[i + 2][j]);
 
         for(int j=0; j < FIELD_SIZE; ++j) // print field 2 data
           {
 
               if (i == target_y && j== target_x)
                 printf("%c", TARGET);
               else
               {
            if ( ap_enter[i * FIELD_SIZE + j] == 0 )
          ap_enter[i * FIELD_SIZE + j]= EMPTY;       // пустое место
           if( ap_enter[i * FIELD_SIZE + j] == 1 )
          ap_enter[i * FIELD_SIZE + j]= SHOT;      // корабль
            if( ap_enter[i * FIELD_SIZE + j] == 2 )
          ap_enter[i * FIELD_SIZE + j]= SHIP;      // подбитый корабль
            if( ap_enter[i * FIELD_SIZE + j] == 3 )
          ap_enter[i * FIELD_SIZE + j]= KILL;      // попадание в 'молоко'
                printf("%c", draw_symbol [ ap_enter[i * FIELD_SIZE + j]]);
 
               }
           }
 
        printf("%c\n",FIELD[i + 2][30]);
    }
 
    printf("%s\n",FIELD[N_Lines - 1]);
}
 
void ship_enter(eFieldInfo *ap_enter,unsigned short a_target)
{
 
    unsigned char target_x = 0;
    unsigned char target_y = 0;
    unsigned short shot_position = 0;
 
    //target_x = a_target;
    //target_y = a_target >> 8;
 
//ap_enter[target_y * 10 + target_x] = STRIKE;
       while( we_can_shoot(ap_enter) == 1 )
 
            {
                shot_position = (target_y << 8) | (target_x);
                while (shot_position < 100) {   // пока на поле есть место куда стрелять
 
        do {    // стреляем
               target_x = a_target;
               target_y = a_target >> 8;
        } while (ap_enter[target_y * 10 + target_x] == 2 || ap_enter[target_y * 10 + target_x] == 3);
 
        shot_position += 1;                 // увеличиваем число сделанных выстрелов
        if( ap_enter[target_y * 10 + target_x] == 1 ) ap_enter[target_y * 10 + target_x] = 2; // попал
        if( ap_enter[target_y * 10 + target_x] == 0 ) ap_enter[target_y * 10 + target_x] = 3; // мимо
        // field[shot_x][shot_y] = ( field[shot_x][shot_y] == 1 )? 2 : 3;
        //draw_filed(ap_enter);          // выводим поле после выстрела на экран
    }}
 
}
 
 
void ship_generate(int field[][N])
{
    /*
      0123456789
    0|&    &  & |
    1|  &  &    |
    2|  &  &   &|
    3|         &|
    4|      &   |
    5|&        &|
    6|&         |
    7|&     &&&&|
    8|&         |
    9|   &&  && |
 
    */
    // i*n+j
int ship_count;     // количество кораблей в зависимости от длины корыта
    struct ship boat;
    for (int i=4; i>0; --i) {   // количество палуб
        ship_count = 5 - i;
        for (int k=0; k<ship_count; ++k) {      // количество кораблей
            boat.len = i;
            // проверяем, есть ли место для корабля:
            do {
                boat.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( boat.direction == HORIZONTAL ) {
                    boat.y = rand() %N;
                    boat.x = rand() %( (i==1)? N : N-i );
                }
                if( boat.direction == VERTICAL ) {
                    boat.y = rand() %( (i==1)? N : N-i );
                    boat.x = rand() %N;
                }
            } while ( check_field(field, boat) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if ( boat.direction == HORIZONTAL ){
                for (int x=0; x<boat.len; ++x)
                    field[boat.y][boat.x+x] = 1;
            }
            if( boat.direction == VERTICAL ) {
                for (int y=0; y<boat.len; ++y)
                    field[boat.y+y][boat.x] = 1;
            }
        }
    }
}
//---------------------------------------------------------
unsigned char get_target_position(unsigned char *ap_x, unsigned char *ap_y)
{
   int key = 0;
   key = getch();
   switch (key)
   {
      case ARROW_KEY_PRESSED:
         {
             switch (getch())
             {
               case KEY_DOWN:
                 {
                  if(*ap_y < (FIELD_SIZE - 1))
                      (*ap_y)++;
                   return 0;
                }
               case KEY_UP:
                {
                   if(*ap_y > 0 )
                      (*ap_y)--;
                   return 0;
                }
               case KEY_LEFT:
                {
                   if(*ap_x > 0 )
                      (*ap_x)--;
                   return 0;
                }
               case KEY_RIGHT:
                {
                  if(*ap_x < (FIELD_SIZE - 1))
                      (*ap_x)++;
                   return 0;
                }
            }
         }
        case KEY_ENTER:
         return 1;
   }
   return 0;
}
// ------------------------------------------------------------
int check_field (int field[][N], struct ship shp) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( shp.direction == HORIZONTAL )
        check = check_horizontal(field, shp);
    if( shp.direction == VERTICAL )
        check = check_vertical(field, shp);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct ship shp)
{
    int check = 1;  // true
    int from_x = (shp.x == 0)? shp.x : shp.x-1;
    int to_x = (shp.x + shp.len >= N)? N-1 : shp.x + shp.len;
    int from_y = (shp.y == 0)? shp.y : shp.y-1;
    int to_y = (shp.y+1 >= N)? N-1 : shp.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct ship shp)
{
    int check = 1;      // true
    int from_x = (shp.x == 0)? shp.x : shp.x-1;
    int to_x = (shp.x+1 >= N)? N-1 : shp.x+1;
    int from_y = (shp.y == 0)? shp.y : shp.y-1;
    int to_y = (shp.y + shp.len >= N)? N-1 : shp.y + shp.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int we_can_shoot (int field[][N]) {
    int check = 0;      // false
    for (int y = 0; y < N && !check; ++y)
        for (int x = 0; x < N && !check; ++x)
            if( field[y][x] == 1 ) check = 1;   // true
    return check;
}
// ------------------------------------------------------------
Думаю проблема с строчках 199-210, вот только что не так, не могу понять ( программа компилируется, все хорошо, просто не чего не выводит во 2-м поле, кроме курсора )
0
2305 / 1131 / 702
Регистрация: 25.04.2016
Сообщений: 3,222
05.06.2020, 23:21 11
Ну.. почти готовый вариант, комп играет сам с собой. Мне сейчас неоткуда взять машину с windows, поэтому реализовать адекватный ввод с клавиатуры не могу, так что пока оставил для пользователя генерацию случайной позиции выстрела:
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
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
enum { N=10, HORIZONTAL=777, VERTICAL=666,
    INIT=0, DRAW, LOGIC, EXIT, PLAYER=1, ENEMY=-1 };
struct cruiser { int x, y, direction, len; };
 
void draw_field (int player[][N], int enemy[][N]);          // выводим поле
void generate_battlefield (int field[][N]);                 // заполняем корытцами
int check_field (int field[][N], struct cruiser ship);      // есть ли место на поле?
int check_horizontal (int field[][N], struct cruiser ship); // место по горизонтали?
int check_vertical (int field[][N], struct cruiser ship);   // а по вертикали?
int doit (int player[][N], int enemy[][N], int user);       // ходы игроков
void enemy_shot (int *x, int *y, int field[][N]);           // ход компьютера
void player_shot (int *x, int *y, int field[][N]);          // ход игрока (переделать!)
 
int main (void) {
    int eGameState = INIT;          // начальное состояние автомата
    int player_field[N][N] = {0};   // поле игрока
    int enemy_field[N][N] = {0};    // поле противника
    int player = PLAYER;            // первым ходит игрок
    int result;                     // результат логической проверки хода
 
    while( eGameState != EXIT ) {
        switch (eGameState) {
            case INIT:
                srand( (unsigned int)time(NULL)/2 );
                generate_battlefield(player_field);
                generate_battlefield(enemy_field);
                eGameState = DRAW;
                break;
            case DRAW:
                draw_field(player_field, enemy_field);
                eGameState = LOGIC;
                break;
            case LOGIC:
                result = doit(player_field, enemy_field, player);
                switch (result) {
                    case 0:
                        // неудачный выстрел
                        player = -player;
                        eGameState = DRAW;
                        break;
                    case PLAYER:
                        // игрок победил
                        puts("Congratulation! You won!");
                        eGameState = EXIT;
                        break;
                    case ENEMY:
                        // игрок проиграл
                        puts("Your fleet was destroyed! You loose.");
                        eGameState = EXIT;
                        break;
                    default:
                        // удачный выстрел
                        eGameState = DRAW;
                }
        }
    }
 
    return 0;
}
// ------------------------------------------------------------
void draw_field (int player[][N], int enemy[][N]) {
    system("clear");    // system("cls"); for windows
    // base screen of game
    char screen[14][33] = {
        "  ABCDEFGHIJ        ABCDEFGHIJ  ",
        " +----------+      +----------+ ",
        "0|          |0    0|          |0",
        "1|          |1    1|          |1",
        "2|          |2    2|          |2",
        "3|          |3    3|          |3",
        "4|          |4    4|          |4",
        "5|          |5    5|          |5",
        "6|          |6    6|          |6",
        "7|          |7    7|          |7",
        "8|          |8    8|          |8",
        "9|          |9    9|          |9",
        " +----------+      +----------+ ",
        "  ABCDEFGHIJ        ABCDEFGHIJ  "
    };
    // copy player date:
    char legend[] = " &* ";
    int pos_x = 2;
    int pos_y = 2;
    for (int y=0; y<N; ++y)
        for (int x=0; x<N; ++x)
            screen[pos_y+y][pos_x+x] = legend[ player[y][x] ];
    // copy enemy date:
    pos_x = 20;
    pos_y = 2;
    char another[] = "  x-";
    for (int y=0; y<N; ++y)
        for (int x=0; x<N; ++x)
            screen[pos_y+y][pos_x+x] = another[ enemy[y][x] ];
    // put screen on the terminal
    for (int i=0; i<14; ++i)
        puts(screen[i]);
    puts("");
}
// ------------------------------------------------------------
void generate_battlefield (int field[][N]) {
    int count_ship;     // количество кораблей в зависимости от длины корыта
    struct cruiser ship;
    for (int i=4; i>0; --i) {   // количество палуб
        count_ship = 5 - i;
        for (int k=0; k<count_ship; ++k) {      // количество кораблей
            ship.len = i;
            // проверяем, есть ли место для корабля:
            do {
                ship.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( ship.direction == HORIZONTAL ) {
                    ship.y = rand() %N;
                    ship.x = rand() %( (i==1)? N : N-i );
                }
                if( ship.direction == VERTICAL ) {
                    ship.y = rand() %( (i==1)? N : N-i );
                    ship.x = rand() %N;
                }
            } while ( check_field(field, ship) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if( ship.direction == HORIZONTAL ){
                for (int x=0; x<ship.len; ++x)
                    field[ship.y][ship.x+x] = 1;
            }
            if( ship.direction == VERTICAL ) {
                for (int y=0; y<ship.len; ++y)
                    field[ship.y+y][ship.x] = 1;
            }
        }
    }
}
// ------------------------------------------------------------
int check_field (int field[][N], struct cruiser ship) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( ship.direction == HORIZONTAL )
        check = check_horizontal(field, ship);
    if( ship.direction == VERTICAL )
        check = check_vertical(field, ship);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct cruiser ship) {
    int check = 1;      // true
    int from_x  = (ship.x == 0)? ship.x : ship.x-1;
    int to_x    = (ship.x + ship.len >= N)? N-1 : ship.x + ship.len;
    int from_y  = (ship.y == 0)? ship.y : ship.y-1;
    int to_y    = (ship.y+1 >= N)? N-1 : ship.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct cruiser ship) {
    int check = 1;      // true
    int from_x  = (ship.x == 0)? ship.x : ship.x-1;
    int to_x    = (ship.x+1 >= N)? N-1 : ship.x+1;
    int from_y  = (ship.y == 0)? ship.y : ship.y-1;
    int to_y    = (ship.y + ship.len >= N)? N-1 : ship.y + ship.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int doit(int player[][N], int enemy[][N], int user) {
    int max_decks = 20;         // всего палуб
    static int pl_decks = 0;    // количество уничтоженных палуб игрока
    static int en_decks = 0;    // количество уничтоженных палуб противника
    int shot_x, shot_y;         // координаты выстрела
 
    if( pl_decks == max_decks ) return ENEMY;
    if( en_decks == max_decks ) return PLAYER;
 
    if( user == PLAYER ) {
        player_shot(&shot_x, &shot_y, enemy);
        enemy[shot_y][shot_x] = ( enemy[shot_y][shot_x] == 1 )? 2 : 3;
        if( enemy[shot_y][shot_x] == 2 ) { ++en_decks; return 2; }
    }
    if( user == ENEMY ) {
        enemy_shot(&shot_x, &shot_y, player);
        player[shot_y][shot_x] = ( player[shot_y][shot_x] == 1 )? 2 : 3;
        if( player[shot_y][shot_x] == 2 ) { ++pl_decks; return 2; }
    }
 
    return 0;
}
// ------------------------------------------------------------
void enemy_shot (int *x, int *y, int field[][N]) {
    int shot_x, shot_y;
 
    do {
        shot_x = rand() %N;
        shot_y = rand() %N;
    } while( field[shot_y][shot_x] == 2 || field[shot_y][shot_x] == 3 );
 
    *x = shot_x;
    *y = shot_y;
}
// ------------------------------------------------------------
void player_shot (int *x, int *y, int field[][N]) {
    /* *************************************************************
     * Cейчас ходы игрока генерируются случайно, точно так же, как и
     * ходы компьютера. Вместо этого необходимо реализовать здесь
     * получение координат от игрока.
     *
     * По сути вместо кода этой функции у вас тут должна быть ваша
     * функция get_target_position().
     * ************************************************************/
 
    int shot_x, shot_y;
 
    do {
        shot_x = rand() %N;
        shot_y = rand() %N;
    } while( field[shot_y][shot_x] == 2 || field[shot_y][shot_x] == 3 );
 
    *x = shot_x;
    *y = shot_y;
}
// ------------------------------------------------------------
0
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
06.06.2020, 05:43  [ТС] 12
Большое спасибо за почти готовый кодс, правда там все немного по другому реализовано, сложновато понять. Так что, пока курсор не хочет интегрироваться, но надеюсь что завтра у меня наконец то все получиться
Миниатюры
Консольный "Морской бой"  
0
2305 / 1131 / 702
Регистрация: 25.04.2016
Сообщений: 3,222
06.06.2020, 19:07 13
Лучший ответ Сообщение было отмечено Keitaro_Fox как решение

Решение

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
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
enum { N=10, HORIZONTAL=777, VERTICAL=666, INIT=0, DRAW, LOGIC, EXIT,
    PLAYER=1, ENEMY=-1, ARROW_KEY_PRESSED=0xE0, KEY_ENTER=13,
    KEY_UP=72, KEY_LEFT=75, KEY_RIGHT=77, KEY_DOWN=80 };
struct cruiser { int x, y, direction, len; };
 
void draw_field (int player[][N], int enemy[][N]);          // выводим поле
void generate_battlefield (int field[][N]);                 // заполняем корытцами
int check_field (int field[][N], struct cruiser ship);      // есть ли место на поле?
int check_horizontal (int field[][N], struct cruiser ship); // место по горизонтали?
int check_vertical (int field[][N], struct cruiser ship);   // а по вертикали?
int doit (int player[][N], int enemy[][N], int user);       // ходы игроков
void enemy_shot (int *x, int *y, int field[][N]);           // ход компьютера
void player_shot (int *x, int *y, int player[][N], int enemy[][N]); // ход игрока
 
int main (void) {
    int eGameState = INIT;          // начальное состояние автомата
    int player_field[N][N] = {0};   // поле игрока
    int enemy_field[N][N] = {0};    // поле противника
    int player = PLAYER;            // первым ходит игрок
    int result;                     // результат логической проверки хода
 
    while( eGameState != EXIT ) {
        switch (eGameState) {
            case INIT:
                srand( (unsigned int)time(NULL)/2 );
                generate_battlefield(player_field);
                generate_battlefield(enemy_field);
                eGameState = DRAW;
                break;
            case DRAW:
                draw_field(player_field, enemy_field);
                eGameState = LOGIC;
                break;
            case LOGIC:
                result = doit(player_field, enemy_field, player);
                switch (result) {
                    case 0:
                        // неудачный выстрел
                        player = -player;
                        eGameState = DRAW;
                        break;
                    case PLAYER:
                        // игрок победил
                        puts("Congratulation! You won!");
                        eGameState = EXIT;
                        break;
                    case ENEMY:
                        // игрок проиграл
                        puts("Your fleet was destroyed! You loose.");
                        eGameState = EXIT;
                        break;
                    default:
                        // удачный выстрел
                        eGameState = DRAW;
                }
        }
    }
 
    return 0;
}
// ------------------------------------------------------------
void draw_field (int player[][N], int enemy[][N]) {
    system("cls");  // system("clear"); for linux or system("cls"); for windows
    // base screen of game
    char screen[14][33] = {
        "  ABCDEFGHIJ        ABCDEFGHIJ  ",
        " +----------+      +----------+ ",
        "0|          |0    0|          |0",
        "1|          |1    1|          |1",
        "2|          |2    2|          |2",
        "3|          |3    3|          |3",
        "4|          |4    4|          |4",
        "5|          |5    5|          |5",
        "6|          |6    6|          |6",
        "7|          |7    7|          |7",
        "8|          |8    8|          |8",
        "9|          |9    9|          |9",
        " +----------+      +----------+ ",
        "  ABCDEFGHIJ        ABCDEFGHIJ  "
    };
    // copy player date:
    char legend[] = " &* ";
    int pos_x = 2;
    int pos_y = 2;
    for (int y=0; y<N; ++y)
        for (int x=0; x<N; ++x)
            screen[pos_y+y][pos_x+x] = legend[ player[y][x] ];
    // copy enemy date:
    pos_x = 20;
    pos_y = 2;
    char another[] = "  x-+";
    for (int y=0; y<N; ++y)
        for (int x=0; x<N; ++x)
            screen[pos_y+y][pos_x+x] = another[ enemy[y][x] ];
    // put screen on the terminal
    for (int i=0; i<14; ++i)
        puts(screen[i]);
    puts("");
}
// ------------------------------------------------------------
void generate_battlefield (int field[][N]) {
    int count_ship;     // количество кораблей в зависимости от длины корыта
    struct cruiser ship;
    for (int i=4; i>0; --i) {   // количество палуб
        count_ship = 5 - i;
        for (int k=0; k<count_ship; ++k) {      // количество кораблей
            ship.len = i;
            // проверяем, есть ли место для корабля:
            do {
                ship.direction = (rand() %2)? VERTICAL : HORIZONTAL;
                if( ship.direction == HORIZONTAL ) {
                    ship.y = rand() %N;
                    ship.x = rand() %( (i==1)? N : N-i );
                }
                if( ship.direction == VERTICAL ) {
                    ship.y = rand() %( (i==1)? N : N-i );
                    ship.x = rand() %N;
                }
            } while ( check_field(field, ship) < 1 );
 
            // заполняем поле палубами корабля в заданном направлении
            if( ship.direction == HORIZONTAL ){
                for (int x=0; x<ship.len; ++x)
                    field[ship.y][ship.x+x] = 1;
            }
            if( ship.direction == VERTICAL ) {
                for (int y=0; y<ship.len; ++y)
                    field[ship.y+y][ship.x] = 1;
            }
        }
    }
}
// ------------------------------------------------------------
int check_field (int field[][N], struct cruiser ship) {
    int check;      // 1 - успешная проверка, 0 - нет
    if( ship.direction == HORIZONTAL )
        check = check_horizontal(field, ship);
    if( ship.direction == VERTICAL )
        check = check_vertical(field, ship);
    return check;
}
// ------------------------------------------------------------
int check_horizontal (int field[][N], struct cruiser ship) {
    int check = 1;      // true
    int from_x  = (ship.x == 0)? ship.x : ship.x-1;
    int to_x    = (ship.x + ship.len >= N)? N-1 : ship.x + ship.len;
    int from_y  = (ship.y == 0)? ship.y : ship.y-1;
    int to_y    = (ship.y+1 >= N)? N-1 : ship.y+1;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int check_vertical (int field[][N], struct cruiser ship) {
    int check = 1;      // true
    int from_x  = (ship.x == 0)? ship.x : ship.x-1;
    int to_x    = (ship.x+1 >= N)? N-1 : ship.x+1;
    int from_y  = (ship.y == 0)? ship.y : ship.y-1;
    int to_y    = (ship.y + ship.len >= N)? N-1 : ship.y + ship.len;
 
    for (int y = from_y; y <= to_y && check; ++y)
        for (int x = from_x; x <= to_x && check; ++x)
            if( field[y][x] == 1 ) check = 0;   // false
 
    return check;
}
// ------------------------------------------------------------
int doit(int player[][N], int enemy[][N], int user) {
    int max_decks = 20;         // всего палуб
    static int pl_decks = 0;    // количество уничтоженных палуб игрока
    static int en_decks = 0;    // количество уничтоженных палуб противника
    int shot_x, shot_y;         // координаты выстрела
 
    if( pl_decks == max_decks ) return ENEMY;
    if( en_decks == max_decks ) return PLAYER;
 
    if( user == PLAYER ) {
        do {
            player_shot(&shot_x, &shot_y, player, enemy);
        } while( enemy[shot_y][shot_x] == 2 || enemy[shot_y][shot_x] == 3 );
        enemy[shot_y][shot_x] = ( enemy[shot_y][shot_x] == 1 )? 2 : 3;
        if( enemy[shot_y][shot_x] == 2 ) { ++en_decks; return 2; }
    }
    if( user == ENEMY ) {
        enemy_shot(&shot_x, &shot_y, player);
        player[shot_y][shot_x] = ( player[shot_y][shot_x] == 1 )? 2 : 3;
        if( player[shot_y][shot_x] == 2 ) { ++pl_decks; return 2; }
    }
 
    return 0;
}
// ------------------------------------------------------------
void enemy_shot (int *x, int *y, int field[][N]) {
    int shot_x, shot_y;
 
    do {
        shot_x = rand() %N;
        shot_y = rand() %N;
    } while( field[shot_y][shot_x] == 2 || field[shot_y][shot_x] == 3 );
 
    *x = shot_x;
    *y = shot_y;
}
// ------------------------------------------------------------
void player_shot (int *x, int *y, int player[][N], int enemy[][N]) {
    int shot_x = 4, shot_y = 4;         // положение прицела
    int old = enemy[shot_y][shot_x];    // запоминаем что было на карте
    enemy[shot_y][shot_x] = 4;          // ставим прицел
    draw_field(player, enemy);          // рисуем поле
 
    int next = 1;
    while( next > 0 ) {
        int key = getch();
        switch (key) {
            case ARROW_KEY_PRESSED:
                switch ( getch() ) {
                    case KEY_DOWN:
                        enemy[shot_y][shot_x] = old;
                        shot_y = (shot_y+1 == N)? N-1 : shot_y+1;
                        old = enemy[shot_y][shot_x];
                        enemy[shot_y][shot_x] = 4;
                        draw_field(player, enemy);
                        break;
                    case KEY_UP:
                        enemy[shot_y][shot_x] = old;
                        shot_y = (shot_y-1 < 0)? 0 : shot_y-1;
                        old = enemy[shot_y][shot_x];
                        enemy[shot_y][shot_x] = 4;
                        draw_field(player, enemy);
                        break;
                    case KEY_LEFT:
                        enemy[shot_y][shot_x] = old;
                        shot_x = (shot_x-1 < 0)? 0 : shot_x-1;
                        old = enemy[shot_y][shot_x];
                        enemy[shot_y][shot_x] = 4;
                        draw_field(player, enemy);
                        break;
                    case KEY_RIGHT:
                        enemy[shot_y][shot_x] = old;
                        shot_x = (shot_x+1 == N)? N-1 : shot_x+1;
                        old = enemy[shot_y][shot_x];
                        enemy[shot_y][shot_x] = 4;
                        draw_field(player, enemy);
                }
                break;
            case KEY_ENTER:
                enemy[shot_y][shot_x] = old;
                next = 0;
        }
    }
 
    *x = shot_x;
    *y = shot_y;
}
// ------------------------------------------------------------
Миниатюры
Консольный "Морской бой"  
1
2 / 2 / 0
Регистрация: 05.03.2020
Сообщений: 58
06.06.2020, 19:15  [ТС] 14
Вы просто лучший
0
06.06.2020, 19:15
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
06.06.2020, 19:15
Помогаю со студенческими работами здесь

Игра морской бой против компьютера
Игра морской бой против компьютера, с возможностью сохранения загрузки. звуковым сопровождением и...

Морской бой. Выбор структуры данных
при создании морского боя можно ли использовать структуру вместо класса и как вопще проще создавать...

Морской бой. Функция авторасстановки кораблей
Всем привет. Пишу морской бой. Затупил на функции авторасстановки кораблей. Ну во-первых какая-то...

Не могу найти ошибку(морской бой)
Пишу игру морской бой. так вот одна из функций, которые я взял из чужой програмы работает не...

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

Игра морской бой. Функция проверки - ранен корабль или убит
в общем задался целю написать игру морской бой. Так как я профи в программировании на С/C++, я...

Окно для игры "Морской бой"
Помогите пожалуйста! Я хочу написать игру на си в Code Blocks. Возникает проблема с оформлением....


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

Или воспользуйтесь поиском по форуму:
14
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru