xxxxxxxxxx
124
let dino;
let obstacles = [];
let score = 0;
let gameSpeed = 6;
function setup() {
createCanvas(600, 400);
dino = new Dino();
}
function draw() {
background(255);
// Display the score
textSize(20);
text("Score: " + score, 500, 30);
// Generate obstacles randomly
if (frameCount % 60 === 0) {
obstacles.push(new Obstacle());
}
// Update and display the obstacles
for (let i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].update();
obstacles[i].show();
// If the obstacle hits the dino, end the game
if (obstacles[i].hits(dino)) {
console.log("Game over!");
noLoop();
}
// Remove the obstacle from the array if it's off screen
if (obstacles[i].offscreen()) {
obstacles.splice(i, 1);
score++;
}
}
// Update and display the dino
dino.update();
dino.show();
}
function keyPressed() {
// Jump when space key is pressed
if (key === " " && dino.isOnGround()) {
dino.jump();
}
}
// Define the Obstacle constructor function
function Obstacle() {
this.width = 20;
this.height = 50;
this.x = width;
this.y = height - this.height;
this.velocity = gameSpeed;
// Update the obstacle's position
this.update = function() {
this.x -= this.velocity;
}
// Display the obstacle on the screen
this.show = function() {
fill(0);
rect(this.x, this.y, this.width, this.height);
}
// Check if the obstacle hits the dino
this.hits = function(dino) {
return collideRectRect(this.x, this.y, this.width, this.height,
dino.x, dino.y, dino.width, dino.height);
}
// Check if the obstacle is off screen
this.offscreen = function() {
return this.x < -this.width;
}
}
// Define the Dino constructor function
function Dino() {
this.x = 50;
this.y = height - 50;
this.width = 40;
this.height = 50;
this.velocity = 0;
this.gravity = 0.6;
// Check if the dino is on the ground
this.isOnGround = function() {
return this.y === height - this.height;
}
// Jump when space key is pressed
this.jump = function() {
if (this.isOnGround()) {
this.velocity = -15;
}
}
// Update the dino's position and velocity
this.update = function() {
this.velocity += this.gravity;
this.y += this.velocity;
// Keep the dino on the ground
if (this.y > height - this.height) {
this.y = height - this.height;
this.velocity = 0;
}
}
// Display the dino on the screen
this.show = function() {
fill(0);
rect(this.x, this.y, this.width, this.height);
}
}