-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfrogger-linux.c
176 lines (148 loc) · 3.03 KB
/
frogger-linux.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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#define WIDTH 30
#define HEIGHT 10
#define STARTING_X 2
#define STARTING_Y HEIGHT - 1
int x, y;
int game_over = 0;
int score = 0;
char grid[HEIGHT][WIDTH] = {
"##############################",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"##############################"};
void draw_grid()
{
system("clear");
for (int i = 0; i < HEIGHT; i++)
{
printf("%s\n", grid[i]);
}
printf("Score: %d\n", score);
}
void move_frogger(int dx, int dy)
{
int new_x = x + dx;
int new_y = y + dy;
if (new_x < 0 || new_x >= WIDTH)
{
return;
}
if (new_y < 0 || new_y >= HEIGHT)
{
return;
}
if (grid[new_y][new_x] == '#')
{
return;
}
if (new_y < y)
{
score += 10;
}
x = new_x;
y = new_y;
}
void spawn_cars()
{
for (int i = 1; i < HEIGHT - 1; i++)
{
if (rand() % 2 == 0)
{
grid[i][0] = '#';
}
else
{
grid[i][WIDTH - 1] = '#';
}
}
}
void move_cars()
{
for (int i = 1; i < HEIGHT - 1; i++)
{
if (grid[i][0] == '#')
{
grid[i][0] = ' ';
grid[i][WIDTH - 1] = '#';
}
else
{
grid[i][WIDTH - 1] = ' ';
grid[i][0] = '#';
}
}
}
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if (ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
int main()
{
x = STARTING_X;
y = STARTING_Y;
srand(time(NULL));
while (!game_over)
{
draw_grid();
if (kbhit())
{
char input = getchar();
switch (input)
{
case 'w':
move_frogger(0, -1);
break;
case 's':
move_frogger(0, 1);
break;
case 'a':
move_frogger(-1, 0);
break;
case 'd':
move_frogger(1, 0);
break;
case 'q':
game_over = 1;
break;
}
}
spawn_cars();
move_cars();
if (grid[y][x] == '#')
{
game_over = 1;
}
usleep(100);
}
printf("Game Over! Final score: %d\n", score);
return 0;
}