Search code examples
javadatabasehibernatedatabase-designplaying-cards

How to design a database for a game with cards and decks


I'm creating a Java-based server for a card game where clients can connect to make their "plays". Each "Game" (Java-class) holds a deck of 104 cards (a normal deck times two). So the basic classes I got are: Game, Deck, Card. A Game will have one Deck, a Deck will have 104 Cards at the most. I've made the base structure for the server with Hibernate and a PostgreSQL database. My issue here is how to model the database.

As there are only 52 different Cards there is no point in making 52 Cards for each Deck in a "Deck"-table. However, the decks need to be shuffled. I guess there's some smart way of doing this, but database modelling is not my strong suit.

At the top of my head I'd figure I could have one table "Cards" with 52 rows, one row for each Card. Then another table "Deck" that will create a row each time a Game is created and that holds a list of numbers (104 numbers) which refers to each Card's ID twice in the Card-table. Does that even sound like a good idea? And how do I accomplish this with Java and Hibernate?

Or is there some other way this should be done? As there are many card games, I'd guess this has been done a million times before and that there's some best practices in resolving this, but I've not been able to find it. I'd appreciate any input on the matter. In advance, thanks!

EDIT: Am I overthinking the problem and should just insert a Deck to the database using Hibernate and let the database take care of the rest?


Solution

  • I dont see a point in storing cards in the database, it would just make things too complex. What I would do is just to create another Class in the java application named like CardDistribution, containing an array of 102 elements. Give each element an id of the card it holds.

    When you want to save the game, serialize your CardDistribution object into JSON and persist it in a column in your Game table.

    And when you read from the database just de-serialize your CardDistribution JSON into a java object and use it.