Форум программистов, компьютерный форум, киберфорум
Visual C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.97/34: Рейтинг темы: голосов - 34, средняя оценка - 4.97
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27

Таблица рекордов

03.06.2022, 11:05. Показов 7047. Ответов 20
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
помогите реализовать таблицу рекордов для игры
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
03.06.2022, 11:05
Ответы с готовыми решениями:

Таблица рекордов
Помогите сделать таблицу рекордов для игры. В таблице должно быть 2 поля: имя и рекорд. имя нужно передавать и 1 формы в 4,а рекорды из 2 и...

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

Онлайн таблица рекордов.
Здраствуйте. У меня есть игра тетрис. Игра написана на Си++. Мне нужно сделать онлайн таблицу рекордов, такую таблицу где имена игроков...

20
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
03.06.2022, 11:10  [ТС]
2048.txt вот созданная игра, для которой нужна таблица рекордов
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
03.06.2022, 21:25
Цитата Сообщение от vipdimanpro Посмотреть сообщение
Таблица рекордов
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
///----------------------------------------------------------------------------|
/// C++17
///----------------------------------------------------------------------------:
#include <map>
#include <tuple>
#include <iomanip>
#include <iostream>
#include <string_view>
 
///----------------------------------------------------------------------------|
/// Таблица рекордов.
///----------------------------------------------------------------------------:
struct Tabrecords
{
    Tabrecords& operator<<(std::tuple<std::string, int> _r)
    {          m.insert  ({std::get<1>(_r),
                           std::get<0>(_r)});
        return *this;
    }
 
    std::ostream& operator>>(std::ostream& o)
    {   int cnt = 1;
        for(const auto&[number, name] : m)
        {   o << "  " << cnt   << "."
              << std::setw(18) << name   << " - "
              << std::setw( 7) << number << '\n';
            ++cnt;
        }   o << '\n';
        return o;
    }
 
private:
    std::multimap<int, std::string, std::greater<int>> m;
}tabrecords;
 
using rec = std::tuple<std::string, int>;
 
///----------------------------------------------------------------------------|
/// Тест.
///----------------------------------------------------------------------------:
int main()
{
    setlocale(0, "");
 
    tabrecords << rec{"Вася Черный"    , 123 }
               << rec{"Джон"           , 555 }
               << rec{"Петя Шок"       , 4000}
               << rec{"Карабас Барабас", 777 };
 
    tabrecords >> std::cout;
}
out:
Code
1
2
3
4
  1.          Петя Шок -    4000
  2.   Карабас Барабас -     777
  3.              Джон -     555
  4.       Вася Черный -     123
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
03.06.2022, 22:43  [ТС]
такие ошибки выдает, не могу исправить. и можете объяснить , как оно именно реализовывается, а то я не до конца понимаю.
C++
1
for(const auto&[number, name] : m)
Миниатюры
Таблица рекордов  
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
03.06.2022, 23:13
vipdimanpro,
включите поддержку C++17
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
03.06.2022, 23:37  [ТС]
спасибо, заработало.. не могли бы ещё подсказать, как реализовать ввод имени и запись очков?
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
03.06.2022, 23:42  [ТС]
пытаюсь сделать таблицу рекордов для этой игры. нужно дописать ввод имени в начале каждой игры и чтобы эта таблица запоминалась даже после выхода с игры
Вложения
Тип файла: txt flappy bird.txt (14.5 Кб, 3 просмотров)
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
03.06.2022, 23:55  [ТС]
преподаватель вообще требует, чтобы в таблице писалось время, номер попытки и сумму очков, поэтому авторизацию не обязательно, но желательно вводить, так будет логичнее
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
04.06.2022, 00:18
Цитата Сообщение от vipdimanpro Посмотреть сообщение
нужно дописать ввод имени
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
///----------------------------------------------------------------------------|
/// C++17
///----------------------------------------------------------------------------:
#include <map>
#include <tuple>
#include <iomanip>
#include <iostream>
#include <string_view>
 
using rec = std::tuple<std::string, int>;
 
template<typename T>
T get()
{   T a = 0;
    while(true)
    {   try
        {   std::cout << "Пожалуйста, введите очки: ";
            std::string s;
            std::getline(std::cin, s);
            size_t            pos ;
            a = std::stoi(s, &pos);
            if(pos == s.size()) break;
            std::cout << "Упс, ты отличаешь цифры от буков?\n";
        }
        catch(...) {}
    }
    return a;
}
 
template<> std::string get<std::string>()
{   std::cout << "Пожалуйста, введите имя : ";
    std::string s;
    std::getline(std::cin, s);
    return s;
}
 
auto input()
{    return rec{get<std::string>(), get<int>()};
}
 
///----------------------------------------------------------------------------|
/// Таблица рекордов.
///----------------------------------------------------------------------------:
struct Tabrecords
{   Tabrecords& operator<<(std::tuple<std::string, int> _r)
    {   m.insert  ({std::get<1>(_r),
                    std::get<0>(_r)});
        return *this;
    }
 
    std::ostream& operator>>(std::ostream& o)
    {   int cnt = 1;
        for(const auto&[number, name] : m)
        {   o << "  " << cnt   << "."
              << std::setw(18) << name   << " - "
              << std::setw( 7) << number << '\n';
            ++cnt;
        }
        o << '\n';
        return o;
    }
 
private:
    std::multimap<int, std::string, std::greater<int>> m;
} tabrecords;
 
///----------------------------------------------------------------------------|
/// Тест.
///----------------------------------------------------------------------------:
int main()
{   setlocale(0, "");
 
    tabrecords << rec{"Вася Черный", 123 }
               << rec{"Джон", 555 }
               << rec{"Петя Шок", 4000}
               << rec{"Карабас Барабас", 777 };
 
    tabrecords >> std::cout;
 
    while(true)
    {   tabrecords << input();
        std::system("cls");
        tabrecords >> std::cout;
    }
}
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
04.06.2022, 00:35  [ТС]
за это спасибо, но это для ручного ввода, нужно реализовать, чтобы при попытке требовалось имя, потом автоматически записывались его очки, и так далее
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
04.06.2022, 00:54
Цитата Сообщение от vipdimanpro Посмотреть сообщение
и так далее
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
///----------------------------------------------------------------------------|
/// C++17
///----------------------------------------------------------------------------:
#include <map>
#include <tuple>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <string_view>
 
using rec = std::tuple<std::string, int>;
 
template<typename T>
T get()
{   T a = 0;
    while(true)
    {   try
        {   std::cout << "Пожалуйста, введите очки: ";
            std::string s;
            std::getline(std::cin, s);
            size_t            pos ;
            a = std::stoi(s, &pos);
            if(pos == s.size()) break;
            std::cout << "Упс, ты отличаешь цифры от буков?\n";
        }
        catch(...) {}
    }
    return a;
}
 
template<> std::string get<std::string>()
{   std::cout << "Пожалуйста, введите имя : ";
    std::string s;
    std::getline(std::cin, s);
    if(s == "exit") throw("exit");
    return s;
}
 
auto input()
{    return rec{get<std::string>(), get<int>()};
}
 
///----------------------------------------------------------------------------|
/// Таблица рекордов.
///----------------------------------------------------------------------------:
struct Tabrecords
{   Tabrecords& operator<<(std::tuple<std::string, int> _r)
    {   for(auto& c : std::get<0>(_r)) if(c == ' ') c = '_';
 
        m.insert  ({std::get<1>(_r),
                    std::get<0>(_r)});
        return *this;
    }
 
    std::ostream& operator>>(std::ostream& o)
    {   int cnt = 1;
        for(const auto&[number, name] : m)
        {   o << "  " << cnt   << ". "
              << std::setw(18) << name   << " - "
              << std::setw( 7) << number << '\n';
            ++cnt;
        }
        o << '\n';
        return o;
    }
 
private:
    std::multimap<int, std::string, std::greater<int>> m;
} tabrecords;
 
std::ifstream& operator>>(std::ifstream& o, Tabrecords& r)
{
    for(std::string s; o >> s;)
    {
        std::string a, b, c;
        o >> a;
        o >> b;
        o >> c;
 
        int n = std::stoi(c);
        r << rec{a, n };
    }
    return o;
}
 
///----------------------------------------------------------------------------|
/// Тест.
///----------------------------------------------------------------------------:
int main()
{   setlocale(0, "");
 
    std::ifstream f("rec.txt"); f >> tabrecords;
 
    if(!f.is_open())
    {   tabrecords << rec{"Вася Черный"    , 123 }
                   << rec{"Джон"           , 555 }
                   << rec{"Петя Шок"       , 4000}
                   << rec{"Карабас Барабас", 777 };
    }
 
    tabrecords >> std::cout;
 
    try
    {
        while(true)
        {   tabrecords << input();
            std::system("cls");
            tabrecords >> std::cout;
        }
    }
    catch(const char* s)
    {
        if(std::string(s) == "exit")
        {
            std::ofstream f("rec.txt");
            tabrecords >> f;
        }
    }
}
для выхода из режима ручного ввода нужно ввести exit
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
04.06.2022, 00:56  [ТС]
или я что-то не понимаю или мы говорим о разном) можете, пожалуйста, уже в коде реализовать вход в игру по имени пользователя и чтобы его очки автоматически (не вручную) записывались в таблицу рекордов
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
04.06.2022, 01:01
Цитата Сообщение от vipdimanpro Посмотреть сообщение
уже в коде реализовать вход в игру по имени пользователя
откуда мне знать чо у тя за игра.
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
04.06.2022, 01:05  [ТС]
выше кидал код, щас ещё раз кину
Вложения
Тип файла: txt flappy bird.txt (14.5 Кб, 0 просмотров)
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
04.06.2022, 01:08
Цитата Сообщение от vipdimanpro Посмотреть сообщение
flappy bird.txt
предлагаешь мне шоп я сделал реинженеринг - определил твою игру по коду?
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
04.06.2022, 01:09  [ТС]
это консольная игра flappy bird
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
04.06.2022, 01:15
Цитата Сообщение от vipdimanpro Посмотреть сообщение
уже в коде реализовать вход в игру по имени пользователя и чтобы его очки автоматически
0.
в начале игры в переменную вводишь имя name.
далее по ходу игры считаешь очки number,

1.
в конце игры делаешь
tabrecords << rec{name, number};

2.
и когда нужно отображаешь таблицу на экран:
tabrecords >> std::cout;

Всё.

Добавлено через 2 минуты
зы:

3.
скинуть на диск:
{ std::ofstream f("rec.txt"); tabrecords >> f;
}

4.
загрузить с диска:
{ std::ifstream f("rec.txt"); f >> tabrecords;
}

Вот и весь интерфейс таблицы рекордов.
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
04.06.2022, 01:38  [ТС]
Цитата Сообщение от XLAT Посмотреть сообщение
0.
в начале игры в переменную вводишь имя name.
далее по ходу игры считаешь очки number,

1.
в конце игры делаешь
tabrecords << rec{name, number};

2.
и когда нужно отображаешь таблицу на экран:
tabrecords >> std::cout;

Всё.

Добавлено через 2 минуты
зы:

3.
скинуть на диск:
{ std::ofstream f("rec.txt"); tabrecords >> f;
}

4.
загрузить с диска:
{ std::ifstream f("rec.txt"); f >> tabrecords;
}

Вот и весь интерфейс таблицы рекордов.
спасибо, вдруг будет желание, помоги с кодом)

Добавлено через 16 минут
Цитата Сообщение от XLAT Посмотреть сообщение
0.
в начале игры в переменную вводишь имя name.
далее по ходу игры считаешь очки number,

1.
в конце игры делаешь
tabrecords << rec{name, number};

2.
и когда нужно отображаешь таблицу на экран:
tabrecords >> std::cout;

Всё.

Добавлено через 2 минуты
зы:

3.
скинуть на диск:
{ std::ofstream f("rec.txt"); tabrecords >> f;
}

4.
загрузить с диска:
{ std::ifstream f("rec.txt"); f >> tabrecords;
}

Вот и весь интерфейс таблицы рекордов.
или хотя бы с одним помоги, не могу сделать так, чтобы в таблице вводились очки игрока, почему-то 0 выводит, хотя приравнивал number к score
0
0 / 0 / 0
Регистрация: 17.05.2022
Сообщений: 27
04.06.2022, 20:28  [ТС]
Цитата Сообщение от XLAT Посмотреть сообщение
0.
в начале игры в переменную вводишь имя name.
далее по ходу игры считаешь очки number,

1.
в конце игры делаешь
tabrecords << rec{name, number};

2.
и когда нужно отображаешь таблицу на экран:
tabrecords >> std::cout;

Всё.

Добавлено через 2 минуты
зы:

3.
скинуть на диск:
{ std::ofstream f("rec.txt"); tabrecords >> f;
}

4.
загрузить с диска:
{ std::ifstream f("rec.txt"); f >> tabrecords;
}

Вот и весь интерфейс таблицы рекордов.
посмотри, пожалуйста, код, имя вводится, счёт записывается, после выхода запоминается, но почему после того, как ещё раз заходишь, сбрасывается весь файл и не пишется в таблице предыдущие результаты?
Вложения
Тип файла: txt FLAPPY BIRD source.txt (14.2 Кб, 8 просмотров)
0
Just Do It!
 Аватар для XLAT
4211 / 2668 / 655
Регистрация: 23.09.2014
Сообщений: 9,077
Записей в блоге: 3
04.06.2022, 21:48
vipdimanpro,
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <map>
#include <tuple>
#include <string_view>
 
using namespace std;
 
char c[30][21]; //variable for storing screen particles (pixels)
int n[30][21];  //variable for checking
int highscore;
string name;
int number;
int contr, tuk = 0, t = 0, bt = 0, birdx = 0, birdy = 0; //variaous variables for certain operations
bool err; //boolean for error detection
 
void game();  //various functions
void screen();
void pipes();
void bird();
bool gameover();
void checkscore();
void help();
void menu();
void endgame();
void credits();
 
///////////////////////////////////////////////////////////////////////---BEGIN:
///--------------------------------|
/// Подключение русского модуля.   |
///--------------------------------:
///----------------------------------------------------------------------------|
/// C++17
///----------------------------------------------------------------------------:
#include <map>
#include <tuple>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <string_view>
 
using rec = std::tuple<std::string, int>;
 
template<typename T>
T get()
{   T a = 0;
    while(true)
    {   try
        {   std::cout << "Пожалуйста, введите очки: ";
            std::string s;
            std::getline(std::cin, s);
            size_t            pos ;
            a = std::stoi(s, &pos);
            if(pos == s.size()) break;
            std::cout << "Упс, ты отличаешь цифры от буков?\n";
        }
        catch(...) {}
    }
    return a;
}
 
template<> std::string get<std::string>()
{   std::cout << "Пожалуйста, введите имя : ";
    std::string s;
    std::getline(std::cin, s);
    if(s == "exit") throw("exit");
    return s;
}
 
auto input()
{    return rec{get<std::string>(), get<int>()};
}
 
///----------------------------------------------------------------------------|
/// Таблица рекордов.
///----------------------------------------------------------------------------:
struct Tabrecords
{   Tabrecords& operator<<(std::tuple<std::string, int> _r)
    {   for(auto& c : std::get<0>(_r)) if(c == ' ') c = '_';
 
        m.insert  ({std::get<1>(_r),
                    std::get<0>(_r)});
        return *this;
    }
 
    void show()
    {   std::system("cls");
        *this >> std::cout;
 
        std::cout << "\n\nПРОДОЛЖИТЬ ЖМАКАЙ ENTER ...\n";
 
        std::string s; std::getline(std::cin, s);
    }
 
    std::ostream& operator>>(std::ostream& o)
    {   int cnt = 1;
        for(const auto&[number, name] : m)
        {   o << "  " << cnt   << ". "
              << std::setw(18) << name   << " - "
              << std::setw( 7) << number << '\n';
            ++cnt;
        }
        o << '\n';
        return o;
    }
 
private:
    std::multimap<int, std::string, std::greater<int>> m;
} tabrecords;
 
std::ifstream& operator>>(std::ifstream& o, Tabrecords& r)
{
    for(std::string s; o >> s;)
    {
        std::string a, b, c;
        o >> a;
        o >> b;
        o >> c;
 
        try
        {   int n = std::stoi(c);
            r << rec{a, n };
        }
        catch(...){}
    }
    return o;
}
 
///----------------------------------------------------------------------------|
/// Тест.
///----------------------------------------------------------------------------:
void test()
{   setlocale(0, "");
 
    std::ifstream f("rec.txt"); f >> tabrecords;
 
    if(!f.is_open())
    {   tabrecords << rec{"Вася Черный"    , 123 }
                   << rec{"Джон"           , 555 }
                   << rec{"Петя Шок"       , 4000}
                   << rec{"Карабас Барабас", 777 };
    }
 
    tabrecords >> std::cout;
 
    try
    {
        while(true)
        {   tabrecords << input();
            std::system("cls");
            tabrecords >> std::cout;
        }
    }
    catch(const char* s)
    {
        if(std::string(s) == "exit")
        {
            std::ofstream f("rec.txt");
            tabrecords >> f;
        }
    }
}
 
///---------------------|
/// Личная инфа игрока. |
///---------------------:
struct Player
{   std::string name    ;
    int         score{0};
}player;
/////////////////////////////////////////////////////////////////////////---END.
 
 
int main()
{   SetConsoleCP(1251);
    SetConsoleOutputCP(1251); //підключення української мови
    srand(time(0));  //seeding random number gen, we will need it later;
 
    ///---------------------------------------------|
    /// 1.                                          |
    ///---------------------------------------------:
    {
        ///-----------------------------------------|
        /// Загрузка с диска.                       |
        ///-----------------------------------------:
        std::ifstream f("rec.txt"); f >> tabrecords;
 
        ///-----------------------------------------|
        /// Щоп не было одиноко.                    |
        ///-----------------------------------------:
        if(!f.is_open())
        {   tabrecords << rec{"Вася Черный"    , 123 }
                       << rec{"Джон"           , 555 }
                       << rec{"Петя Шок"       , 4000}
                       << rec{"Карабас Барабас", 777 };
        }
 
        tabrecords.show();
 
        std::cout << "Введите ваше имя: "; std::getline(std::cin, player.name);
    }
 
    err = false;  //error will be false, because file opened successfully
 
    int a = 0;
    char sl; //selection variable
    while (1) //loop for repeating actions after each start
    {   if (a == 0) goto play;
        if (a > 0)               //if you play not the first time, it will ask you if you want to play
        {   player.score = 0;
            cout << "Do you want to play again? [y/n] ";
            cin >> sl;
            if (sl == 'n') goto quit;
            else goto play;
        }
play:
        menu(); //calling menu function
        cin >> sl;
        switch (sl) //menu selections
        {   case '1':
            {   game(); //if you choose play, it calls function game
                break;
            }
            case '2': //other selections-other functions
            {   help();
                goto play;
                break;
            }
            case '3':
            {   credits();
                goto play;
                break;
            }
            case '4':
            {   goto quit; //exits game
                break;
            }
            default:
            {   goto play;
                break;
            }
        }
        a++; //variable for checking how many times you've played
    }
quit:
    {   cout << "I quit."; //stops game, app closes.
        ///----------------------------------|
        /// Записываем результат.            |
        ///----------------------------------:
        {
            tabrecords << rec{player.name, highscore };
            std::ofstream f("rec.txt"); tabrecords >> f;
            tabrecords.show();
        }
    }
 
    return 0;
}
 
void game()  //function for playing game
{   int x, y;
    char s;
    for (y = 0; y < 21; y++)  //setting screen
    {   for (x = 0; x < 30; x++)
        {   if (y < 20)
            {   c[x][y] = ' ';
                n[x][y] = 0;
            }
            if (y == 20)
            {   c[x][y] = '-';
                n[x][y] = 2;
            }
        }
    }
    c[10][10] = '*';  //in these coordinates will be our bird, marked *
    screen();      //calls func for showin screen
    while (1)       //loop starts, actual gameplay begins
    {   s = '~';  //default control variable
        Sleep(0.2 * 1000);  //this sets how fast everyhing moves
        t++;              //this is a variable for storing 'time',or how many times a loop passed
        if (_kbhit()) //if key is pressed, certain operations are done for bird to move up.
        {   s = _getch();        //gets what key is pressed
            if (s != '~') tuk = 1; //if it is not default, then 'tuk' will be equal to 1, meaning that bird will fly up
        }
        for (x = 0; x < 30; x++) //just setting ground
        {   c[x][20] = '-';
            n[x][20] = 2;
        }
        bird();                       //cals bird move function
        checkscore();                 //checks score
 
        if (gameover() == true) goto gameEnd;   //checks if bird hits pipes, if yes, game ends
        pipes();                             //spawns and moves pipes
        if (player.score > highscore) highscore = player.score;  //i think this is clear
        screen();                            //finally, calls screen function to show enerything.
 
        if (tuk > 0) tuk++;           //if key is pressed, bird will fly up 2 times.
        if (tuk == 3) tuk = 0;          //after that, bird falls
    }
gameEnd:   //ends game
    {
 
        if (player.score > highscore) highscore = player.score;
        screen();    //shows ending screen, and returns to int main
        endgame();
        return;
    }
}
 
void screen()    //func for showing screen
{   int x, y;
    system("cls");    //clears console
    for (y = 0; y < 21; y++) //shows pixels on their coordinates, and your score
    {   for (x = 0; x < 30; x++)
        {   if (x < 29) cout << c[x][y];
            if (x == 29) cout << c[x][y] << endl;
        }
    }
    cout << "" << endl;
    cout << "Your Score: " << player.score;
}
 
void pipes()  //pipe movement and spawn func
{   int x, y, r;
    if (t == 10)   //if time is 10, or loop has passed 10 times, it spawns a new pipe
    {   r = (rand() % 11) + 5;  //generates random number, which will be the pipe's hole center
        for (y = 0; y < 20; y++)  // only y coordinate is needed
        {   c[29][y] = '|';  //sets pipe
            n[29][y] = 2;    //n will be 2, for checking if bird has hit it,
        }
        c[29][r - 1] = ' ';  //sets hole
        c[29][r] = ' ';
        c[29][r + 1] = ' ';
        n[29][r - 1] = 0;
        n[29][r] = 0;
        n[29][r + 1] = 0;
        t = 0;
        goto mv; //moves pipes
    }
    else goto mv;
mv:                 //pipe movement
    {   for (y = 0; y < 20; y++)  //loops for generating coordinates
        {   for (x = 0; x < 30; x++)
            {   if (c[x][y] == '|')  //all the pipes will be moved left by 1;
                {   if (x > 0)
                    {   c[x - 1][y] = '|';
                        n[x - 1][y] = 2;
                        c[x][y] = ' ';
                        n[x][y] = 0;
                    }
                    if (x == 0)  //if screen ends (x=0) pipe will dissapear, to prevent errors
                    {   c[x][y] = ' ';
                        n[x][y] = 0;
                    }
                }
            }
        }
    }
}
 
void bird()   //bird movement function!
{   int x, y;
    if (tuk > 0) //if key is pressed, bird moves up
    {   bt = 0;
        for (y = 0; y < 20; y++)   //loops for finding bird coordinates
        {   for (x = 0; x < 30; x++)
            {   if (c[x][y] == '*')
                {   if (y > 0)
                    {   c[x][y - 1] = '*';  //bird moves up by 1;
                        c[x][y] = ' ';
                        birdx = x;        //sets bird x coordinate
                        birdy = y - 1;      //sets bird y coord
                        return;         //retuns to game func
                    }
                }
            }
        }
    }
    else   //if no key is pressed, bird falls
    {   bt++;
        for (y = 0; y < 20; y++)
        {   for (x = 0; x < 30; x++)
            {   if (c[x][y] == '*')
                {   if (y < 20)  //if bird is not on the ground
                    {   if (bt < 3)   //if bird time is lower that 3, it falls 1 pixel
                        {   c[x][y + 1] = '*';
                            c[x][y] = ' ';
                            birdx = x;
                            birdy = y + 1;
                            return;
                        }
                        else if (bt > 2 && bt < 5)  //more time has passed, faster bird falls (acceleration)
                        {   c[x][y + 2] = '*';
                            c[x][y] = ' ';
                            birdx = x;
                            birdy = y + 2;
                            return;
                        }
                        else if (bt > 4)
                        {   c[x][y + 3] = '*';
                            c[x][y] = ' ';
                            birdx = x;
                            birdy = y + 3;
                            return;
                        }
                    }
                    else
                    {   return;  //if bird is already on the ground, function returns to check for game over.
                    }
                }
            }
        }
    }
}
 
void checkscore()  //checks if bird gained score
{   int y;
    for (y = 0; y < 20; y++)
    {   if (c[birdx][y] == '|')  //if bird x coord is equal to pipe's coord, you get 1 point
        {   player.score++;
            return;
        }
    }
}
 
bool gameover()  //checks if bird has hit something
{   int f = 0;
    if (birdy > 19) //checks if bird hits ground
    {   c[birdx][19] = '*';  //sets bird and ground again, prevents errors
        c[birdx][20] = '-';
        f = 1;           //f=1, means function will return true
        goto quit;
    }
    else
    {   //checks if bird has hit pipes, here the 'n' variable is needed (pipe's coordinate's n is equal 2 (more than 0))
        if (n[birdx][birdy] > 0 && (c[birdx][birdy] == '|' || c[birdx][birdy] == '*'))
        {   c[birdx][birdy] = '|';
            c[birdx - 1][19] = '*';
            f = 1;
            goto quit;
        }
    }
quit:
    if (f == 1) return true;
    else return false;
}
 
void endgame() //just some screens for certain actions
{   screen();   //this one pops up if game ends
    cout << "" << endl << endl;
    cout << " ------------------------------------------------------------------------- " << endl;
    cout << "|    *****      *     *       * ******       ****  *       ****** ****    |" << endl;
    cout << "|   *          * *    * *   * * *           *    *  *     * *     *   *   |" << endl;
    cout << "|   *  ****   *   *   *  * *  * *****       *    *   *   *  ****  ****    |" << endl;
    cout << "|   *  *  *  *******  *   *   * *           *    *    * *   *     * *     |" << endl;
    cout << "|    *****  *       * *       * ******       ****      *    ***** *   *   |" << endl;
    cout << " ------------------------------------------------------------------------- " << endl;
    cout << "" << endl << endl;
    cout << "                        Y O U R   S C O R E : " << player.score << endl << endl;
    cout << "                        H I G H   S C O R E : " << highscore << endl;
    cout << "" << endl << endl;
}
 
void menu()  //shows menu
{   system("cls");
    cout << "" << endl;
    cout << " --------------------------------------------------------  " << endl;
    cout << "|                                                        | " << endl;
    cout << "|   **** *    **** **** **** *   *    ***  * ***  ***    | " << endl;
    cout << "|   *    *    *  * *  * *  * *   *    *  * * *  * *  *   | " << endl;
    cout << "|   ***  *    **** **** **** *****    ***  * ***  *  *   | " << endl;
    cout << "|   *    *    *  * *    *      *      *  * * *  * *  *   | " << endl;
    cout << "|   *    **** *  * *    *      *      ***  * *  * ***    | " << endl;
    cout << "|                                                  v 1.0 | " << endl;
    cout << " --------------------------------------------------------  " << endl;
    cout << "" << endl << endl;
    cout << "                  High Score:  " << highscore << endl << endl;
    cout << "" << endl << endl;
    cout << "                     М Е Н Ю:    " << endl << endl;
    cout << "                  1: Почати гру  " << endl << endl;
    cout << "                  2: Інструкція        " << endl << endl;
    cout << "                  3: Таблиця рекордів     " << endl << endl;
    cout << "                  4: Вихід        " << endl << endl;
}
 
void credits()
{   std::system("cls");
    tabrecords >> std::cout;
 
    std::string s; std::getline(std::cin, s);
    std::cin.get();
}
 
void help()
{   char sel;
    system("cls");
    while (true)
    {   cout << "" << endl << endl;
        cout << "                   Controls: Press any key to fly up.         " << endl << endl;
        cout << "             Goal: Fly through the holes between the pipes.   " << endl;
        cout << "             When you pass through the hole,you get 1 point.  " << endl;
        cout << "                    Try to pass as much as you can.           " << endl;
        cout << "            But be careful, don't hit the pipes or the ground!" << endl << endl;
        cout << "                          Are you ready? Go!                  " << endl << endl << endl;
        cout << "Go back? [y/n]  ";
        cin >> sel;
        if (sel == 'y') return;
        else system("cls");
    }
}
в саму игру вашу я не лез ...
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
04.06.2022, 21:48
Помогаю со студенческими работами здесь

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

Таблица рекордов для 2d игры
Всем привет, как можно сделать таблицу рекордов для 2d игры WinAPI c++? Может есть какие-то функции? Подскажите пожалуйста?

Builder C++ 6 таблица рекордов в сапере
Привет всем, такое дело, нужно сделать таблицу рекордов в сапере. Рекорды по времени, может есть у кого какие идеи или пример какой? ...

Таблица рекордов для игры
Доброго времени суток! Подскажите, пожалуйста, как сделать таблицу рекордов. Есть игра. Сначала вводиться имя игрока, потом игра, а...

Игра Тетрис. Таблица рекордов
Может кто может помочь добавить таблицу рекордов в игру?? #include &lt;vcl.h&gt; #pragma hdrstop #include &quot;Unit1.h&quot; ...


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

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь 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. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru