#include <ncurses.h>
const int X_SIZE = 80;
const int Y_SIZE = 25;
const int RACKET_SIZE = 3;
const int LEFT_X = 3;
const int RIGHT_X = X_SIZE - LEFT_X - 1;
void print_field(int ball_x, int ball_y, int racket_left_y, int racket_right_y) {
int x, y;
for (y = 0; y < Y_SIZE; y++) {
for (x = 0; x < X_SIZE; x++) {
if (y == 0 || y == Y_SIZE - 1) {
printw("-");
} else if (x == ball_x && y == ball_y) {
printw("o");
} else if (x == LEFT_X && y >= racket_left_y && y < racket_left_y + RACKET_SIZE) {
printw("|");
} else if (x == RIGHT_X && y >= racket_right_y && y < racket_right_y + RACKET_SIZE) {
printw("|");
} else if (x == X_SIZE / 2) {
printw("|");
} else {
printw(" ");
}
}
printw("\n");
}
}
void print_score(int score_left, int score_right) {
int margin_left = 27;
printw("\n");
for (int i = 0; i < margin_left; i++) printw(" ");
printw(" SCORE\n\n");
for (int i = 0; i < margin_left; i++) printw(" ");
printw("Player 1 Player 2\n\n");
for (int i = 0; i < margin_left; i++) printw(" ");
printw(" %d %d \n", score_left, score_right);
}
int main() {
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
int ball_x = X_SIZE / 2, ball_y = Y_SIZE / 2;
int ball_dx = 1, ball_dy = 1;
int racket_left_y = Y_SIZE / 2 - 1;
int racket_right_y = Y_SIZE / 2 - 1;
int score_left = 0, score_right = 0;
int game_running = 1;
while (game_running) {
clear();
print_field(ball_x, ball_y, racket_left_y, racket_right_y);
print_score(score_left, score_right);
refresh();
int ch = getch();
if (ch == 'a' || ch == 'A') {
if (racket_left_y > 1) racket_left_y--;
} else if (ch == 'z' || ch == 'Z') {
if (racket_left_y < Y_SIZE - RACKET_SIZE - 1) racket_left_y++;
} else if (ch == 'k' || ch == 'K') {
if (racket_right_y > 1) racket_right_y--;
} else if (ch == 'm' || ch == 'M') {
if (racket_right_y < Y_SIZE - RACKET_SIZE - 1) racket_right_y++;
} else if (ch == ' ') {
} else if (ch == 27) { //escape значение = 27, которое возвращает функция getch() из ncurses
game_running = 0;
break;
}
ball_x += ball_dx;
ball_y += ball_dy;
if (ball_y <= 1 || ball_y >= Y_SIZE - 2) {
ball_dy = -ball_dy;
}
if (ball_x == LEFT_X + 1 && ball_y >= racket_left_y && ball_y < racket_left_y + RACKET_SIZE) {
ball_dx = -ball_dx;
}
if (ball_x == RIGHT_X - 1 && ball_y >= racket_right_y && ball_y < racket_right_y + RACKET_SIZE) {
ball_dx = -ball_dx;
}
if (ball_x <= 0) {
score_right++;
ball_x = X_SIZE / 2; ball_y = Y_SIZE / 2;
ball_dx = 1;
}
if (ball_x >= X_SIZE - 1) {
score_left++;
ball_x = X_SIZE / 2; ball_y = Y_SIZE / 2;
ball_dx = -1;
}
if (score_left == 21 || score_right == 21) {
game_running = 0;
}
}
endwin();
return 0;
}