-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblasteroids.c
executable file
·92 lines (83 loc) · 2.97 KB
/
blasteroids.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
#include "blasteroids.h"
int main(void) {
ALLEGRO_DISPLAY *display;
int display_width, display_height;
Spaceship s;
ALLEGRO_EVENT_QUEUE *q;
ALLEGRO_TIMER *timer;
ALLEGRO_EVENT event;
al_init();
al_init_primitives_addon();
al_install_keyboard();
display = al_create_display(800, 640);
al_clear_to_color(al_map_rgba(0,0,0,255));
al_flip_display();
display_width = al_get_display_width(display);
display_height = al_get_display_height(display);
s.x = display_width/2;
s.y = display_height/2;
s.rotation = M_PI;
s.rotating = 0;
s.speed = 0;
s.accelerating = 0;
s.lifes = 3;
s.color = al_map_rgb(255,255,255);
q = al_create_event_queue();
al_register_event_source(q, al_get_keyboard_event_source());
timer = al_create_timer(1.0f/FPS);
al_register_event_source(q, al_get_timer_event_source(timer));
al_start_timer(timer);
while (true) {
al_wait_for_event(q, &event);
if(event.type == ALLEGRO_EVENT_KEY_DOWN){
switch (event.keyboard.keycode) {
case ALLEGRO_KEY_LEFT:
s.rotating = 1;
break;
case ALLEGRO_KEY_RIGHT:
s.rotating = -1;
break;
case ALLEGRO_KEY_UP:
s.accelerating = 1;
break;
case ALLEGRO_KEY_DOWN:
s.accelerating = -1;
break;
case ALLEGRO_KEY_SPACE:
//TODO
break;
}
}else if(event.type == ALLEGRO_EVENT_KEY_UP){
switch (event.keyboard.keycode) { //TODO: need to get adequate input. Considering using multiple threads
case ALLEGRO_KEY_LEFT: //fall through
case ALLEGRO_KEY_RIGHT:
s.rotating = 0;
break;
case ALLEGRO_KEY_UP: //fall through
case ALLEGRO_KEY_DOWN:
s.accelerating = 0;
break;
case ALLEGRO_KEY_SPACE:
//TODO
break;
}
}else if (event.type == ALLEGRO_EVENT_TIMER){
//Redraw scene, ...
al_clear_to_color(al_map_rgb(0,0,0));
draw_spaceship(&s);
al_flip_display();
//... then compute physics
//s.rotation += SPACESHIP_ANGULAR_VELOCITY*s.rotating/FPS;
s.rotation = fmod(s.rotation + SPACESHIP_ANGULAR_VELOCITY*s.rotating/FPS, 2*M_PI);
s.speed = clamp(s.speed + SPACESHIP_ACCELERATION*s.accelerating*(1.0f/FPS), SPACESHIP_MIN_SPEED, SPACESHIP_MAX_SPEED);
s.x = clamp(s.x + s.speed*sin(s.rotation)*(1.0f/FPS), 0, (float)display_width);
s.y = clamp(s.y + s.speed*cos(s.rotation)*(1.0f/FPS), 0, (float)display_height);
}
}
return 0;
}
float clamp(float val, float min_val, float max_val){
if(val > max_val) val = max_val;
else if(val < min_val) val = min_val;
return val;
}