Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
55 / 55 / 63
Регистрация: 18.03.2014
Сообщений: 386
1

игра "Змейка"

28.03.2014, 23:07. Показов 367. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
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
#include <iostream>  //стандартная библиотека
#include <time.h> //случайные числа
#include <stdio.h> //для printf
#include <windows.h> // для HANDLE, курсора, цвета
#include <conio.h>  //для kbhit
using namespace std;
HANDLE hConsole;
//HANDLE hStdout, hStdin;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
 
void GotoXY(int X, int Y)
{
    COORD coord = { X, Y };
    SetConsoleCursorPosition(hStdOut, coord);
} 
//Цвет
enum ConsoleColor
{
        Black         = 0,
        Blue          = 1,
        Green         = 2,
        Cyan          = 3,
        Red           = 4,
        Magenta       = 5,
        Brown         = 6,
        LightGray     = 7,
        DarkGray      = 8,
        LightBlue     = 9,
        LightGreen    = 10,
        LightCyan     = 11,
        LightRed      = 12,
        LightMagenta  = 13,
        Yellow        = 14,
        White         = 15
};
void SetColor(ConsoleColor text, ConsoleColor background)
{
    SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
}
class Zmeja  // структура змейка 
{
    public:COORD *t; //точки
    public:int PCount; //количество яблок
};
enum uprawlenie{LEFT,UP,RIGHT,DOWN}; //направление змейки
class Game //даные-точности: змейки, яблок, передвижение по X и Y, задержка, направление
{
    public:Zmeja gaduka; //змейка
    public:COORD jabloko; //яблоко
    public:int dx,dy; //передвижение
    public:int pause; //задержка
    public:int nap; //направление
};
void PlusJabloko(Game &g) //Функция разброски яблок
{
    int i,x,y;
    int n = g.gaduka.PCount;
    do
    {
        x = rand() % 56+3; //
        y = rand() % 19+3; //кординаты яблока
        for(i = 0; i < n; i++)
        {
            if(x == g.gaduka.t[i].X && y == g.gaduka.t[i].Y) // проверка чтоб яблоко не бросит на змею
                break;
        }
    }
    while(i < n);
    g.jabloko.X = x; //
    g.jabloko.Y = y; //запоминаем позицию яблока
    SetConsoleCursorPosition(hConsole, g.jabloko); //переносим курсор в эту позицию
    SetConsoleTextAttribute(hConsole,12); //цвет яблока  
    printf("%c", 4); //рисуем яблоко каким хотим символом
}
void skorostGame(Game &g) // Функцыя старта змейки ее координат и скорости
{
    system("cls");
    g.gaduka.PCount = 3; //сколько точек в змейке
    g.gaduka.t = new COORD [3];//создали точки
    for(int i = 0; i < 3; i++)
    {
        g.gaduka.t[i].X = 20 + i;
        g.gaduka.t[i].Y = 20;
        
    }
    g.dx = 1;
    g.dy = 0;
    g.pause = 100;//скорость передвижение змеи
    PlusJabloko(g);//рисуем яблока
}
void Level()
{
    setlocale(LC_ALL, "Russian");
    GotoXY(10,30);cout <<"Вам не победить)"<<endl;
}
void ZmejaStart()
{
    setlocale(LC_ALL, "Russian");
    GotoXY(10,35);cout <<"Собери 50 яблок"<<endl;
}
void STENA_2() //Вся информация, отображаемая на стене
{
    setlocale(LC_ALL, "Russian");
    SetColor(LightBlue , Black);GotoXY(20,0);cout << "Автор игры Разуткин Игорь Олегович" <<endl;
    GotoXY(64,2);cout <<  "Данные:" << endl ; //Данные
    GotoXY(64,3);cout <<  "Яблок:0" << endl ; //Яблок
    GotoXY(64,4); cout <<  "Длина:3"<< endl; //Длина
    GotoXY(64,5); cout <<  "Скорость:0" << endl; //Скорость
    GotoXY(64,7); cout << "Управление:" <<  endl; //Управление
    GotoXY(64,8); cout << "Esc:Выход" <<  endl; //Выход
    GotoXY(64,9); cout << "P:Пауза" <<  endl; //Пауза
    GotoXY(64,10); cout <<"S:Старт" <<  endl; //Старт
    GotoXY(64,11); cout <<"L:Уровень" <<  endl; //Уровень
    GotoXY(64,13);printf("%c",24);cout <<":Вверх"<<endl; //Вверх
    GotoXY(64,14);printf("%c",25);cout<<":Вниз"<<endl;   //Вниз
    GotoXY(64,15);printf("%c",27);cout<<":Влево"<<endl;  //Влево
    GotoXY(64,16);printf("%c",26);cout<<":Вправо"<<endl; //Вправо
                {SetColor(LightMagenta , Black);
                GotoXY(2,2); //Рисуем верхнюю горизонтальную линию-стенку
                int m = 0;
                for(m = 0; m < 60; m++)
                {
                    printf("*");
                }
                }
                
                {
                    GotoXY(2,24); //Рисуем нижнюю горизонтальную линию-стенку
                    int m = 0;
                    for(m = 0; m < 60;m++)
                    {
                        printf("*");
                    }
                }
                {   //Рисуем левую вертикальную линию-стенку
                    GotoXY(2,3); cout << "*"<<endl;
                    GotoXY(2,4); cout << "*"<<endl;
                    GotoXY(2,5); cout << "*"<<endl;
                    GotoXY(2,6); cout << "*"<<endl;
                    GotoXY(2,7); cout << "*"<<endl;
                    GotoXY(2,8); cout << "*"<<endl;
                    GotoXY(2,9); cout << "*"<<endl;
                    GotoXY(2,10); cout << "*"<<endl;
                    GotoXY(2,11); cout << "*"<<endl;
                    GotoXY(2,12); cout << "*"<<endl;
                    GotoXY(2,13); cout << "*"<<endl;
                    GotoXY(2,14); cout << "*"<<endl;
                    GotoXY(2,15); cout << "*"<<endl;
                    GotoXY(2,16); cout << "*"<<endl;
                    GotoXY(2,17); cout << "*"<<endl;
                    GotoXY(2,18); cout << "*"<<endl;
                    GotoXY(2,19); cout << "*"<<endl;
                    GotoXY(2,20); cout << "*"<<endl;
                    GotoXY(2,21); cout << "*"<<endl;
                    GotoXY(2,22); cout << "*"<<endl;
                    GotoXY(2,23); cout << "*"<<endl;
                }
                {   //Рисуем правую вертикальную линию-стенку
                    GotoXY(61,3); cout << "*"<<endl;
                    GotoXY(61,4); cout << "*"<<endl;
                    GotoXY(61,5); cout << "*"<<endl;
                    GotoXY(61,6); cout << "*"<<endl;
                    GotoXY(61,7); cout << "*"<<endl;
                    GotoXY(61,8); cout << "*"<<endl;
                    GotoXY(61,9); cout << "*"<<endl;
                    GotoXY(61,10); cout << "*"<<endl;
                    GotoXY(61,11); cout << "*"<<endl;
                    GotoXY(61,12); cout << "*"<<endl;
                    GotoXY(61,13); cout << "*"<<endl;
                    GotoXY(61,14); cout << "*"<<endl;
                    GotoXY(61,15); cout << "*"<<endl;
                    GotoXY(61,16); cout << "*"<<endl;
                    GotoXY(61,17); cout << "*"<<endl;
                    GotoXY(61,18); cout << "*"<<endl;
                    GotoXY(61,19); cout << "*"<<endl;
                    GotoXY(61,20); cout << "*"<<endl;
                    GotoXY(61,21); cout << "*"<<endl;
                    GotoXY(61,22); cout << "*"<<endl;
                    GotoXY(61,23); cout << "*"<<endl;
                }
}
//Функция которая двигает и рисует
enum {KONEC, STENA,  PLUS, MOVE};
int Move(Game &g)
{
    int & n = g.gaduka.PCount;
    COORD head = g.gaduka.t[n - 1]; //голова
    COORD tail = g.gaduka.t[0]; //хвост
    COORD next;
    next.X = head.X + g.dx;
    next.Y = head.Y + g.dy; //проверка следующей точки по направлению
    if(next.X < 3 || next.Y < 3 || next.X > 60 || next.Y > 23)//не уперлась ли в стену?
        return STENA;
    if(n > 4)
    {
        for(int i = 0; i < n; i++)
            if(next.X == g.gaduka.t[i].X && next.Y == g.gaduka.t[i].Y) //не наехали ли на себя?
                return KONEC;
    }
    if(next.X == g.jabloko.X && next.Y == g.jabloko.Y)
    {
        COORD*temp = new COORD[ ++n ]; //новый масив больший на 1
        for(int i = 0; i < n; i++)
            temp[i] = g.gaduka.t[i]; //перекопируем
        temp[n - 1] = next; //добавляем одну
        delete [] g.gaduka.t;
        g.gaduka.t = temp;
        SetConsoleCursorPosition(hConsole,head);
        SetConsoleTextAttribute(hConsole, 0x0a); //закрашываем яблоко которое сели 
        printf("*");
        SetConsoleCursorPosition(hConsole,next);
        SetConsoleTextAttribute(hConsole,0x0a);
        printf("%c",1);
        PlusJabloko(g);
        return PLUS;
    }
    for(int i = 0; i < n - 1; i++)
        g.gaduka.t[i] = g.gaduka.t[i + 1];
    g.gaduka.t[n - 1] = next;
    SetConsoleCursorPosition(hConsole,tail);//закрашиваем хвостик
    printf(" ");
    SetConsoleCursorPosition(hConsole,head);
    SetConsoleTextAttribute(hConsole, 0x0a);//красим хвост змеи в зелений цвет
    printf("*");
    SetConsoleCursorPosition(hConsole,next);
    SetConsoleTextAttribute(hConsole,14); //красим курсор в белый цвет (голову змеи) 
    printf("%c",1);
    return MOVE;
}
int intro()
{
    setlocale(LC_ALL, "Russian");
        GotoXY(18,10);
    printf("Это змейка");
    GotoXY(18,11);
    printf("Цель: собрать 50 яблок");
    GotoXY(18,15);
    printf("Нажмите на любую клавишу");
    getch();
}
int main()
{
    SetConsoleTitle("Hungry Snake 0.0.1");
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE); //получаем дескриптор консоли
    intro();
    int key = 0, count = 0;
    bool Pause=false;
    Game g;
    skorostGame(g);
    STENA_2();
    srand(time(0));
    bool pause = false;
    while(key != 27)
    {
        while(!kbhit()) //ждет пока нажмем
        {
            if(Pause==true)
            {
                Sleep(1); 
                continue;
            }
            switch (Move(g))//движение
            {
                setlocale(LC_ALL, "Russian");
            case PLUS:
                ++count;
                g.pause-=1;
                SetColor(LightBlue , Black);
                GotoXY(64,2);cout <<  "Данные:" << endl ;
                GotoXY(64,3); cout << "Яблок:" <<count << endl;
                GotoXY(64,4); cout << "Длина:" <<g.gaduka.PCount << endl;
                GotoXY(64,5); cout << "Скорость:" <<g.pause<< endl;
                GotoXY(64,7); cout << "Управление:" <<  endl;
                GotoXY(64,8); cout << "Esc:Выход" <<  endl;
                GotoXY(64,9); cout << "P:Пауза" <<  endl;
                GotoXY(64,10); cout <<"S:Старт" <<  endl;
                GotoXY(64,11); cout <<"L:Уровень" <<  endl;
                GotoXY(64,13);printf("%c",24);cout <<":Вверх"<<endl;
                GotoXY(64,14);printf("%c",25);cout<<":Вниз"<<endl;
                GotoXY(64,15);printf("%c",27);cout<<":Влево"<<endl;
                GotoXY(64,16);printf("%c",26);cout<<":Вправо"<<endl;
                if (count == 50) 
                {
                    setlocale(LC_ALL, "Russian");
                    SetColor(White , Black);
                    GotoXY(24,1); cout << "Вы выиграли" << endl; //Вы выиграли
                    getch();
                    return(0);
                }
                break;
            case STENA:
            case KONEC:
                setlocale(LC_ALL, "Russian");
                GotoXY(23,1); printf("Вы проиграли"); //Вы проиграли, ХА ХА ХА
                getch();
                return 0;
            }
            Sleep(g.pause); //Задержка
        }
    key = getch();
        if(key=='P'||key=='p')
            Pause=!Pause;
            else if(key=='S'||key=='s')
            ZmejaStart();
        else if(key=='L'||key=='l')
            Level();
        else if(key==0||key==224)
        {
            key=getch();
            if(key == 72 && g.nap != DOWN)
            {
                g.nap = UP;
                g.dx = 0;
                g.dy = -1;
            }
            else if(key == 80 && g.nap != UP)
            {
                g.nap = DOWN;
                g.dx = 0;
                g.dy = 1;
            }
            else if(key == 75 && g.nap != RIGHT)
            {
                g.nap = LEFT;
                g.dx = -1;
                g.dy = 0;
            }
            else if(key == 77 && g.nap != LEFT)
            {
                g.nap = RIGHT;
                g.dx = 1;
                g.dy = 0;
            }
        }
    }
}
нужно чтобы после нажатия клавиши 'p' открывалось доп. окно, в котором было бы две кнопки "Возобновить" и "Выйти".
Как это реализовать?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
28.03.2014, 23:07
Ответы с готовыми решениями:

Игра змейка
Уже много дней пытаюсь решить одну задачу , а точнее ради удовольствия создать игру ЗМЕЙКА. Но всё...

Игра змейка
Кто делал подобную игру отзовитесь, есть пару вопросов! заранее спасибо!

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

Игра змейка классы
Нужно добавить больше классов(class) класс еда, карта, очки #include &lt;iostream&gt; #include...

0
28.03.2014, 23:07
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
28.03.2014, 23:07
Помогаю со студенческими работами здесь

Игра Змейка (хвост змеи)
Немогу сообразить каким способом пришить змее хвост.Подкиньте пару идей. PS:грубо,страшно написано...

Игра змейка, не понимаю в чём проблема
Ошибок компиляторн не видит, но оно не работает.. Помогите, пожалуйста! #include &lt;iostream&gt;...

Игра змейка: исправить ошибки в коде
Помогите исправить код. #include &lt;time.h&gt; #include &lt;stdlib.h&gt; #include &lt;GL/glut.h&gt; int N =...

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

Игра Змейка. Нужны входные и выходные данные
Курсовой, нужны входные и выходные данные. в интернете не могу найти. Вот основа курсача:...

Баг в функции еды, игра змейка (Glut + C++)
Помогите, у меня баг в прогге, не могу сделать нормальную функцию еды для игры типо змейки и...


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

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