Code:
#include <iostream>
#include <curses.h>
using namespace std;
/*********************** Global Variables *********************/
char paddle = '|';
char ball = 'O';
char str[1000];
double posx = 12;
double posy = 12;
double speedx = 0.004;
double speedy = 0.004;
int maxX, maxY;
int blocks = 0;
int misses = 0;
int x = 12;
int y = 12;
/*************** Function Prototypes *******************/
void initialize();
void quit();
void displayPaddle(int y, int x, char paddle);
void moveBall();
void movePaddle();
void displayScreen();
void pause(int x);
void printLogo();
/**************** Main ************************/
int main(){
initialize();
movePaddle();
return 0;
}
/******************** Initialize Function *********************/
void initialize(){
initscr(); /* initialize the curses library */
keypad(stdscr, TRUE); /* enable keyboard mapping */
nonl(); /* tell curses not to do NL->CR/NL on output */
cbreak(); /* take input chars one at a time, no wait for \n */
noecho(); /* don't echo input */
nodelay(stdscr, TRUE); /* allows no delay for speed on ball*/
}
/***************** displayPaddle function ****************/
void displayPaddle(int y, int x, char paddle){
mvaddch(y, x, paddle);
mvaddch(y+1, x, paddle);
mvaddch(y+2, x, paddle);
mvaddch(y-1, x, paddle);
mvaddch(y-2, x, paddle);
}
/******************* moveBall function ******************/
void moveBall(){
displayScreen();
getmaxyx(stdscr, maxY, maxX);
mvaddch((int) posy, (int) posx, ' ');
posx = posx + speedx;
posy = posy + speedy;
if(posx <= 0){
speedx = -1.0 * speedx;
misses++;
}
if(posx >= maxX){
speedx = -1.0 * speedx;
}
if(posy <= 0){
speedy = -1.0 * speedy;
}
if(posy >= maxY){
speedy = -1.0 * speedy;
}
mvaddch((int) posy, (int) posx, ball);
}
/**************** movePaddle function *********************/
void movePaddle(){
getmaxyx(stdscr, maxY, maxX);
for (;;){
int c = getch();
if(c == 'q' || c == 'Q'){
endwin();
break;
}
moveBall();
displayPaddle(y,x,' ');
if(y<=(maxY-4) && y>=3){
switch (c){
case 'w':
y--;
break;
case 'W':
y--;
break;
case 's':
y++;
break;
case 'S':
y++;
break;
default:
break;
}
}else if(y>(maxY-4)){
switch (c){
case 'w':
y--;
break;
case 'W':
y--;
break;
case 's':
break;
default:
break;
}
}else if(y<3){
switch (c){
case 'w':
break;
case 's':
y++;
break;
case 'S':
y++;
break;
default:
break;
}
}
displayPaddle(y,x,paddle);
}
}
/************** displayScreen function********************/
void displayScreen(){
sprintf(str, "Blocks: %2i", blocks);
mvaddstr(0, 60, str);
sprintf(str, "Misses: %2i", misses);
mvaddstr(1, 60, str);
sprintf(str, "Press Q to quit");
mvaddstr(0, 30, str);
}
/****************** pause function **********************/
void pause(int x){
for(int i=0;i<x*1000000;i++){
//pause
}
}
/****************** printLogo function *******************/
void printLogo(){
sprintf(str, "P O N G P O N G P O N G P O N G P O N G");
mvaddstr(10, 19, str);
mvaddstr(11, 20, str);
mvaddstr(12, 19, str);
}