Browse Source

Add basic pong game

master
MasterOfTheSoftware 2 weeks ago
commit
ccdbe22125
2 changed files with 141 additions and 0 deletions
  1. 3
    0
      Makefile
  2. 138
    0
      pong.c

+ 3
- 0
Makefile View File

@@ -0,0 +1,3 @@
LDFLAGS=-lncurses

all: pong

+ 138
- 0
pong.c View File

@@ -0,0 +1,138 @@
#include <ncurses.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>

const int DELAY = 30000;
const int PADDLE_SIZE = 5;
const int PADDLE_SPEED = 4;

int kbhit()
{
int ch = getch();

if (ch != ERR) {
ungetch(ch);
return 1;
} else {
return 0;
}
}

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 = 5;
int hits = 0;

initscr();
noecho();
nodelay(stdscr, TRUE);
curs_set(FALSE);

while (1) {
getmaxyx(stdscr, max_y, max_x);
if (kbhit()) {
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;
}
}

clear();
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;
}

Loading…
Cancel
Save