-
Notifications
You must be signed in to change notification settings - Fork 0
/
bouncing_ball.ino_
64 lines (57 loc) · 1.44 KB
/
bouncing_ball.ino_
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#define BALL_UP 0
#define BALL_RIGHT 1
#define BALL_LEFT 2
#define BALL_DOWN 3
struct Ball {
int x;
int y;
int direction;
};
struct Ball ball;
void drawBallUpdates(){
int pixelIndex = getPixelIndex(ball.x, ball.y);
pixels.SetPixelColor(pixelIndex, RgbColor(0, 0, 0));
Serial.print("x:");
Serial.print(ball.x);
Serial.print(" y:");
Serial.print(ball.y);
Serial.print(" direction:");
Serial.println(ball.direction);
switch (ball.direction){
case BALL_UP: ball.y++;break;
case BALL_RIGHT: ball.x++;break;
case BALL_LEFT: ball.x--;break;
case BALL_DOWN: ball.y--;break;
}
detectBorderAndSwitchDirections();
pixelIndex = getPixelIndex(ball.x, ball.y);
pixels.SetPixelColor(pixelIndex, RgbColor(0, 0, 64));
pixels.Show();
delay(200);
}
void detectBorderAndSwitchDirections(){
switch(ball.x) {
case -1:
ball.x++;
ball.direction = newRandomDirection(ball.direction); break;
case ROWS:
ball.x--;
ball.direction = newRandomDirection(ball.direction); break;
}
switch(ball.y) {
case -1:
ball.y++;
ball.direction = newRandomDirection(ball.direction); break;
case ROWS:
ball.y--;
ball.direction = newRandomDirection(ball.direction); break;
}
}
int newRandomDirection(int oldDirection){
int newDirection = random(0, BALL_DOWN);
if(newDirection != oldDirection){
return newDirection;
} else {
return newRandomDirection(oldDirection);
}
}