Why use class for memory card game

Hi,

I’m making a memory game. People are telling me to use a class for the cards, because it would be more efficient.

Can someone explain me why?

1 Like

It would be useful to see your code for this.

use a class for the cards: The class represents ONE card. Now you can have an array of that class.

But let’s say you got 16 Cards.

Each card has a position x,y, size, image p and its partner int pair.

Alternative 1

You could hardcode it all:

int x0;
int x1;
... (=16 lines)
int y0;
int y1;
....(+16 lines)
...

and so on.

Approx. 80 lines. Far too many. Bad.

Alternative 2

OR you go for arrays which are parallel:

  • Card 0 has its data in x[0], y[0], size[0], images[0], etc.
  • Card 1 has its data in x[1], y[1], size[1] etc.
  • etc.

Confusing.

With a class

With a class you see ONE card and inside it are all this properties and also its functions like display(), mouseOver() etc.

So you have one package that contains everything for a Card. Very good.

Now you can have an array of that class:

Card cards = new Card[16];

You can treat everything in for-loops now

for(Card card : cards) {
     card.display();
}

Very nice.

A change for all cards now has to be made only once inside the class. Very nice.

See tutorial objects for more: https://www.processing.org/tutorials/objects/

Chrisir

3 Likes

An object or class is a tool in programming that allows you to create instances of items that share and use similar code.

So you can create a class of shapes or buttons, define the code that handles the position, shape, logic, etc in the class, and create new instances using the constructor. The constructor will allow you to set the variables you want for each item, ie position.

Essentially its just a time saving method, if you only need one button for example then there us no need to create a class or object, however if you are going to be using 100s of buttons then by using a class you do not need to code 100 buttons and 100 pieces of logic for said buttons, everything is done once, then you can store your buttons in an array and simply call your button draw and logic in a for loop

2 Likes
3 Likes

Trust me, objects are much better.

It’s an old well established tool / concept / paradigm used everywhere. Not only for Memory Game.

You are lost without it.

1 Like