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
|
#include "raylib.h"
#include <print>
#include <string>
#define SCREEN_WIDTH (800)
#define SCREEN_HEIGHT (450)
#define WINDOW_TITLE "Hello World"
#define GRAVITY 1
#define PLAYER_SIZE 40
#define JUMP_STRENGTH 10
#define NUM_OF_OBSTACLES 8
#define OBSTACLE_SIZE 40
struct Player
{
float y = 0;
float velocity = 0;
Rectangle rec;
};
struct Obstacle
{
float y;
float x;
float speed;
Rectangle rec;
};
int
main(void)
{
InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_TITLE);
SetTargetFPS(60);
Player player;
Obstacle obstacles[NUM_OF_OBSTACLES];
for (auto &o: obstacles)
{
o.y = static_cast<float>(GetRandomValue(0, SCREEN_HEIGHT - OBSTACLE_SIZE));
o.x = static_cast<float>(GetRandomValue(SCREEN_WIDTH, SCREEN_WIDTH * 2));
o.speed = static_cast<float>(GetRandomValue(2, 5));
o.rec = {o.x, o.y, OBSTACLE_SIZE, OBSTACLE_SIZE};
}
int score = 0;
int highscore = 0;
while (!WindowShouldClose())
{
score += 1;
if (score >= highscore)
highscore = score;
if (player.y <= 0)
{
player.velocity = 0;
}
if (IsKeyDown(KEY_SPACE) && player.y > 0)
{
player.velocity = -JUMP_STRENGTH;
}
else if (player.velocity >= 0 && player.y >= SCREEN_HEIGHT - PLAYER_SIZE - player.velocity)
{
player.velocity = 0;
}
else
{
player.velocity += GRAVITY;
}
player.y += player.velocity;
player.rec = {50, player.y, PLAYER_SIZE, PLAYER_SIZE};
for (auto &o : obstacles)
{
o.x -= o.speed;
if (o.x < -OBSTACLE_SIZE)
{
o.y = static_cast<float>(GetRandomValue(0, SCREEN_HEIGHT - OBSTACLE_SIZE));
o.x = static_cast<float>(GetRandomValue(SCREEN_WIDTH, SCREEN_WIDTH * 2));
o.speed = static_cast<float>(GetRandomValue(1, 5));
}
o.rec = {o.x, o.y, OBSTACLE_SIZE, OBSTACLE_SIZE};
if (CheckCollisionRecs(o.rec, player.rec))
score = 0;
}
BeginDrawing();
ClearBackground(BLUE);
auto score_text = std::format("Score: {}\nBest: {}", score, highscore);
DrawText(score_text.c_str(), 10, 10, 20, WHITE);
DrawRectangleRec(player.rec, BLACK);
for (auto o : obstacles)
{
DrawRectangleRec(o.rec, RED);
}
EndDrawing();
}
CloseWindow();
return 0;
}
|