match_magic/lib/game/match_magic_game.dart

102 lines
2.9 KiB
Dart
Raw Normal View History

2024-08-02 10:53:40 +00:00
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
2024-08-13 14:50:11 +00:00
import 'package:match_magic/game/sprite_loader.dart';
2024-08-05 08:04:54 +00:00
import 'package:provider/provider.dart';
import 'board.dart';
import 'swap_notifier.dart';
2024-08-02 10:53:40 +00:00
2024-08-13 14:50:11 +00:00
class MatchMagicGameScreen extends StatefulWidget {
const MatchMagicGameScreen({Key? key}) : super(key: key);
@override
_MatchMagicGameScreenState createState() => _MatchMagicGameScreenState();
}
class _MatchMagicGameScreenState extends State<MatchMagicGameScreen> {
late Future<List<Sprite>> _spritesFuture;
Board? board;
@override
void initState() {
super.initState();
_spritesFuture = SpriteLoader.loadSprites();
}
void _restartGame() {
context.read<SwapNotifier>().resetScore();
setState(() {
board = null;
_spritesFuture = SpriteLoader.loadSprites();
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Sprite>>(
future: _spritesFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data == null) {
return const Center(child: Text('No sprites found'));
} else {
final sprites = snapshot.data!;
board ??= Board(
sprites: sprites, swapNotifier: context.read<SwapNotifier>());
return Column(
children: [
2024-08-16 16:09:24 +00:00
SizedBox(
height: 50,
),
2024-08-13 14:50:11 +00:00
const ScoreDisplay(),
Expanded(
child: Center(
child: AspectRatio(
aspectRatio: 1,
child: GameWidget(game: board!),
),
),
),
ElevatedButton(
onPressed: _restartGame,
2024-08-16 16:09:24 +00:00
child: const Text(
'Restart',
style: TextStyle(color: Colors.black),
),
2024-08-13 14:50:11 +00:00
),
2024-08-16 16:09:24 +00:00
SizedBox(
height: 50,
)
2024-08-13 14:50:11 +00:00
],
);
}
} else {
return const Center(child: CircularProgressIndicator());
}
},
);
}
}
class ScoreDisplay extends StatelessWidget {
const ScoreDisplay({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Consumer<SwapNotifier>(
builder: (context, notifier, child) {
return Text(
'Score: ${notifier.score}',
2024-08-16 16:09:24 +00:00
style: const TextStyle(
fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white),
2024-08-13 14:50:11 +00:00
);
},
2024-08-05 08:04:54 +00:00
),
);
2024-08-02 10:53:40 +00:00
}
}