Форум программистов, компьютерный форум, киберфорум
Visual C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/23: Рейтинг темы: голосов - 23, средняя оценка - 4.91
35 / 35 / 11
Регистрация: 25.05.2010
Сообщений: 211

морской бой

06.11.2011, 18:01. Показов 4838. Ответов 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
#include <iostream> // cin, cout
#include <clocale>  // поддержка русского языка
#include <conio.h>  // _getch()
#include <stdlib.h> // поддержка функции очистки экрана system("cls")
#include<time.h>
using namespace std;
 
enum direction{h=0,v=1};    
class player{
public:
    bool defeat_flag;
    int hits[10][10];
    int ships[10][10];
    player(): defeat_flag(false)
    {};
    void ships_init();
    void set(int deck);
    int place_ship(int s,int c,direction d,int deck);
    void turn(player& p,int s,int c);
    void turn(player& p);
 
};
int m[10]={1,3,2,1,4,2,3,1,1,2};
int const str=13;
int const col=29;
player human;
player computer;
char map[str][col]; // двумерный массив для хранения игровой карты
 
 
void map_init();
void show();
void input(char& , char&);
int check_end();
 
void player::ships_init(){
    for (int i=0;i<10;i++){
        for(int j=0;j<10;j++){
            ships[i][j]=1;
            hits[i][j]=0;
        }
    }
    for (int i=0;i<10;i++)
        set(m[i]);
}
 
int player::place_ship(int s,int c,direction d,int deck){
    switch(d){
        case 0:
            for (int i=-1;i<2;i++)
                for (int j=-1;j<deck+2;j++)
                    if(ships[i][j]==2)
                        return 1;
            break;
        case 1:
            for (int j=-1;j<2;j++)
                for (int i=-1;i<deck+2;i++)
                    if(ships[i][j]==2)
                        return 1;
    }
    return 0;
 
}
void player::set(int deck){
    int e,isset=0;
 while(!isset){
    int s=rand()%10;
    int c=rand()%10;
    direction d=rand()%2;
    switch(d){
        case 0:
            if((c+dec-1)<10){
            if(ships[s][c+dec-1]==1){
                e=place_ship(s,c,d,dec);
                if(e==0){
                    for (int i=0;i<dec;i++)
                        ships[s][c+i]=2;
                    isset=1;
                }
            }
            }break;
        case 1:
            if((s+dec-1)<10){
            if(ships[s+dec-1][c]==1){
                e=place_ship(s,c,d,dec);
                if(e==0){
                    for (int i=0;i<dec;i++)
                        ships[s+i][c]=2;
                isset=1;
                }
            }
        }
    }
    }
}
 
 
 
 
 
 
void player::turn(player& p,int s,int c){
    if(p.ships[s][c]==2){
        p.ships[s][c]=3;
        }
        hits[s][c]=1;
 
}
void player::turn(player& p){
    int e=0;
    while(!e){
        int s=rand()%10;
        int c=rand()%10;
        if( hits[s][c]==1)
            e=1;
    }
    if(p.ships[s][c]==2){
        p.ships[s][c]=3;
        }
    hits[s][c]=1;
}
 
int main()
{
    int e=0;
    char s,c;
    srand(time(NULL));
    setlocale(LC_CTYPE,"Russian"); // установка русского языка
    map_init();
    human.ships_init();
    computer.ships_init();
    while(!e){
        show();
        input(s,c);
        human.turn(computer,(int)s,(int)c);
        computer.turn(human);
        e=check_end();
    }
    _getch();
    return 0;
}
 
 
 
 
void show(){
    system("cls");
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
            map[i+2][j+2]=human.ships[i][j];
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
            map[i+17][j+17]=human.hits[i][j];
    for(int i=0;i<13;i++){
        for(int j=0;j<29;j++)
            cout<<map[i][j];
        cout<<endl;
    }
}
 
 
 
void input(char& s, char& c){
    while(1){
        s=_getch();
        if(s==27)
            exit(0);
        if (s>=0 && s<9)
            break;
    }
        while(1){
        c=_getch();
        if(s==27)
            exit(0);
        if (c>=0 && c<9)
            break;
    }
}
int check_end(){
    if(human.defeat_flag || computer.defeat_flag)
        return 1;
    return 0;
}
void map_init(){
    
    int m[4]={1,12,16,27};
    char l='A';
    char n='1';
 
    for(int i=0;i<13;i++){
        for (int j=0;j<29;j++)
            map[i][j]=' ';
}
 
for(int i=2,j=17;i<12,j<27;i++,n++,j++){
    if(i==11)
        n='0';
    map[0][i]=n;
    map[0][j]=n;
}
for(int i=2;i<12;i++,l++){
    map[i][0]=l;
    map[i][15]=l;
}
for(int j=0,k=0;j<2;j++){
k=m[j];
for(int i=1;i<29;i++){
    if((i==1)||(i==12)||(i==16)||(i==27))
        map[k][i]='#';
    else if((i>12)&&(i<16)||(i>27))
        map[k][i]=' ';
    else
        map[k][i]='-';
        }
        
}
for(int j=0,k=0;j<4;j++){
k=m[j];
    for(int i=2;i<12;i++){
        map[i][k]='|';
    }
}
 
}
пишет вот ето
1>------ Build started: Project: a, Configuration: Debug Win32 ------
1>Compiling...
1>Source2.cpp
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(69) : error C2440: 'initializing' : cannot convert from 'int' to 'direction'
1> Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(72) : error C2297: '+' : illegal, right operand has type 'std::ios_base &(__cdecl *)(std::ios_base &)'
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(73) : error C2297: '+' : illegal, right operand has type 'std::ios_base &(__cdecl *)(std::ios_base &)'
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(74) : error C2664: 'player:lace_ship' : cannot convert parameter 4 from 'std::ios_base &(__cdecl *)(std::ios_base &)' to 'int'
1> There is no context in which this conversion is possible
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(76) : error C2446: '<' : no conversion from 'std::ios_base &(__cdecl *)(std::ios_base &)' to 'int'
1> There is no context in which this conversion is possible
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(76) : error C2040: '<' : 'int' differs in levels of indirection from 'std::ios_base &(__cdecl *)(std::ios_base &)'
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(83) : error C2297: '+' : illegal, right operand has type 'std::ios_base &(__cdecl *)(std::ios_base &)'
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(84) : error C2297: '+' : illegal, right operand has type 'std::ios_base &(__cdecl *)(std::ios_base &)'
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(85) : error C2664: 'player:lace_ship' : cannot convert parameter 4 from 'std::ios_base &(__cdecl *)(std::ios_base &)' to 'int'
1> There is no context in which this conversion is possible
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(87) : error C2446: '<' : no conversion from 'std::ios_base &(__cdecl *)(std::ios_base &)' to 'int'
1> There is no context in which this conversion is possible
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(87) : error C2040: '<' : 'int' differs in levels of indirection from 'std::ios_base &(__cdecl *)(std::ios_base &)'
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(117) : error C2065: 's' : undeclared identifier
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(117) : error C2065: 'c' : undeclared identifier
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(118) : error C2065: 's' : undeclared identifier
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(118) : error C2065: 'c' : undeclared identifier
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(120) : error C2065: 's' : undeclared identifier
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(120) : error C2065: 'c' : undeclared identifier
1>c:\documents and settings\виталик\мои документы\visual studio 2008\projects\a\a\source2.cpp(127) : warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>Build log was saved at "file://c:\Documents and Settings\Виталик\Мои документы\Visual Studio 2008\Projects\a\a\Debug\BuildLog.htm"
1>a - 17 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
в чем ошибка??
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
06.11.2011, 18:01
Ответы с готовыми решениями:

Морской бой
Хочу написать игру морской бой средствами win api, но возник вопрос - каким образом определять в какую именно клетку поля произошло нажатие?

Программирование игры "морской бой" на с++
Помогите пожалуйст, кто может. Мне нужно написать курсовую.. Нужно спрограммировать игру &quot;морской бой&quot; на языке С++..:help:

Консольная игра "Морской бой"
Всем здравствуйте! Вот недавно решил разработать простую консольную игру &quot;Морской бой&quot;. Я думаю суть известна всем. Кое-что уже...

2
277 / 150 / 25
Регистрация: 05.11.2011
Сообщений: 429
Записей в блоге: 1
06.11.2011, 18:42
vetal10, В строчке 69 написана ерунда! Посмотрите на строчку 8.

Добавлено через 4 минуты
Со строчки 117 по 120 переменные s, с вышли из области видимости

Добавлено через 2 минуты
Может быть в методе void player::set вместо использования dec нужно deck
1
35 / 35 / 11
Регистрация: 25.05.2010
Сообщений: 211
06.11.2011, 18:52  [ТС]
а ты его не запускал??
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
06.11.2011, 18:52
Помогаю со студенческими работами здесь

Морской бой
Всем привет. Помогите пожалуйста. Задали написать игру «Морской бой». В Borlande 3.11 используя графический режим. Но признаюсь –...

C++ microsoft visual как сделать морской бои шаг за шагом?
C++ microsoft visual как сделать морской бои шаг за шагом?

Морской бой
Здравствуйте.Прошу помочь. Задался целью написать морской бой под консолью. Для начала решил рандомно заполнить поле игрока тремя...

Морской бой.
Хочу написать игру &quot;морской бой&quot;, Но прежде чем начинать хотелось бы глянуть на рабочие исходники других подобных прог. Все, что я нашел...

Морской бой
Здравствуйте господа. Мне нужно сделать игру морской бой. Игровое поле- 10x10 Корабли на игровом поле: Четыре одноклеточных, три...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Символьное дифференцирование
igorrr37 13.02.2026
/ * Программа принимает математическое выражение в виде строки и выдаёт его производную в виде строки и вычисляет значение производной при заданном х Логарифм записывается как: (x-2)log(x^2+2) -. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru