6 #include <sys/select.h>
22 return (rand() % (high - low + 1)) + low;
30 return ((rand() % (high - low + 1)) + low) / 100.0;
36 return pow(-1, rand());
42 struct timeval timeout;
43 timeout.tv_usec = 10000;
44 select(NULL, NULL, NULL, NULL, &timeout); // Sleep 100 ms
49 srand((unsigned int)time(NULL));
50 int max_y, max_x, max_y_new, max_x_new;
51 int a_score = 0, b_score = 0;
52 int slope_x = randslope();
53 int index_dir = randsign();
54 int direction = randsign();
55 double speed = randspeed();
56 struct timeval start, stop;
62 nodelay(stdscr, 1); // Don't wait for getch input
63 getmaxyx(stdscr, max_y, max_x);
68 int pad_h = 0.2 * max_y;
69 int aoff = max_y / 2 - pad_h;
70 int boff = max_y / 2 - pad_h;
72 gettimeofday(&start, NULL);
75 getmaxyx(stdscr, max_y_new, max_x_new);
79 if (max_y_new != max_y || max_x_new != max_x) {
89 } else if (key == 'k') {
90 if (boff < max_y - pad_h) boff += 2;
91 } else if (key == 'i') {
92 if (boff > 0) boff -= 2;
93 } else if (key == 's') {
94 if (aoff < max_y - pad_h) aoff += 2;
95 } else if (key == 'w') {
96 if (aoff > 0) aoff -= 2;
97 } else if (key == 27) {
100 mvprintw(0, 0, "PAUSED");
104 } else if (key == 'q') {
112 for (int i = 0; i < max_y + 1; i++) {
115 mvprintw(i, max_x, " ");
116 mvprintw(i, max_x - 1, " ");
120 for (int i = aoff; i < aoff + pad_h; i++) {
124 for (int i = boff; i < boff + pad_h; i++) {
125 mvprintw(i, max_x, "|");
129 for (int i = 0; i < max_y; i++) {
130 mvprintw(i, max_x/2, ":");
134 mvprintw(0, max_x/2 - 2, "%d", a_score);
135 mvprintw(0, max_x/2 + 2, "%d", b_score);
137 // Move ball if enough time has elapsed
138 gettimeofday(&stop, NULL);
139 if ((double)(stop.tv_usec - start.tv_usec) / 1000000 +
140 (double)(stop.tv_sec - start.tv_sec) > speed) {
141 gettimeofday(&start, NULL);
144 if (x % slope_x == 0) y += index_dir;
148 if ((x >= max_x - 1 && y >= boff && y <= boff + pad_h) ||
149 (x <= 1 && y >= aoff && y <= aoff + pad_h)) {
152 /* Find the distance that the ball hits from the center of the padel and
153 accordingly adjust ball path */
154 int poff = (x <= 1) ? aoff : boff;
155 double fromc = (fabs(poff + 0.5 * pad_h - y) / 2);
156 slope_x /= (abs(slope_x) > 25) ? 2 : fromc;
157 slope_x = (slope_x < 2) ? 2 : slope_x;
162 } else if (x >= max_x - 1 || x <= 1) {
163 // Ball goes out of bounds
166 mvprintw(0, 0, "PLAYER B SCORES");
169 mvprintw(0, 0, "PLAYER A SCORES");
173 // Reset to default values
176 slope_x = randslope();
177 index_dir = randsign();
179 aoff = max_y / 2 - pad_h;
180 boff = max_y / 2 - pad_h;
184 } else if (y == 0 || y == max_y) {
185 // Ball hits top or bottom wall
188 y = (y == max_y) ? max_y - 1 : 1;