#include "raylib.h" #include #include #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(GetRandomValue(0, SCREEN_HEIGHT - OBSTACLE_SIZE)); o.x = static_cast(GetRandomValue(SCREEN_WIDTH, SCREEN_WIDTH * 2)); o.speed = static_cast(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(GetRandomValue(0, SCREEN_HEIGHT - OBSTACLE_SIZE)); o.x = static_cast(GetRandomValue(SCREEN_WIDTH, SCREEN_WIDTH * 2)); o.speed = static_cast(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; }