質問

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?

役に立ちましたか?

解決

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.

他のヒント

One critical thing about RDBMSs in general (and basically every JPA provider will complain if you don't), is that you usually want to have some sort of unique-key for a table (even if it ends up being every column).
Additionally, SQL has a 'guarantee', that if no order is explicitly requested, the returned rows will be 'random' (this is to allow optimizers to take whatever shortcuts they can, which means the ordering might change unexpectedly).

With this in mind, Deck is probably best setup as:

Deck
-----------------
gameId  -- fk reference to Game.id
cardId  -- fk reference to Card.id
deckOrder  -- order of card in deck for this game

The entire row comprises the unique key.

As for adding the rows to the deck... you may find it easiest (and 'correctly random') to add all cards to an array and shuffle it in Java - randomly ordering something is quite difficult.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top