I am trying to make a card matching game. But I don’t know how I can matching than when they are correct. Maybe I can let the first card and second card . But I don’t really know how to do it.
Link: p5.js Web Editor
let images = [];
let visibleImages = new Array(16);
let x = 0;
function preload() {
for (let j = 0; j < 8; j++) {
let img = loadImage(j + 1 + ".jpg");
images.push(img);
images.push(img);
}
}
function mouseClicked() {
let cx = floor(mouseX / (width / 4));
let cy = floor(mouseY / (height / 4));
let imgIndex = cy * 4 + cx;
visibleImages[imgIndex] = true;
}
function setup() {
createCanvas(400, 400);
visibleImages.fill(false);
shuffle(images, true);
}
function draw() {
background(255);
for (let j = 0; j < 4; j++) {
for (let i = 0; i < 4; i++) {
square((i * 400) / 4, (j * 400) / 4, 400 / 4);
let imgIndex = j * 4 + i;
if (visibleImages[imgIndex] == true) {
image(images[imgIndex], (i * 400) / 4, (j * 400) / 4, 400 / 4, 400 / 4);
}
}
}
}
Instead of using a class:
You also could load the image names into a String grid first.
Shuffle the string grid.
Load then the images into a second image grid (the one you already have)
Now you have the string names and can compare the names easily (numbers at start of String) to find out whether the 2 images match
next step
Have a counter for the mouse clicks. When it’s ==2 then compare the 2 open images, then reset. Thus you can distinguish between first and second mouse click.
remark
Also draw an image for images that are not open (the backside of each card), the same image for every card.
After loading the names (after the for loop), first shuffle them.
Then load the images using the names (in a new for loop in setup()). Since the names are with duplicates you don’t load each image twice but just once
Thus we make sure that the two grids are parallel in the sense that the image name and its image are in the same cell of the grid. Only then can we do a comparison using the String name
Remember when comparing Strings later you can’t use == ; use s1.equals(s2) instead