@@ -30,6 +30,7 @@ class _SnakeGameState extends State<SnakeGame> {
30
30
@override
31
31
void initState () {
32
32
WidgetsBinding .instance.addPostFrameCallback ((_) {
33
+ _updateGridDimensions ();
33
34
showGameStartDialog (context);
34
35
});
35
36
resetGame ();
@@ -413,10 +414,7 @@ class _SnakeGameState extends State<SnakeGame> {
413
414
break ;
414
415
}
415
416
416
- if (nextHead >= 0 &&
417
- nextHead < squaresPerRow * squaresPerCol &&
418
- ! snake.contains (nextHead) &&
419
- ! visited.contains (nextHead)) {
417
+ if (nextHead >= 0 && nextHead < squaresPerRow * squaresPerCol && ! snake.contains (nextHead) && ! visited.contains (nextHead)) {
420
418
visited.add (nextHead);
421
419
queue.add (nextHead);
422
420
previousMove[nextHead] = direction;
@@ -572,34 +570,33 @@ class _SnakeGameState extends State<SnakeGame> {
572
570
573
571
// 根据屏幕尺寸动态设置网格的维度,保证充满整个屏幕
574
572
void _updateGridDimensions () {
575
- final double screenWidth = MediaQuery .of (context).size.width;
576
- final double screenHeight = MediaQuery .of (context).size.height;
577
-
578
- // 设定每个方格的最小宽高
579
- const double gridSize = 22.0 ; // 每个方格的大小
573
+ setState (() {
574
+ final double screenWidth = MediaQuery .of (context).size.width;
575
+ final double screenHeight = MediaQuery .of (context).size.height;
580
576
581
- // 计算每行和每列能容纳的方格数
582
- squaresPerRow = (screenWidth / gridSize).floor ();
583
- squaresPerCol = (screenHeight / gridSize).floor ();
577
+ // 设定每个方格的最小宽高
578
+ const double gridSize = 22.0 ; // 每个方格的大小
584
579
585
- // 如果屏幕方向是横屏,调整网格方向
586
- if (screenWidth > screenHeight) {
587
- // 横屏:确保每行的方格数量多,列数少
580
+ // 计算每行和每列能容纳的方格数
588
581
squaresPerRow = (screenWidth / gridSize).floor ();
589
582
squaresPerCol = (screenHeight / gridSize).floor ();
590
- } else {
591
- // 竖屏:确保每列的方格数量多,行数少
592
- squaresPerRow = (screenWidth / gridSize).floor ();
593
- squaresPerCol = (screenHeight / gridSize).floor ();
594
- }
583
+
584
+ // 如果屏幕方向是横屏,调整网格方向
585
+ if (screenWidth > screenHeight) {
586
+ // 横屏:确保每行的方格数量多,列数少
587
+ squaresPerRow = (screenWidth / gridSize).floor ();
588
+ squaresPerCol = (screenHeight / gridSize).floor ();
589
+ } else {
590
+ // 竖屏:确保每列的方格数量多,行数少
591
+ squaresPerRow = (screenWidth / gridSize).floor ();
592
+ squaresPerCol = (screenHeight / gridSize).floor ();
593
+ }
594
+ });
595
595
}
596
596
597
597
@override
598
598
Widget build (BuildContext context) {
599
599
SystemChrome .setEnabledSystemUIMode (SystemUiMode .manual, overlays: []);
600
-
601
- _updateGridDimensions ();
602
-
603
600
return GestureDetector (
604
601
onTap: () {
605
602
if (! isPlaying) startGame ();
0 commit comments