xxxxxxxxxx
149
let timer = 20;
let gameState = "start";
let mypongBall;
let xBall = Math.floor(Math.random() * 300) + 50;
let yBall = 50;
let xSpeed = (5, 9);
let ySpeed = (-9, -5);
let score = 0;
let restart;
let photo;
class pongBall {
constructor() {
this.xPos = xBall;
this.yPos = 50;
this.xSpeed = (5, 9);
this.ySpeed = (-9, -5);
}
move() {
xBall += xSpeed;
yBall += ySpeed;
}
checkForCollisions() {
if (xBall < 10 || xBall > 500 - 10) {
xSpeed *= -1;
}
if (yBall < 10 || yBall > 445 - 10) {
ySpeed *= -1;
}
}
draw() {
fill(218, 255, 115);
ellipse(xBall, yBall, 20, 20);
}
// Bounce off the bar
barCollisions() {
if (xBall > mouseX && xBall < mouseX + 90 && yBall + 10 >= 440) {
xSpeed *= -1;
ySpeed *= -1;
score++;
song.play();
}
}
}
function preload() {
font = loadFont("JetBrainsMono-ExtraBold.ttf");
song = loadSound("media_doorbell.mp3");
photo = loadImage("cat.webp");
}
// Canvas
function setup() {
createCanvas(500, 500);
textFont(font);
background(255);
angleMode(DEGREES);
rectMode(CENTER);
noStroke();
mypongBall = new pongBall();
}
function draw() {
if (gameState == "start") {
startScreen();
}
if (gameState == "play") {
playScreen();
}
if (gameState == "end") {
restartScreen();
}
}
function restartScreen() {
if (keyCode == ENTER) {
gameState = "start";
}
}
function startScreen() {
background(0);
fill(255);
text(
"If you manage to get 5 points under\n 20 seconds, you will win the game.\n Press ENTER to start the game",
100,
250
);
//click ENTER to play
if (keyCode == ENTER) {
gameState = "play";
}
}
function playScreen() {
background(0);
mypongBall.move();
mypongBall.checkForCollisions();
mypongBall.draw();
mypongBall.barCollisions();
//bar
fill("white");
rect(mouseX, 450, 90, 15);
//score
fill(218, 255, 115);
textSize(24);
text("Score: " + score, 190, 80);
//title
fill("white");
textSize(30);
text("PONG STREAK", 150, 40);
//countdown
textAlign(CENTER, CENTER);
fill("white");
textSize(50);
text(timer, width / 2, height / 2);
if (frameCount % 60 == 0 && timer > 0) {
// if the frameCount is divisible by 60, then a second has passed. it will stop at 0
timer--;
}
if (timer == 0) {
image(photo, 200, 200, 250, 250);
fill(255);
textSize(25);
text("GAME OVER", width / 2, height * 0.7);
{
if (score >= 5) {
text("YOU WON", width / 2, height / 3);
} else {
text("YOU LOST", width / 2, height / 3);
}
}
fill(255);
textSize(25);
text("Press ENTER to restart", 230, 200);
if (keyCode == ENTER) {
gameState = "end";
}
}
}