r/C_Programming • u/kor_danggeut • Jul 09 '26
Code of the first game
This is the first code I wrote. What do you think?
#include "raylib.h"
int main(void) { InitWindow(800, 600, "Color Changing Ball Clicker"); SetTargetFPS(60);
int money = 0;
Color color = RED;
while (!WindowShouldClose())
{
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))
{
money = money + 1;
}
if (money < 100)
{
color = RED;
}
else if (money < 200)
{
color = BLUE;
}
else if (money < 300)
{
color = GREEN;
}
else if (money < 400)
{
color = GOLD;
}
else if (money < 500)
{
color = PURPLE;
}
else
{
color = MAROON;
}
BeginDrawing();
ClearBackground(RAYWHITE);
DrawCircle(400, 300, 80, color);
DrawText(TextFormat("money: %d", money), 20, 20, 30, BLACK);
DrawText("Click to change the ball color!", 20, 60, 20, DARKGRAY);
EndDrawing();
}
CloseWindow();
return 0;}
2
Upvotes
12
u/mikeblas Jul 09 '26
It's a start.
5
u/sinister_lazer Jul 09 '26
I'd extract the large if-else branch to its own function for easier maintainability:
Color get_color(int); // so you can use Color color = get_color(money)3
u/Fujinn981 Jul 09 '26
One thing I'd do is, move that big else if for the color to its own function, and secondly not have that ran on every loop. It should only be called when money is added, or decremented. Thirdly, create a tick system so the loop isn't being ran all of the time, otherwise this will be far more CPU intensive than it has any need to be.
2
u/mysticreddit Jul 09 '26
PSA: On desktop you'll want to indent with 4 spaces so the ENTIRE code is marked up properly.
2
u/Total-Box-5169 Jul 10 '26
There is another way to write an if/else if chain that makes easier to spot typos when you are doing those mappings:
2
u/sciencekm Jul 09 '26 edited Jul 09 '26
How about this:
static const Color colors[] = {RED,BLUE,GREEN,GOLD,PURPLE};color = money < 500 ? colors[money / 100] : MAROON;That can replace your giant if-else-if-else for determining color based on money.