Instantly share code, notes, and snippets.

@aaronparsekian /pong Secret
Created Oct 6, 2015

Embed
What would you like to do?
var serial;
var speedx = 1;
var speedy = 1;
var x = 10;
var y = 0;
var gravity = 0.1;
var pos = 0;
var len = 40;
var score = 0;
function preload() {
mySound = loadSound('ding.wav');
}
function setup() {
createCanvas(900, 600);
rectMode(CENTER);
noCursor();
noStroke();
gotData();
Initialize();
}
function gotData() {
serial = new p5.SerialPort();
serial.open("/dev/cu.usbmodem1411");
serial.onData(gotData);
this.data = serial.readLine();
if (this.data.length > 0); {
if (this.data > 0) {
pos = map(Number(this.data), 0, 1023, len, width - len);
rect(pos, height - 10, 2 * len, 20);
}
}
}
function draw() {
Gameplay();
}
function Initialize() {
createCanvas(900, 600);
noStroke();
rectMode(CENTER);
noCursor();
this.x = random(width);
}
function Gameplay() {
background(0, 100);
stroke(255);
textSize(50);
text(score, 800, 500);
// bouncing ball
ellipse(x, y, 10, 10);
// set speed of bouncing ball
y += speedy;
x += speedx;
speedy += gravity;
// if x value is off screen, change direction
if (x < 0 || x > width) {
speedx *= -1;
}
// if y value is off the top of screen, change direction
if (y < 0) {
speedy *= -1;
}
// if ball is hitting paddle, bounce away
if (y > 580 && x > pos - len && x < pos + len) {
speedy *= -1;
score++;
mySound.setVolume(3);
mySound.play();
// if ball does not hit paddle/falls off screen, lose game
} else if (y > height) {
x = 0;
cursor();
background(255, 255, 0);
stroke(255);
textSize(40);
text("Game Over", 320, 300);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment