Skip to content

Instantly share code, notes, and snippets.

@m1cr0lab
Created August 5, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1cr0lab/eb9e2b5995fccebd55b0e33a48630344 to your computer and use it in GitHub Desktop.
Save m1cr0lab/eb9e2b5995fccebd55b0e33a48630344 to your computer and use it in GitHub Desktop.
Dynamic stretching and shrinking of a pong paddle (Gamebuino Meta)
/**
* Dynamic stretching and shrinking of a pong paddle
*
* This piece of code follows a question by Cric on Gamebuino's forum:
* @see https://community.gamebuino.com/t/moving-ball-probleme-de-test-de-sortie-decran-non-effectue/262/22
*/
#include <Gamebuino-Meta.h>
/**
* 0 for an arithmetical progression
* 1 for a geometrical progression
*/
#define GEOMETRIC 0
const uint8_t SCREEN_W = 80;
const uint8_t SCREEN_H = 64;
struct Paddle {
static const uint8_t W = 3;
static const uint8_t H = 16;
static const uint8_t H_SHRUNK = 8;
static const uint8_t VY = 2;
uint8_t x;
uint8_t y;
uint8_t h;
uint8_t th;
#if GEOMETRIC
float_t fh;
#endif
bool sizing;
Paddle(uint8_t x, uint8_t y) : x(x), y(y), h(H), th(H), sizing(false) {}
void up() { y -= VY; }
void down() { y += VY; }
void shrink() {
sizing = true;
th = H_SHRUNK;
#if GEOMETRIC
fh = h;
#endif
}
void stretch() {
sizing = true;
th = H;
#if GEOMETRIC
fh = h;
#endif
}
void update() {
if (sizing) {
#if GEOMETRIC
float_t dh = th - fh;
if (abs(dh) < 1) {
h = th;
sizing = false;
} else {
fh += .5f * dh;
if (abs(fh - h) > 1.5f) h += fh < h ? -2 : 2;
}
#else
if (h == th) sizing = false;
else h += th - h < 0 ? -2 : 2;
#endif
}
uint8_t h2 = .5f * h;
if (y < h2) y = h2;
else if (y + h2 > SCREEN_H) y = SCREEN_H - h2;
}
void draw() {
gb.display.setColor(WHITE);
gb.display.fillRect(x, y - (.5f * h), W, h);
}
};
Paddle player(4, .5f * SCREEN_H);
void readButtons() {
if (gb.buttons.repeat(BUTTON_UP, 0)) player.up();
else if (gb.buttons.repeat(BUTTON_DOWN, 0)) player.down();
if (gb.buttons.pressed(BUTTON_A)) player.shrink();
else if (gb.buttons.pressed(BUTTON_B)) player.stretch();
}
void update() {
player.update();
}
void draw() {
player.draw();
}
void setup() {
gb.begin();
}
void loop() {
gb.waitForUpdate();
gb.display.clear();
readButtons();
update();
draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment