직관적인 드래그 앤 드롭 상호작용, 부드러운 애니메이션 및 사용자 정의 가능한 레이아웃을 갖춘 카드 게임을 구축하기 위한 선언형 Flutter 패키지입니다. 솔리테어와 워와 같은 게임에 적합하며, 인터랙티브한 카드 메커니즘 생성을 간소화하면서 Android, iOS, Web, macOS, Windows, Linux 등 여러 플랫폼을 지원합니다. 깔끔하고 반응형 API를 통해 개발자의 생산성을 강조합니다.
사용 사례
솔리테어 스타일의 게임 만들기
멀티플레이어 카드 게임 만들기
드래그 앤 드롭 카드 메커니즘 구현
애니메이션 카드 전환 설계
크로스 플랫폼 카드 애플리케이션 개발
주요 기능
카드 컴포넌트를 위한 선언형 UI
내장 드래그 앤 드롭 지원
카드 이동을 위한 부드러운 애니메이션
유연한 레이아웃 사용자 정의
크로스 플랫폼 호환성
적합한 대상
카드 게임을 구축하는 Flutter 개발자
재사용 가능한 카드 컴포넌트를 찾는 게임 디자이너
인터랙티브 카드 인터페이스를 필요로 하는 앱
교육용 또는 캐주얼 게임 프로젝트
고려 사항
Flutter 위젯 시스템에 익숙해야 합니다
복잡한 게임 규칙을 처리하기 위해 추가 로직이 필요할 수 있습니다
성능은 렌더링된 카드 수에 따라 달라집니다
카드 기반 게임 메커니즘에 제한됨
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
card_game
A declarative Flutter package for building card games with beautiful animations. Create card games with minimal code by defining the rules and letting the package handle the rest!
A puzzle game where you move a stack of numbered disks between three columns, following the rule that larger numbers can't be placed on smaller ones.
• Custom numeric cards with CardGame<int, int> • Basic drag-and-drop with validation • maxGrabStackSize to limit moves to one card • Simple state management
A two-player card game where each player draws from their deck, and the highest card wins both cards.
• SuitedCard with deckCardStyle() • Flipped cards with CardDeck.flipped • Card value comparison with SuitedCardValueMapper • Automatic card flip animations
The classic solitaire game. Build foundation piles by suit from Ace to King, and move cards between columns following standard rules.
• Advanced card movement rules • Multiple card dragging • Complex state management • Card stacking with flipped and unflipped cards
Showcased in Production
Cards by JLogical
Cards is a full-featured card game collection built with the card_game package that demonstrates its capabilities in a production environment.
Features:
🎮 Multiple game variants: Golf Solitaire, Classic Solitaire, FreeCell
⚡ Auto-moves and smart hints
🎵 Sound effects
🎨 Customizable themes and card backs
🏆 Achievements and statistics
⏱️ Timer
📱 Fully responsive design
💾 Game saving and loading
The Cards project showcases advanced implementations including sophisticated game logic, multi-game support, persistent storage, and polished UI/UX. Check out the source code for inspiration on building your own complex card games.
Let's walk through implementing the Tower of Hanoi example, as it's the simplest game that demonstrates the core concepts:
classTowerOfHanoiextendsHookWidget{
// Number of disks to include in the gamefinalint amount;
constTowerOfHanoi({super.key, this.amount = 4});
// Initialize the game state with all disks in the first column// Each disk is represented by a number, where larger numbers represent larger disksList<List<int>> get initialCards => [
// First column contains all disks, largest (amount) to smallest (1)List.generate(amount, (i) => amount - i),
// Second and third columns start empty
<int>[],
<int>[],
];
@overrideWidgetbuild(BuildContext context) {
// Use Flutter Hooks to manage the state of our columns// Each column is a list of integers representing the disksfinal cardsState = useState(initialCards);
returnCardGame<int, int>(
// Use the built-in numeric card style to render our disks as numbers
style: numericCardStyle(),
children: [
SafeArea(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: cardsState.value
.mapIndexed((i, states) => CardColumn<int, int>(
// Each column needs a unique identifier
value: i,
// The cards (disks) currently in this column
values: states,
// Only allow moving one disk at a time
maxGrabStackSize: 1,
// Define the rules for when a disk can be placed here
canMoveCardHere: (move) {
final movingCard = move.cardValues.last;
final movingOnto = states.lastOrNull;
// Allow moves if:// 1. Column is empty (movingOnto == null)// 2. Moving disk is smaller than the top diskreturn movingOnto == null || movingCard < movingOnto;
},
// Handle the actual movement of cards between columns
onCardMovedHere: (move) {
// Create a copy of the current statefinal newCards = [...cardsState.value];
// Remove the moving card from its original column// Since maxGrabStackSize is 1, we know we're only removing one card
newCards[move.fromGroupValue].removeLast();
// Add the moved card to its new column// We use move.cardValues.first because maxGrabStackSize: 1 ensures// there's exactly one card being moved at a time
newCards[i].add(move.cardValues.first);
// Update the state, triggering a rebuild
cardsState.value = newCards;
},
))
.toList(),
),
Spacer(),
// Reset button to start the game overElevatedButton(
onPressed: () => cardsState.value = initialCards,
style: ButtonStyle(
shape: WidgetStatePropertyAll(CircleBorder())),
child: Icon(Icons.restart_alt),
),
],
),
),
],
);
}
}
This implementation shows:
Using numeric cards with the built-in numericCardStyle()
Setting up three columns using CardColumn
Implementing drag-and-drop rules with canMoveCardHere
Managing state with Flutter Hooks
Animating card movements automatically
For more complex examples, check out the implementations of the other games in the example folder.
Running the Examples
To try out the examples:
Clone the repository
Navigate to the example directory
Run flutter pub get
Run flutter run and select the example you want to try
Getting Started
Add the package to your pubspec.yaml:
dependencies:card_game:^1.0.0
Core Concepts
Card Types
The package uses two generic types:
T: The type of your cards (e.g., SuitedCard for playing cards or int for numeric cards)
G: The type for group identifiers (can be any type, often dynamic, String, or int)
Card Groups
Three types of card groups are available:
CardDeck: Shows only the top card, useful for draw piles
CardRow: Displays cards horizontally with customizable spacing
CardColumn: Displays cards vertically with customizable spacing
Card Styles
Built-in styles:
deckCardStyle(): Renders standard playing cards with a red back
numericCardStyle(): Renders numeric cards
Custom styles can be created by implementing CardGameStyle<T>.
Customization
Card Movement Rules
Control card movement with the following parameters:
CardColumn<T, G>(
// ... other params
canCardBeGrabbed: (index, card) => true, // Control which cards can be grabbed
maxGrabStackSize: 1, // Limit how many cards can be grabbed at once
canMoveCardHere: (moveDetails) => true, // Define rules for accepting cards
onCardMovedHere: (moveDetails) {}, // Handle successful moves
)
Card Interaction and Appearance
Control card interaction and visual state:
CardColumn<T, G>(
// ... other params
onCardPressed: (card) {
// Handle card press events// Useful for flipping cards, selecting cards, or triggering game actions
},
isCardFlipped: (index, card) {
// Control whether specific cards are shown face-down// Return true to show the card's back, false to show its facereturnshouldCardBeFlipped(index, card);
},
)
Common use cases:
Memory Match: Use onCardPressed to flip cards when clicked
Solitaire: Use isCardFlipped to hide cards in the tableau
War: Use isCardFlipped with CardDeck.flipped for face-down draw piles
Each card value (T) must be unique within the game
Each group value (G) must be unique within the game
Always explicitly specify type parameters for CardGroups to match the parent CardGame. For example, if you have CardGame<SuitedCard, String>, your groups should be CardColumn<SuitedCard, String>, CardRow<SuitedCard, String>, or CardDeck<SuitedCard, String>. This helps prevent type errors and makes the code more maintainable
Use flutter_hooks or your preferred state management solution
Changes to card positions and flips are automatically animated
Card states (regular, highlighted, error) are handled automatically during drag and drop by default