Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
1
Indexable
Never
// Definicja stałych
const GAME_WIDTH = 800;
const GAME_HEIGHT = 600;
const CHICKEN_WIDTH = 60;
const CHICKEN_HEIGHT = 60;
const EGG_WIDTH = 20;
const EGG_HEIGHT = 20;
const COCK_WIDTH = 80;
const COCK_HEIGHT = 80;

// Inicjalizacja canvasa
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = GAME_WIDTH;
canvas.height = GAME_HEIGHT;
document.body.appendChild(canvas);

// Definicja obiektów
let chicken = {
  x: GAME_WIDTH / 2 - CHICKEN_WIDTH / 2,
  y: GAME_HEIGHT - CHICKEN_HEIGHT - 10,
  width: CHICKEN_WIDTH,
  height: CHICKEN_HEIGHT,
  speed: 5,
};

let eggs = [];
let cock = {
  x: Math.random() * (GAME_WIDTH - COCK_WIDTH),
  y: 0,
  width: COCK_WIDTH,
  height: COCK_HEIGHT,
  speed: 3,
};

// Funkcja do rysowania obiektów
function drawRect(x, y, width, height, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x, y, width, height);
}

// Funkcja do rysowania obrazów
function drawImage(img, x, y, width, height) {
  ctx.drawImage(img, x, y, width, height);
}

// Funkcja do rysowania jajek
function drawEggs() {
  for (let i = 0; i < eggs.length; i++) {
    drawRect(eggs[i].x, eggs[i].y, EGG_WIDTH, EGG_HEIGHT, "#FFFFFF");
  }
}

// Funkcja do rysowania koguta
function drawCock() {
  drawImage(
    cockImg,
    cock.x,
    cock.y,
    cock.width,
    cock.height
  );
}

// Funkcja do rysowania kurczaka
function drawChicken() {
  drawImage(
    chickenImg,
    chicken.x,
    chicken.y,
    chicken.width,
    chicken.height
  );
}

// Funkcja do sprawdzania kolizji
function checkCollision(rect1, rect2) {
  let xOverlap =
    Math.abs(rect1.x + rect1.width / 2 - (rect2.x + rect2.width / 2)) <
    rect1.width / 2 +
      rect2.width / 2;
  let yOverlap =
    Math.abs(rect1.y + rect1.height / 2 - (rect2.y + rect2.height / 2)) <
    rect1.height / 2 +
      rect2.height / 2;
  return xOverlap && yOverlap;
}

// Funkcja do aktualizowania pozycji jajek
function updateEggs() {
  for (let i = 0; i < eggs.length; i++) {
    eggs[i].y -= 5;
    if (eggs[i].y < 0) {
      eggs.splice(i, 1);
      i--;
    } else if (checkCollision(eggs[i