board_painter.dart 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:gobang/models/position.dart';
  3. import 'package:gobang/utils/constants.dart';
  4. /// 棋盘 + 棋子绘制
  5. class BoardPainter extends CustomPainter {
  6. BoardPainter({required this.pieces, required this.version});
  7. final List<Position> pieces;
  8. final int version;
  9. @override
  10. void paint(Canvas canvas, Size size) {
  11. final cell = size.width / (kBoardSize - 1);
  12. final bg = Paint()
  13. ..isAntiAlias = true
  14. ..style = PaintingStyle.fill
  15. ..color = const Color(0x77cdb175);
  16. canvas.drawRect(Offset.zero & size, bg);
  17. final line = Paint()
  18. ..style = PaintingStyle.stroke
  19. ..color = CupertinoColors.systemGrey6
  20. ..strokeWidth = 1;
  21. for (var i = 0; i < kBoardSize; i++) {
  22. final o = cell * i;
  23. canvas.drawLine(Offset(0, o), Offset(size.width, o), line);
  24. canvas.drawLine(Offset(o, 0), Offset(o, size.height), line);
  25. }
  26. final radius = cell / 2 - 2;
  27. final fill = Paint()..style = PaintingStyle.fill;
  28. for (final p in pieces) {
  29. fill.color = p.chess.color;
  30. final center = Offset(p.dx, p.dy);
  31. if (p.chessShape.shape == 1) {
  32. canvas.drawCircle(center, radius, fill);
  33. } else {
  34. canvas.drawRect(
  35. Rect.fromCircle(center: center, radius: radius),
  36. fill,
  37. );
  38. }
  39. }
  40. }
  41. @override
  42. bool shouldRepaint(covariant BoardPainter oldDelegate) {
  43. return oldDelegate.version != version;
  44. }
  45. }