]> code.delx.au - pong/blobdiff - pong.c
Optional AI, scores now reset when they hit 9
[pong] / pong.c
diff --git a/pong.c b/pong.c
index ad2abdace89bff8d9f2535e297a082776e36347b..6f2ec4ce02c40741ab36994d997cc0580b23e450 100644 (file)
--- a/pong.c
+++ b/pong.c
@@ -16,6 +16,7 @@
 #define PADDLESIZE  10
 #define HEIGHT      100
 
+static int AI = 0;
 static int p1move = 0;
 static int p2move = 0;
 static int score1 = 0;
@@ -39,6 +40,16 @@ static void initball(void) {
 }
 
 static void run(void) {
+       // AI
+       if(AI) {
+               if(ballY < paddle2 - PADDLESIZE)
+                       p2move = -1;
+               else if(ballY > paddle2 + PADDLESIZE)
+                       p2move = 1;
+               else
+                       p2move = 0;
+       }
+
        // Move the paddles
        paddle1 += p1move * PADDLESPEED;
        paddle2 += p2move * PADDLESPEED;
@@ -66,17 +77,25 @@ static void run(void) {
        if(ballX >= HEIGHT) {
                ++score1;
                initball();
-               return;
        }
        if(ballX <= -HEIGHT) {
                ++score2;
                initball();
-               return;
        }
 
        // Move the ball
        ballX += ballVecX;
        ballY += ballVecY;
+
+       // Check scores for winners..
+       if(score1 == 9) {
+               // Player 1 wins
+               score1 = score2 = 0;
+       }
+       if(score2 == 9) {
+               // Player 2 wins
+               score1 = score2 = 0;
+       }
 }
 
 static void display(void) {
@@ -175,6 +194,10 @@ static void init(void) {
 }
 
 int main(int argc, char *argv[]) {
+       if(argc == 2 && *argv[1] == '1') {
+               AI = 1;
+       }
+
        glutInitWindowPosition(100, 100);
        glutInitWindowSize(640, 480);
        glutInit(&argc, argv);