OK, here's a specific example of something in your code that could broken down into a separate function, the code for drawing the paddles. RIght now, it consists of two successive nested for() loops, to draw the initial state of the paddles, plus similar loops throughout the code to redraw them when they are changed. The whole thing could be simplfied as a single function of arity three:
Code: Select all
enum {BLACK = 0, WHITE = 223} COLOR;
int const p1_col = 10;
int const p2_col = 304;
void draw_paddle(int hpos, int vpos, COLOR c)
{
int const width = 6;
int const height = 22;
for(int dy=0;dy<height;dy++)
{
for(int dx=0;dx<width;dx++)
{
video.putpixel(hpos+dx,vpos+dy, c);
}
}
}
Which could then be called like so:
Code: Select all
draw_paddle(p1_col, p1[0], WHITE);
draw_paddle(p2_col, p2[0], WHITE);
To move the paddle, you'd simply do something like:
Code: Select all
draw_paddle(p1_col, p1[0], BLACK); // erase paddle
p1[0] -= 2; // move paddle
draw_paddle(p1_col, p1[0], WHITE);
Note that this code has not been not tested; it is simply a demonstration of how it could be simplified. There are several sections of the code where this should be possible; how you would decompose it would be up to you. Note that this may require some changes in the program flow, but if done carefully, the changes should improve overall program behavior.
Admittedly, I'm something of a fanatic on this point: if four or more lines of code are used twice in a program, I often try to make a function out of them. Similarly, I loathe having any
magic numbers (def. 1) in code, and invariably put them into named constants, even if they are only used once. You probably don't want to go to quite such lengths, but you really would be better off decomposing the problem further than you have and givng names to the more commonly used constants.