21 return (rand() % (high - low + 1)) + low;
29 return ((rand() % (high - low + 1)) + low) / 100.0;
35 return pow(-1, rand());
40 srand((unsigned int)time(NULL));
41 int max_y, max_x, max_y_new, max_x_new;
42 int a_score = 0, b_score = 0;
43 int slope_x = randslope();
44 int index_dir = randsign();
45 int direction = randsign();
46 double speed = randspeed();
47 struct timeval start, stop;
53 nodelay(stdscr, 1); // Don't wait for getch input
54 getmaxyx(stdscr, max_y, max_x);
59 int pad_h = 0.2 * max_y;
60 int aoff = max_y / 2 - pad_h;
61 int boff = max_y / 2 - pad_h;
63 gettimeofday(&start, NULL);
66 getmaxyx(stdscr, max_y_new, max_x_new);
70 if (max_y_new != max_y || max_x_new != max_x) {
80 } else if (key == 'k') {
81 if (boff < max_y - pad_h) boff += 2;
82 } else if (key == 'i') {
83 if (boff > 0) boff -= 2;
84 } else if (key == 's') {
85 if (aoff < max_y - pad_h) aoff += 2;
86 } else if (key == 'w') {
87 if (aoff > 0) aoff -= 2;
88 } else if (key == 27) {
91 mvprintw(0, 0, "PAUSED");
95 } else if (key == 'q') {
102 for (int i = 0; i < max_y + 1; i++) {
105 mvprintw(i, max_x, " ");
106 mvprintw(i, max_x - 1, " ");
110 for (int i = aoff; i < aoff + pad_h; i++) {
114 for (int i = boff; i < boff + pad_h; i++) {
115 mvprintw(i, max_x, "|");
119 for (int i = 0; i < max_y; i++) {
120 mvprintw(i, max_x/2, ":");
124 mvprintw(0, max_x/2 - 2, "%d", a_score);
125 mvprintw(0, max_x/2 + 2, "%d", b_score);
127 // Move ball if enough time has elapsed
128 gettimeofday(&stop, NULL);
129 if ((double)(stop.tv_usec - start.tv_usec) / 1000000 +
130 (double)(stop.tv_sec - start.tv_sec) > speed) {
131 gettimeofday(&start, NULL);
134 if (x % slope_x == 0) y += index_dir;
138 if ((x >= max_x - 1 && y >= boff && y <= boff + pad_h) ||
139 (x <= 1 && y >= aoff && y <= aoff + pad_h)) {
142 /* Find the distance that the ball hits from the center of the padel and
143 accordingly adjust ball path */
144 int poff = (x <= 1) ? aoff : boff;
145 double fromc = (fabs(poff + 0.5 * pad_h - y) / 2);
146 slope_x /= (abs(slope_x) > 25) ? 2 : fromc;
147 slope_x = (slope_x < 2) ? 2 : slope_x;
152 } else if (x >= max_x - 1 || x <= 1) {
153 // Ball goes out of bounds
156 mvprintw(0, 0, "PLAYER B SCORES");
159 mvprintw(0, 0, "PLAYER A SCORES");
163 // Reset to default values
166 slope_x = randslope();
167 index_dir = randsign();
169 aoff = max_y / 2 - pad_h;
170 boff = max_y / 2 - pad_h;
174 } else if (y == 0 || y == max_y) {
175 // Ball hits top or bottom wall
178 y = (y == max_y) ? max_y - 1 : 1;