-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
658 lines (559 loc) · 19.7 KB
/
main.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
#include <allegro.h>
#include <stdbool.h>
#include <math.h>
#include <stdio.h>
// macros
#define BORDER_POINTS 8
#define BOUNCER_AMOUNT 5
#define TRAIL_LENGTH 10
#define TRAIL_CHECK_MS 0
// scaling
float scale;
float simWidth;
float simHeight;
float sX(float x) {
return x * scale;
}
float sY(float y) {
return SCREEN_H - (y * scale);
}
typedef struct {
float x;
float y;
} Vector;
typedef struct {
Vector a;
Vector b;
} LineSegment;
// in-game objects
typedef struct {
Vector position;
Vector velocity;
float radius;
int color;
float restitution;
} Ball;
typedef struct {
Vector position;
float radius;
float pushStrength;
int color;
int score;
int hitTimer;
} Bouncer;
typedef struct {
float radius;
Vector position;
float length;
float restAngle;
float maxRotation;
float sign;
float angularVelocity;
// changing
float rotation;
float currentAngularVelocity;
int touchIdentifier;
} Flipper;
typedef struct {
double r; // a fraction between 0 and 1
double g; // a fraction between 0 and 1
double b; // a fraction between 0 and 1
} rgb;
typedef struct {
double h; // angle in degrees
double s; // a fraction between 0 and 1
double v; // a fraction between 0 and 1
} hsv;
// physics scene
bool paused = false;
float gravity = -3.0f;
float flipperHeight = 1.7f;
float deathZone = -0.5;
float streakEndZone = 0.3;
// score
int score = 0;
int lives = 3;
int streak = 0;
Ball ball;
Bouncer bouncers[BOUNCER_AMOUNT];
Flipper flippers[2];
float margin = 0.02;
Vector border[BORDER_POINTS];
Vector trail[TRAIL_LENGTH];
int trailIndex = 0;
unsigned long lastTrailUpdate = 0;
int latestColor;
// general util functions
float clamp(float n, float start, float end) {
return MAX(start, MIN(end, n));
}
// vector & point functions
Vector subtractVectors(Vector a, Vector b) {
a.x -= b.x;
a.y -= b.y;
return a;
}
Vector addVectors(Vector a, Vector b) {
a.x += b.x;
a.y += b.y;
return a;
}
Vector scaleVector(Vector v, float scale) {
v.x *= scale;
v.y *= scale;
return v;
}
float vectorLength(Vector v) {
return sqrt((double)(v.x*v.x + v.y*v.y));
}
// alternatively, there's an existing built in function for 3d
Vector normalizeVector(Vector v) {
return scaleVector(v, 1 / vectorLength(v));
}
Vector perpendicularVector(Vector v) {
return (Vector){-v.y, v.x};
}
// get line segment from position, length, and angle
LineSegment getLineSegment(Vector position, float length, float angle) {
Vector directionVector = {cos(angle), sin(angle)};
Vector endpoint = addVectors(position, scaleVector(directionVector, length));
return (LineSegment){.a = position, .b = endpoint};
}
// builtin allegro function is for 3d
float dotProduct(Vector a, Vector b) {
return (a.x * b.x) + (a.y * b.y);
}
Vector closestPointOnLineSegment(Vector point, LineSegment line) {
Vector segmentVector = subtractVectors(line.b, line.a);
float segmentLengthSquared = dotProduct(segmentVector, segmentVector);
// if it's just a point, return the point
if (segmentLengthSquared == 0) {
return line.a;
}
float distAlongLine = clamp((dotProduct(point, segmentVector) - dotProduct(line.a, segmentVector)) / segmentLengthSquared, 0, 1);
return addVectors(line.a, scaleVector(segmentVector, distAlongLine));
}
Vector getFlipperTip(Flipper* flipper) {
float angle = flipper->restAngle + flipper->sign * flipper->rotation;
Vector dir = {cos(angle), sin(angle)};
return addVectors(flipper->position, scaleVector(dir, flipper->length));
}
// https://stackoverflow.com/a/6930407
rgb hsv2rgb(hsv in)
{
double hh, p, q, t, ff;
long i;
rgb out;
if(in.s <= 0.0) { // < is bogus, just shuts up warnings
out.r = in.v;
out.g = in.v;
out.b = in.v;
return out;
}
hh = in.h;
if(hh >= 360.0) hh = 0.0;
hh /= 60.0;
i = (long)hh;
ff = hh - i;
p = in.v * (1.0 - in.s);
q = in.v * (1.0 - (in.s * ff));
t = in.v * (1.0 - (in.s * (1.0 - ff)));
switch(i) {
case 0:
out.r = in.v;
out.g = t;
out.b = p;
break;
case 1:
out.r = q;
out.g = in.v;
out.b = p;
break;
case 2:
out.r = p;
out.g = in.v;
out.b = t;
break;
case 3:
out.r = p;
out.g = q;
out.b = in.v;
break;
case 4:
out.r = t;
out.g = p;
out.b = in.v;
break;
case 5:
default:
out.r = in.v;
out.g = p;
out.b = q;
break;
}
return out;
}
// feature-specific functions
void updateBall(Ball* b, float dt) {
b->velocity.y += gravity * dt;
b->position.x += b->velocity.x * dt;
b->position.y += b->velocity.y * dt;
if (b->position.y < deathZone) {
printf("test!!!!");
b->position = (Vector){0.8, 0.7};
b->velocity = (Vector){0, 0};
lives--;
}
if (b->position.y < streakEndZone) {
streak = 0;
}
}
void updateFlipper(Flipper* flipper, float dt, bool pressed) {
float prevRotation = flipper->rotation;
if (pressed) {
flipper->rotation = MIN(flipper->rotation + dt * flipper->angularVelocity, flipper->maxRotation);
} else {
flipper->rotation = MAX(flipper->rotation - dt * flipper->angularVelocity, 0.0);
}
flipper->currentAngularVelocity = flipper->sign * (flipper->rotation - prevRotation) / dt;
}
// collision handlers
void handleBouncerCollision(Ball* ball, Bouncer* bouncer) {
Vector directionVector = subtractVectors(ball->position, bouncer->position); // vector pointing from the ball center to the bouncer center
float distance = vectorLength(directionVector);
// if the distance is greater than the sum of the radii, they aren't touching
if (distance > ball->radius + bouncer->radius || distance == 0) { return; }
// add to score
score += bouncer->score * (1 + streak/10);
streak++;
// trigger bouncer hit effects
bouncer->hitTimer = 5;
directionVector = normalizeVector(directionVector);
// how far into the bouncer the ball is
float inset = ball->radius + bouncer->radius - distance;
// move the ball outside the boucner
ball->position = addVectors(ball->position, scaleVector(directionVector, inset));
// add the new velocity to the ball (away from the bouncer)
float velocityTowardsBouncer = dotProduct(ball->velocity, directionVector); // the component of the ball's velocity in the bouncer's direction
ball->velocity = addVectors(ball->velocity, scaleVector(directionVector, bouncer->pushStrength - velocityTowardsBouncer));
}
void handleFlipperCollision(Ball* ball, Flipper* flipper) {
Vector tip = getFlipperTip(flipper);
Vector closest = closestPointOnLineSegment(ball->position, (LineSegment){flipper->position, tip});
Vector directionVector = subtractVectors(ball->position, closest);
float d = vectorLength(directionVector);
if (d == 0.0 || d > ball->radius + flipper->radius)
return;
// reset streak
streak = 0;
directionVector = scaleVector(directionVector, 1.0 / d);
float corr = (ball->radius + flipper->radius - d);
ball->position = addVectors(ball->position, scaleVector(directionVector, corr));
// update velocity
Vector radius = addVectors(closest, scaleVector(directionVector, flipper->radius));
radius = subtractVectors(radius, flipper->position);
Vector surfaceVel = perpendicularVector(radius);
surfaceVel = scaleVector(surfaceVel, flipper->currentAngularVelocity);
float v = dotProduct(ball->velocity, directionVector);
float vnew = dotProduct(surfaceVel, directionVector);
ball->velocity = addVectors(ball->velocity, scaleVector(directionVector, vnew - v));
}
void handleBorderCollision(Ball* ball, Vector border[], int borderCount) {
if (borderCount < 3)
return;
Vector d, closest, ab, normal;
float minDist = 0.0f;
int closestIndex = 0;
for (int i = 0; i < borderCount; i++) {
Vector a = border[i];
Vector b = border[(i + 1) % borderCount];
Vector c = closestPointOnLineSegment(ball->position, (LineSegment){a, b});
d = subtractVectors(ball->position, c);
float dist = vectorLength(d);
if (i == 0 || dist < minDist) {
minDist = dist;
closest = c;
ab = subtractVectors(b, a);
normal = normalizeVector(perpendicularVector(ab));
closestIndex = i;
}
}
d = subtractVectors(ball->position, closest);
float dist = vectorLength(d);
if (dist < 0.0001f) {
d = normal;
dist = vectorLength(normal);
}
d = normalizeVector(d);
if (dotProduct(d, normal) >= 0.0f) {
if (dist > ball->radius)
return;
ball->position = addVectors(ball->position, scaleVector(normal, ball->radius - dist));
float angle = acos(dotProduct(normalizeVector(ball->velocity), normal));
if (fabs(angle - M_PI/2) < M_PI/6) {
float bounceStrength = 0.5f;
Vector bounceVector = scaleVector(normal, bounceStrength);
ball->velocity = addVectors(ball->velocity, bounceVector);
}
}
else {
ball->position = addVectors(ball->position, scaleVector(d, -(dist + ball->radius)));
}
float v = dotProduct(ball->velocity, normal);
Vector reflectedVelocity = subtractVectors(ball->velocity, scaleVector(normal, 2 * v));
float energyLoss = 0.8f;
ball->velocity = scaleVector(reflectedVelocity, energyLoss);
}
void drawFilledPolygon(BITMAP *bmp, int points[], int num_points, int color) {
for (int i = 1; i < num_points - 1; i++) {
triangle(bmp,
points[0], points[1],
points[i*2], points[i*2+1],
points[(i+1)*2], points[(i+1)*2+1],
color);
}
}
void updateTrail(Ball* ball) {
unsigned long currentTime = clock() * 1000 / CLOCKS_PER_SEC;
if (currentTime - lastTrailUpdate >= TRAIL_CHECK_MS) {
trail[trailIndex] = ball->position;
trailIndex = (trailIndex + 1) % TRAIL_LENGTH;
lastTrailUpdate = currentTime;
}
}
void drawTrail(BITMAP* buffer) {
for (int i = TRAIL_LENGTH - 1; i >= 0; i--) {
int index = (trailIndex - i - 1 + TRAIL_LENGTH) % TRAIL_LENGTH;
// float radius = ball.radius * (TRAIL_LENGTH - i) / TRAIL_LENGTH;
float radius = ball.radius;
float hue = (float)i / TRAIL_LENGTH * 360.0f;
int r, g, b;
hsv_to_rgb(hue, 1.0f, 1.0f, &r, &g, &b);
int color = makecol(r, g, b);
circlefill(buffer, sX(trail[index].x), sY(trail[index].y), sX(radius), color);
}
}
int main(int argc, const char **argv)
{
BITMAP *buffer;
int timer;
// delta time
double old_time = 0;
double new_time = 0;
double dt = 0;
// initialize allegro.
if (allegro_init() != 0) {
return 1;
}
install_keyboard();
install_timer();
// 320x200 graphics mode
if (set_gfx_mode(GFX_AUTODETECT, 320, 200, 0, 0) != 0) {
set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
allegro_message("Cannot set graphics mode:\r\n%s\r\n", allegro_error);
return 1;
}
set_palette(desktop_palette);
// set up scaling
scale = MIN(SCREEN_W, SCREEN_H) / flipperHeight;
simWidth = SCREEN_W / scale;
simHeight = SCREEN_H / scale;
// initialize physics scene
ball = (Ball){
.position = {0.8, 0.7},
.velocity = {0, 0},
.radius = 0.05,
.color = makecol(0, 0, 0),
.restitution = 0
};
Vector ballPositions[10] = {} ;
Vector border[BORDER_POINTS] = {
{0.74, 0.25},
{1 - margin, 0.4},
{1 - margin, flipperHeight - margin},
{margin, flipperHeight - margin},
{margin, 0.4},
{.26, .25},
{.26, -1},
{.74, -1}
};
Flipper flippers[2] = {
{
.radius = 0.03,
.position = {0.26, 0.22},
.length = 0.15,
.restAngle = -0.5,
.maxRotation = 1.0,
.sign = 1,
.angularVelocity = 15.0,
.rotation = 0.0,
.currentAngularVelocity = 0.0,
.touchIdentifier = -1
},
{
.radius = 0.03,
.position = {0.74, 0.22},
.length = 0.15,
.restAngle = M_PI + 0.5,
.maxRotation = 1.0,
.sign = -1,
.angularVelocity = 15.0,
.rotation = 0.0,
.currentAngularVelocity = 0.0,
.touchIdentifier = -1
}
};
// initialize trail
for (int i = 0; i < TRAIL_LENGTH; i++) {
trail[i] = ball.position;
}
Bouncer bouncers[BOUNCER_AMOUNT] = {
{ .position = {0.35, 0.6}, .radius = 0.07, .pushStrength = 2.2, .color = makecol(225, 81, 131), .score = 50, .hitTimer = 0 }, // bottom left
{ .position = {0.65, 0.7}, .radius = 0.09, .pushStrength = 2.0, .color = makecol(82, 247, 159), .score = 70, .hitTimer = 0 }, // bottom right
{ .position = {0.25, 1.0}, .radius = 0.08, .pushStrength = 2.1, .color = makecol(82, 226, 247), .score = 20, .hitTimer = 0 }, // top left
{ .position = {0.75, 1.1}, .radius = 0.06, .pushStrength = 2.3, .color = makecol(247, 235, 82), .score = 30, .hitTimer = 0 }, // top right
{.position = 0.5, 1.4, .radius = 0.15, .pushStrength = 2.0, .color = makecol(255, 255, 255), .score = 100} // top center
};
buffer = create_bitmap(SCREEN_W, SCREEN_H);
// for filling in over the dark background
int white_area[BORDER_POINTS * 2];
for (int i = 0; i < BORDER_POINTS; i++) {
white_area[i*2] = sX(border[i].x);
white_area[i*2+1] = sY(border[i].y);
}
while (1) {
new_time = (double)retrace_count / CLOCKS_PER_SEC;
dt = new_time - old_time;
dt = MIN(dt, 1.0/60.0);
old_time = new_time;
// clear_bitmap(buffer);
clear_to_color(buffer, makecol(0, 0, 0));
drawFilledPolygon(buffer, white_area, BORDER_POINTS, makecol(255, 255, 255));
// draw trail before ball
drawTrail(buffer);
// draw ball
circlefill(buffer, sX(ball.position.x), sY(ball.position.y), sX(ball.radius), ball.color);
circlefill(buffer, sX(ball.position.x + 0.005), sY(ball.position.y + 0.005), sX(ball.radius - 0.018), makecol(50, 50, 50));
circlefill(buffer, sX(ball.position.x + 0.009), sY(ball.position.y + 0.009), sX(ball.radius - 0.035), makecol(100, 100, 100));
// draw borders
for (int i = 0; i < 7; i++) {
line(buffer,
sX(border[i].x), sY(border[i].y),
sX(border[i+1].x), sY(border[i+1].y),
makecol(0, 0, 0));
}
// the last line connecting the end to the start
line(buffer,
sX(border[BORDER_POINTS-1].x), sY(border[BORDER_POINTS-1].y),
sX(border[0].x), sY(border[0].y),
makecol(0, 0, 0));
// draw flippers
for (int i = 0; i < 2; i++) {
Flipper flipper = flippers[i];
float angle = flipper.restAngle + flipper.sign * flipper.rotation;
float cos_angle = cos(angle);
float sin_angle = sin(angle);
float x1 = flipper.position.x + (-flipper.radius * cos_angle);
float y1 = flipper.position.y + (-flipper.radius * sin_angle);
float x2 = flipper.position.x + (flipper.length * cos_angle - flipper.radius * sin_angle);
float y2 = flipper.position.y + (flipper.length * sin_angle + flipper.radius * cos_angle);
float x3 = flipper.position.x + (flipper.length * cos_angle + flipper.radius * sin_angle);
float y3 = flipper.position.y + (flipper.length * sin_angle - flipper.radius * cos_angle);
float x4 = flipper.position.x + (flipper.radius * cos_angle);
float y4 = flipper.position.y + (flipper.radius * sin_angle);
int points[8] = {
sX(x1), sY(y1),
sX(x2), sY(y2),
sX(x3), sY(y3),
sX(x4), sY(y4)
};
polygon(buffer, 4, points, makecol(0, 0, 0));
circlefill(buffer, sX(flipper.position.x), sY(flipper.position.y), sX(flipper.radius), makecol(0, 0, 0));
float end_x = flipper.position.x + flipper.length * cos_angle;
float end_y = flipper.position.y + flipper.length * sin_angle;
circlefill(buffer, sX(end_x), sY(end_y), sX(flipper.radius), makecol(0, 0, 0));
}
// draw bouncers
for (int i = 0; i < BOUNCER_AMOUNT; i++) {
Bouncer* bouncer = &bouncers[i];
// rainbow effect for the 4th bouncer
if (i == 4 && (int)new_time*1000 % 2 == 0) {
float hue = (int)(new_time * 360) % 360;
int r, g, b;
hsv_to_rgb(hue, 1.0f, 1.0f, &r, &g, &b);
bouncer->color = makecol(r, g, b);
}
// effects for when the ball hits a bouncer
float drawRadius = bouncer->radius;
if (bouncer->hitTimer > 0) {
bouncer->hitTimer--;
drawRadius += 0.01;
}
circlefill(buffer, sX(bouncer->position.x), sY(bouncer->position.y), sX(drawRadius), makecol(0, 0, 0));
circle(buffer, sX(bouncer->position.x), sY(bouncer->position.y), sX(drawRadius) - 2, bouncer->color);
}
// draw score
char scoreText[20];
sprintf(scoreText, "Score: %d", score);
textout_ex(buffer, font, scoreText, SCREEN_W - 100, 10, makecol(255, 255, 255), -1);
// draw streak
int streakColor;
int streakBg = -1;
if (streak == 0) {
streakColor = makecol(200, 200, 200);
} else if (streak == 1) {
streakColor = makecol(200, 200, 200);
} else {
float hue = streak * 10;
int r, g, b;
hsv_to_rgb(hue, 1.0f, 1.0f, &r, &g, &b);
streakColor = makecol(r, g, b);
}
if (streak > 15) {
streakBg = makecol(255, 255, 255);
}
char streakText[20];
sprintf(streakText, "Streak: %d", streak);
textout_ex(buffer, font, streakText, SCREEN_W - 100, 23, streakColor, streakBg);
// multiplier text
char multiplierText[20];
sprintf(multiplierText, "%.2fx", 1.0 + (streak / 10.0));
textout_ex(buffer, font, multiplierText, SCREEN_W - 100, 33, streakColor, streakBg);
// draw lives
for (int i = 0; i < lives; i++) {
circlefill(buffer, 130, 10 + (15 * i), 5, makecol(255,255,255));
}
// physics simulations
// flippers
updateFlipper(&flippers[0], dt, key[KEY_LEFT]);
updateFlipper(&flippers[1], dt, key[KEY_RIGHT]);
// ball
updateBall(&ball, dt);
// end game if lives are 0
if (lives == 0) {
allegro_exit();
printf("Thanks for playing! You got: %d", score);
return 0;
}
// ball interactions
for (int i = 0; i < BOUNCER_AMOUNT; i++) {
handleBouncerCollision(&ball, &bouncers[i]);
}
for (int i = 0; i < 2; i++) {
handleFlipperCollision(&ball, &flippers[i]);
}
handleBorderCollision(&ball, border, BORDER_POINTS);
updateTrail(&ball);
vsync();
blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
if (keyboard_needs_poll()) {
poll_keyboard();
}
if (key[KEY_ESC] || (key[KEY_LCONTROL] && key[KEY_C])) {
allegro_exit();
return 0;
}
}
return 0;
}
END_OF_MAIN()