#include "raylib.h"
#include <math.h>
#include <stdcountof.h>
#include <stdlib.h>
constexpr int SCREEN_WIDTH = 400, SCREEN_HEIGHT = 400, BALL_COUNT = 100,
FPS = 60, // Frames per second
VEL_MAX = 5, // Maximum velocity in pixels per frame
RADIUS_MAX = 20, // Maximum ball radius
RADIUS_MIN = 5; // Minimum ball radius
constexpr char TITLE[] = "Balls and their admirers";
Color RAYLIB_COLORS[] = {
// These colors are defined in `raylib.h`
// Used to pick a random color.
LIGHTGRAY, GRAY, DARKGRAY, YELLOW, GOLD, ORANGE, PINK,
RED, MAROON, GREEN, LIME, DARKGREEN, SKYBLUE, BLUE,
DARKBLUE, PURPLE, VIOLET, DARKPURPLE, BEIGE, BROWN, DARKBROWN,
};
// Definition of Ball
// Ball stores state and other properties
// YOUR CODE HERE
Ball balls[BALL_COUNT];
// Initializes a ball with random values
Ball *init_ball_random(Ball *b) {
// Randomly initialize state and properties
// YOUR CODE HERE
// Find a leading ball. The ball must not lead itself.
Ball *leader; // Represents the leading ball that this ball will follow
// YOUR CODE HERE
return b;
}
// Initialize all balls in `balls`.
void init_balls_random() {
// YOUR CODE HERE
}
const Ball *draw_ball(const Ball *b) {
DrawCircle(b->pos.x, b->pos.y, b->radius, b->color);
return b;
}
// Updates the positions of balls according to their velocities
Ball *update_pos(Ball *b) {
b->pos.x += b->vel.x;
b->pos.y += b->vel.y;
b->pos.x =
fmodf(SCREEN_WIDTH + b->pos.x + b->vel.x,
SCREEN_WIDTH); // `SCREEN_WIDTH +` because C uses truncated division
b->pos.y = fmodf(SCREEN_HEIGHT + b->pos.y + b->vel.y, SCREEN_HEIGHT);
return b;
}
// Updates the velocity of a ball so that it follows the leading ball
Ball *update_vel_of_the_follower(Ball *b) {
// Position differences reflect in which direction the velocity vector of the
// follower should point to.
int diff_posx = b->leader->pos.x - b->pos.x,
diff_posy = b->leader->pos.y - b->pos.y;
// Adjust the velocity according to the difference.
b->vel.x = diff_posx > 0 ? 1 : -1;
b->vel.y = diff_posy > 0 ? 1 : -1;
return b;
}
// Update all elements
void draw_elements() {
for (size_t i = 0; i < countof balls; ++i) {
draw_ball(update_pos(update_vel_of_the_follower(&balls[i])));
}
}
int main() {
InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, TITLE);
SetTargetFPS(FPS);
init_balls_random();
while (!WindowShouldClose()) // Detect window close button or ESC key
{
BeginDrawing();
draw_elements();
ClearBackground(RAYWHITE);
EndDrawing();
}
CloseWindow();
}