How to load images in editorP5JS

let cards = [];
let flipped = [ ];
let moves = 0;
let cardSize;

// Preload images
preload = () => {
  cards.push(loadImage("C:\Users\stark\OneDrive\Pictures\Screenshots\hanuman.png")); // Replace with your uploaded image link
  cards.push(loadImage("C:\Users\stark\OneDrive\Pictures\Screenshots\jalebi.png")); // Replace with your uploaded image link
  cards.push(loadImage("C:\Users\stark\OneDrive\Pictures\Screenshots\ladoo.png")); // Replace with your uploaded image link
  cards.push(loadImage("C:\Users\stark\OneDrive\Pictures\Screenshots\TrollFace.png")); // Replace with your uploaded image link
};

// Calculate card size based on the canvas dimensions
function setup(
) {
  let canvasWidth = 400;
  let canvasHeight = 400;
  cardSize = (canvasWidth / 2) - 2;

  createCanvas(canvasWidth, canvasHeight);
  for (let i = 0; i < 4; i++) {
    flipped[i] = false;
  }
  for (let i = 0; i < 4; i++) {
    let x = map(i % 2, 0, 1, 0, canvasWidth);
    let y = map(floor(i / 2), 0, 1, 0, canvasHeight);
    let card = createButton(x, y);
    card.mousePressed(flipCard);
  }
}

// Flip a card
function flipCard(
) {
  let pos = mouseX / cardSize;
  if (floor(pos) < 2 && floor(mouseY / cardSize) < 2) {
    let index = int(pos) + int(floor(mouseY / cardSize)) * 2;
    if (!flipped[index]) {
      flipped[index] = true;
      moves++;
    }
  }
}

// Check if game is finished
function checkWin(
) {
  let cardPairs = 0;
  for (let i = 0; i < flipped.length; i++) {
    if (flipped[i]) {
      let j = i + 1;
      while (j < flipped.length) {
        if (flipped[j] && cards[i] === cards[j]) {
          cardPairs++;
          flipped[j] = false;
          break;
        }
        j++;
      }
    }
  }
  return cardPairs === 2;
}

// Draw cards and display number of moves
function draw(
) {
  background(51);
  for (let i = 0; i < 4; i++) {
    let x = map(i % 2, 0, 1, 0, width);
    let y = map(floor(i / 2), 0, 1, 0, height);
    image(cards[i], x, y, cardSize, cardSize);
  }
  text(`Moves: ${moves}`, 20, height - 20);
  if (checkWin()) {
    background(200, 255, 200);
  }
}

Whats it doing that it shouldnt be, or not doing that it should be? Are there errors in your console?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.