This is the classic Atari game called Pong, recreated by my son all on his own for the RBX. I am extremely proud of him!
Connect:
- OLED Display Brick to Port 4E
- Rotary Switch Brick to Port 2A and Port 4A
- Buzzer Brick to Port 2B
Run the following script:
var rs = new RotarySwitch(PORT_2A,PORT_4D);
var sc = new OledDisplay();
var buz = new Buzzer(PORT_2B);
function resetBall() {
ballx = sc.width()/2;
bally = sc.height()/2;
bs = [3,3];
bv = [bs[0],bs[1]];
}
function hit() {
buz.playTone((Math.random()*100)+600, 80);
}
function scored() {
buz.playNote(NOTE_E, 5, 250);
buz.playNote(NOTE_A, 5, 250);
}
// variabes
var speed = 3;
var s = 1;
var b = 5;
var pheight = 24;
var score = [0,0];
var start = false;
// ai variables
var y1 = sc.height()/2-pheight/2;
// player variables
rs.setValue(sc.height()/2-pheight/2);
var y2 = rs.getValue();
// ball variables
var ballx = 16;
var bally = 16;
var bs = [3,3];
var bv = [bs[0],bs[1]];
var bw = 7;
sc.setFont(FONT_LARGE);
while (!start) {
sc.drawString(6,32,"PRESS TO START");
if (rs.clicked()) {
start = true;
}
while(start) {
sc.startBuffer();
sc.clear();
// get player y position
y2 += rs.getDelta()*speed;
if (y2 < 0) {
y2 = 0;
}
if (y2 > sc.height()-pheight) {
y2 = sc.height()-pheight;
}
// set ai y position to ball y position
if (bally-pheight/2 > y1) {
y1 += speed;
}
else if (bally-pheight/2 < y1) {
y1 -= speed;
}
// draw bg
sc.drawLine(sc.width()/2,0,sc.width()/2,sc.height());
// draw score
sc.drawString(sc.width()/2-16,10,score[0].toString());
sc.drawString(sc.width()/2+8,10,score[1].toString());
// draw ai
sc.drawRect(2,y1,5,pheight,filled=true);
// draw player
sc.drawRect(121,y2,5,pheight,filled=true);
// draw ball
sc.drawEllipse(ballx,bally,3,3,filled=true);
// ball velocity
ballx += bv[0];
bally += bv[1];
// ball wall collision
if (ballx > sc.width()-b) {
resetBall();
scored();
score[0] += 1;
}
else if (ballx < b) {
resetBall();
scored();
score[1] += 1;
}
if (bally > sc.height()-b) {
bv[1] = -bs[1];
}
else if (bally < b) {
bv[1] = bs[1];
}
// ball paddle collision
if ((ballx > 121 && ballx < 128) || (ballx+bw > 121 && ballx+bw < 128)) {
if ((bally > y2 && bally < y2+pheight) || (bally+bw > y2 && bally+bw < y2+pheight)) {
hit();
ballx = 116;
bv[0] = -bs[0];
if (bs[0] < 6) {
bs[0] += s;
bs[1] += s/4;
}
}
}
if ((ballx > 0 && ballx < 12) || (ballx+bw > 0 && ballx+bw < 12)) {
if ((bally > y1 && bally < y1+pheight) || (bally+bw > y1 && bally+bw < y1+pheight)) {
hit();
ballx = 12;
bv[0] = bs[0];
if (bs[0] < 7) {
bs[0] += s;
bs[1] += s/4;
}
}
}
sc.flushBuffer();
}
}
Here is the game in action: