xxxxxxxxxx
135
//divides the screen into rows and columns
let NUM_ROWS = 10;
let NUM_COLS = 10;
let TILE_WIDTH;
let TILE_HEIGHT;
let SCORE = 0;
let SCREEN = 0; //to show sucessive different screens
let basket;
let elements = [];
function setup() {
createCanvas(500, 500);
TILE_WIDTH = width / NUM_COLS;
TILE_HEIGHT = height / NUM_ROWS;
basket = new Basket();
}
function draw() {
background(255);
if (SCREEN === 0) {
// Start Screen
fill(0);
textSize(32);
textAlign(CENTER, CENTER);
text("Press Enter to Start", width / 2, height / 2); }
else if (SCREEN === 1) {
// Game Screen
basket.display();
// Display falling elements
for (let element of elements) {
element.display();
}
fill(0);
textSize(24);
text("Score: " + SCORE, width - 100, 30);
}
}
//temporarily in the same file
class Basket {
constructor() {
this.col_num = floor(NUM_COLS / 2); //initial position of the basket in the middle col
this.x = this.col_num * TILE_WIDTH - 15; //centering
this.y = (NUM_ROWS - 1) * TILE_HEIGHT; //bottom row
this.w = TILE_WIDTH + 20; //width of the basket
this.h = TILE_HEIGHT + 20; //height of the basket
this.speed = 5; //speed of the basket
}
display() {
this.update();
noStroke();
fill('#D7B078');
rect(this.x, this.y, this.w, this.h,4);
}
update() {
//smoothly move basket towards the center of the adjacent column
let targetX = this.col_num * TILE_WIDTH - 15;
if (this.x < targetX) {
this.x += this.speed; // Move right
} else if (this.x > targetX) {
this.x -= this.speed; // Move left
}
}
//move the basket to the adjacent left column
moveLeft() {
this.col_num = constrain(this.col_num - 1, 0, NUM_COLS - 1);
}
//move the basket to the adjacent right column
moveRight() {
this.col_num = constrain(this.col_num + 1, 0, NUM_COLS - 1);
}
}
//falling elements
class Element {
constructor() {
this.w = TILE_WIDTH - 10;
this.h = TILE_HEIGHT - 10;
this.col_num = floor(random(0, NUM_COLS)); //chooses random column to fall from
this.x = this.col_num * TILE_WIDTH;
this.y = -TILE_HEIGHT;
this.speed = 5; // Speed of the falling element (adjustable)
}
display() {
this.update();
fill('rgb(239,150,165)');
ellipse(this.x + this.w / 2, this.y + this.h / 2, this.w, this.h);
}
update() {
this.y += this.speed; //move the element down
this.catch(); //check if the element is caught by the basket
if (this.y > height) {
this.respawn(); //respawn the element at the top if it goes off-screen
}
}
//collision detection
catch() {
if (this.x - 15 === basket.x && this.y + this.h === basket.y) {
SCORE++;
this.respawn(); // Respawn the element after catching
}
}
respawn() {
this.col_num = floor(random(0, NUM_COLS));
this.x = this.col_num * TILE_WIDTH;
this.y = -TILE_HEIGHT;
}
}
function keyPressed() {
if (keyCode === ENTER) { //start game
if (SCREEN === 0) {
SCREEN = 1;
elements.push(new Element()); }
}
else if (keyCode === LEFT_ARROW) {
basket.moveLeft(); }
else if (keyCode === RIGHT_ARROW) {
basket.moveRight(); }
}