-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforestfire.cpp
122 lines (96 loc) · 2.72 KB
/
forestfire.cpp
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
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include <iostream>
#include <math.h>
using namespace std;
#define N 800
#define M 800
enum states {EMPTY = 0, TREE = 1, FIRE = 2};
float probRand() {
return (float) rand() / RAND_MAX;
}
bool withinGrid(int row, int col) {
if((row < 0) || (col<0))
return false;
if((row >= N) || (col >= M))
return false;
return true;
}
bool getNeighbors(int x, int y, int** forest) {
for(int i=x-1; i<=(x+1); i++) {
for(int j=y-1; j<=(y+1); j++) {
if(!(i==x && j==y)) {
if(withinGrid(i, j) && forest[i][j] == FIRE)
return true;
}
}
}
return false;
}
void print(int** forest) {
al_clear_to_color(al_map_rgb(0, 0, 0));
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
switch(forest[i][j]) {
case EMPTY:
al_draw_filled_rectangle(i*5, j*5, i*5+5, j*5+5, al_map_rgb(0,0,0));
break;
case TREE:
al_draw_filled_rectangle(i*5, j*5, i*5+5, j*5+5, al_map_rgb(34,139,34));
break;
case FIRE:
al_draw_filled_rectangle(i*5, j*5, i*5+5, j*5+5, al_map_rgb(255,140,0));
break;
}
}
}
al_flip_display();
al_rest(0.2);
}
void game(int** forest, float p, float f) {
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
switch(forest[i][j]) {
case EMPTY:
if(probRand() < p)
forest[i][j] = TREE;
break;
case TREE:
if(getNeighbors(i, j, forest) || probRand() < f)
forest[i][j] = FIRE;
break;
case FIRE:
forest[i][j] = EMPTY;
break;
}
}
}
}
int main(int argc, char *argv[]) {
int** forest = new int*[N];
float p = 0.02; // Probability of new growth
float f = 0.0002; // Probability of lightning
// Matrix init
for(int i=0; i<N; i++)
forest[i] = new int[M];
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
forest[i][j] = EMPTY;
// Allegro Setup
ALLEGRO_DISPLAY* display;
const int displayHeight = N;
const int displayWidth = M;
al_init();
display = al_create_display(displayWidth, displayHeight);
al_init_primitives_addon();
// Start
while(true) {
print(forest);
game(forest, p, f);
}
for(int i=0; i<M; i++) {
delete[] forest[i];
}
delete[] forest;
return 0;
}