A simple pong-like game written in C with ncurses
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

121 lines
2.6 KiB

#include <ncurses.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include "config.h"
void print_paddle(int size, int y, int x)
{
for (int i = 0; i < size; ++i)
mvprintw(y - i, x, "|");
}
void decorations(int width, int height)
{
for (int i = 0; i < width; ++i)
mvprintw(0, i, "*");
for (int i = 0; i < width; ++i)
mvprintw(height - 1, i, "*");
}
// Updates the panel of information
void refresh_score(int lives, int hits)
{
char str_lives[3];
char str_hits[3];
sprintf(str_lives, "%d", lives);
sprintf(str_hits, "%d", hits);
mvprintw(1, 1, "Lives:");
mvprintw(1, 9, str_lives);
mvprintw(1, 13, "Hits:");
mvprintw(1, 20, str_hits);
}
int main()
{
srand(time(NULL)); // initiate randomness
int ball_x = 20, ball_y = 10, paddle_y = 10;
int max_y = 0, max_x = 0;
int ball_next_x = 0, ball_next_y = 0;
int ball_direction_x = 1, ball_direction_y = 0;
int lives = LIVES;
int hits = 0;
initscr();
noecho();
nodelay(stdscr, TRUE);
curs_set(FALSE);
while (1) {
getmaxyx(stdscr, max_y, max_x);
switch (getch()) {
case 'q':
endwin();
return 0;
case 'w':
if ((paddle_y - PADDLE_SPEED) > 0)
paddle_y -= PADDLE_SPEED;
else
paddle_y = PADDLE_SIZE;
break;
case 's':
if ((paddle_y + PADDLE_SPEED) < max_y)
paddle_y += PADDLE_SPEED;
else
paddle_y = max_y - 1;
break;
}
erase();
decorations(max_x, max_y);
refresh_score(lives, hits);
mvprintw(ball_y, ball_x, "o");
print_paddle(PADDLE_SIZE, paddle_y, max_x - 2);
refresh();
usleep(DELAY - hits * 500); // Make it progressively faster
ball_next_x = ball_x + ball_direction_x;
ball_next_y = ball_y + ball_direction_y;
// Check if the ball is going to hit any part of the paddle
for (int i = 0; i < PADDLE_SIZE; ++i) {
if (ball_y == paddle_y - i && ball_next_x >= max_x - 2) {
ball_direction_x *= -1;
ball_direction_y = rand() % 3 - 1;
hits++;
break;
}
}
// Check if the ball is going to hit the edges
if (ball_next_x >= max_x || ball_next_x < 0)
ball_direction_x *= -1;
else
ball_x += ball_direction_x;
if (ball_next_y >= max_y - 1 || ball_next_y < 1)
ball_direction_y *= -1;
else
ball_y += ball_direction_y;
// Check if the ball gets past the paddle
if (ball_next_x > max_x - 2) {
lives -= 1;
sleep(1);
if (lives == 0)
break;
ball_x = 20;
ball_y = 10;
ball_direction_y = 0;
ball_direction_x = 1;
}
}
mvprintw(10, 34, "GAME OVER!");
mvprintw(11, 31, "press \'q\' to quit");
refresh();
while (getchar() != 'q');
endwin();
printf("GAME OVER. You got %d hits!\n", hits);
return 0;
}