Playing with myself
After all the rigmarole and messing about I went through getting some text to draw itself on the screen, I was bracing myself for plenty of hassle checking off the next point on my Pong clone wishlist: a computer opponent. Until now both bats have been human-controlled via the keyboard.
But to my surprise it didn’t take much setting up.
First a new boolean variable within the player structure so that each player can be either human-controlled or computer-controlled.
Then a new function, moveAIbat, that does exactly what it says on the tin. It finds out where the ball is and what direction it’s moving in. Then if necessary (and if it won’t result in the bat moving off the screen) it moves the bat co-ordinates either up or down (towards the ball’s y position) by a fixed amount.
Fewer than 20 lines of code from start to finish, but it seems to do the job. It’s not quite what you’d call AI, but to my surprise it’s good enough to win a fair proportion of points. My first game vs CPU ended 10-7 (keeping tally of the score and making the first to 10 a winner was added soon after solving the zoomstring conundrum).