Skip to content

Commit a69a472

Browse files
🎨 added game activity
1 parent 022a9ca commit a69a472

File tree

6 files changed

+225
-4
lines changed

6 files changed

+225
-4
lines changed

assets/snake_game.jpg

34.7 KB
Loading

lib/game_over.dart

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import 'package:flutter/material.dart';
2+
3+
class GameOver extends StatelessWidget {
4+
5+
final int score;
6+
7+
GameOver({
8+
this.score
9+
});
10+
11+
@override
12+
Widget build(BuildContext context) {
13+
return Scaffold(
14+
body: Center(
15+
child: Text('Game over, score: $score'),
16+
),
17+
);
18+
}
19+
}

lib/game_page.dart

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import 'dart:async';
2+
import 'dart:math';
3+
4+
import 'package:SnakeGameFlutter/game_over.dart';
5+
import 'package:flutter/material.dart';
6+
7+
class GamePage extends StatefulWidget {
8+
@override
9+
_GamePageState createState() => _GamePageState();
10+
}
11+
12+
class _GamePageState extends State<GamePage> with TickerProviderStateMixin {
13+
14+
int _playerScore;
15+
bool _hasStarted;
16+
Animation _snakeAnimation;
17+
AnimationController _snakeController;
18+
List _snake = [404, 405, 406, 407];
19+
final int _noOfSquares = 500;
20+
final Duration _duration = Duration(milliseconds: 250);
21+
final int _squareSize = 20;
22+
String _currentSnakeDirection;
23+
int _snakeFoodPosition;
24+
Random _random = new Random();
25+
26+
@override
27+
void initState() {
28+
super.initState();
29+
_setUpGame();
30+
}
31+
32+
void _setUpGame() {
33+
_playerScore = 0;
34+
_currentSnakeDirection = 'RIGHT';
35+
_hasStarted = true;
36+
do {
37+
_snakeFoodPosition = _random.nextInt(_noOfSquares);
38+
} while(_snake.contains(_snakeFoodPosition));
39+
_snakeController = AnimationController(vsync: this, duration: _duration);
40+
_snakeAnimation = CurvedAnimation(curve: Curves.easeInOut, parent: _snakeController);
41+
}
42+
43+
void _gameStart() {
44+
Timer.periodic(Duration(milliseconds: 250), (Timer timer) {
45+
_updateSnake();
46+
if(_hasStarted) timer.cancel();
47+
});
48+
}
49+
50+
bool _gameOver() {
51+
for (int i = 0; i < _snake.length - 1; i++) if (_snake.last == _snake[i]) return true;
52+
return false;
53+
}
54+
55+
void _updateSnake() {
56+
if(!_hasStarted) {
57+
setState(() {
58+
_playerScore = (_snake.length - 4) * 100;
59+
switch (_currentSnakeDirection) {
60+
case 'DOWN':
61+
if (_snake.last > _noOfSquares) _snake.add(_snake.last + _squareSize - (_noOfSquares + _squareSize));
62+
else _snake.add(_snake.last + _squareSize);
63+
break;
64+
case 'UP':
65+
if (_snake.last < _squareSize) _snake.add(_snake.last - _squareSize + (_noOfSquares + _squareSize));
66+
else _snake.add(_snake.last - _squareSize);
67+
break;
68+
case 'RIGHT':
69+
if ((_snake.last + 1) % _squareSize == 0) _snake.add(_snake.last + 1 - _squareSize);
70+
else _snake.add(_snake.last + 1);
71+
break;
72+
case 'LEFT':
73+
if ((_snake.last) % _squareSize == 0) _snake.add(_snake.last - 1 + _squareSize);
74+
else _snake.add(_snake.last - 1);
75+
}
76+
77+
if (_snake.last != _snakeFoodPosition) _snake.removeAt(0);
78+
else {
79+
do {
80+
_snakeFoodPosition = _random.nextInt(_noOfSquares);
81+
} while (_snake.contains(_snakeFoodPosition));
82+
}
83+
84+
if (_gameOver()) {
85+
setState(() {
86+
_hasStarted = !_hasStarted;
87+
});
88+
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => GameOver(score: _playerScore)));
89+
}
90+
});
91+
}
92+
}
93+
94+
@override
95+
Widget build(BuildContext context) {
96+
return Scaffold(
97+
appBar: AppBar(
98+
title: Text('SnakeGameFlutter', style: TextStyle(color: Colors.white, fontSize: 20.0)),
99+
centerTitle: false,
100+
backgroundColor: Colors.redAccent,
101+
actions: <Widget>[
102+
Center(
103+
child: Padding(
104+
padding: const EdgeInsets.symmetric(horizontal: 20.0),
105+
child: Text('Score: $_playerScore', style: TextStyle(fontSize: 16.0)),
106+
)
107+
)
108+
],
109+
),
110+
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
111+
floatingActionButton: FloatingActionButton.extended(
112+
backgroundColor: Colors.redAccent,
113+
elevation: 20,
114+
label: Text(
115+
_hasStarted ? 'Start' : 'Pause',
116+
style: TextStyle(),
117+
),
118+
onPressed: () {
119+
setState(() {
120+
if(_hasStarted) _snakeController.forward();
121+
else _snakeController.reverse();
122+
_hasStarted = !_hasStarted;
123+
_gameStart();
124+
});
125+
},
126+
icon: AnimatedIcon(icon: AnimatedIcons.play_pause, progress: _snakeAnimation)
127+
),
128+
body: Center(
129+
child: GestureDetector(
130+
onVerticalDragUpdate: (drag) {
131+
if (drag.delta.dy > 0 && _currentSnakeDirection != 'UP') _currentSnakeDirection = 'DOWN';
132+
else if (drag.delta.dy < 0 && _currentSnakeDirection != 'DOWN') _currentSnakeDirection = 'UP';
133+
},
134+
onHorizontalDragUpdate: (drag) {
135+
if (drag.delta.dx > 0 && _currentSnakeDirection != 'LEFT') _currentSnakeDirection = 'RIGHT';
136+
else if (drag.delta.dx < 0 && _currentSnakeDirection != 'RIGHT') _currentSnakeDirection = 'LEFT';
137+
},
138+
child: Container(
139+
width: MediaQuery.of(context).size.width,
140+
child: GridView.builder(
141+
itemCount: _squareSize + _noOfSquares,
142+
physics: NeverScrollableScrollPhysics(),
143+
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: _squareSize),
144+
itemBuilder: (BuildContext context, int index) {
145+
return Center(
146+
child: Container(
147+
color: Colors.white,
148+
padding: _snake.contains(index) ? EdgeInsets.all(1) : EdgeInsets.all(0),
149+
child: ClipRRect(
150+
borderRadius: index == _snakeFoodPosition || index == _snake.last ? BorderRadius.circular(7) : _snake.contains(index) ? BorderRadius.circular(2.5) : BorderRadius.circular(1),
151+
child: Container(
152+
color: _snake.contains(index) ? Colors.black : index == _snakeFoodPosition ? Colors.green : Colors.blue
153+
),
154+
),
155+
),
156+
);
157+
},
158+
),
159+
),
160+
),
161+
),
162+
);
163+
}
164+
}

lib/home_page.dart

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import 'package:SnakeGameFlutter/game_page.dart';
2+
import 'package:flutter/material.dart';
3+
4+
class HomePage extends StatelessWidget {
5+
@override
6+
Widget build(BuildContext context) {
7+
return Scaffold(
8+
body: Container(
9+
width: MediaQuery.of(context).size.width,
10+
height: MediaQuery.of(context).size.height,
11+
color: Colors.blue,
12+
child: Column(
13+
crossAxisAlignment: CrossAxisAlignment.center,
14+
mainAxisAlignment: MainAxisAlignment.center,
15+
children: <Widget>[
16+
Image.asset('assets/snake_game.jpg'),
17+
18+
SizedBox(height: 50.0),
19+
20+
Text('Welcome to SnakeGameFlutter', style: TextStyle(color: Colors.white, fontSize: 40.0, fontStyle: FontStyle.italic, fontWeight: FontWeight.bold), textAlign: TextAlign.center),
21+
22+
SizedBox(height: 50.0),
23+
24+
FlatButton.icon(
25+
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 30.0),
26+
color: Colors.redAccent,
27+
onPressed: () {
28+
Navigator.of(context).push(MaterialPageRoute(builder: (context) => GamePage()));
29+
},
30+
icon: Icon(Icons.play_circle_filled, color: Colors.white, size: 30.0),
31+
label: Text("Start the Game...", style: TextStyle(color: Colors.white, fontSize: 20.0))
32+
),
33+
],
34+
),
35+
)
36+
);
37+
}
38+
}

lib/main.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import 'package:SnakeGameFlutter/game_widget.dart';
1+
import 'package:SnakeGameFlutter/home_page.dart';
22
import 'package:flutter/material.dart';
33

44
void main() {
@@ -12,7 +12,7 @@ class MyApp extends StatelessWidget {
1212
return MaterialApp(
1313
title: 'SnakeGameFlutter',
1414
debugShowCheckedModeBanner: false,
15-
// home: GameWidget(),
15+
home: HomePage(),
1616
);
1717
}
1818
}

pubspec.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ flutter:
4545
uses-material-design: true
4646

4747
# To add assets to your application, add an assets section, like this:
48-
# assets:
49-
# - images/a_dot_burr.jpeg
48+
assets:
49+
- assets/
5050
# - images/a_dot_ham.jpeg
5151

5252
# An image asset can refer to one or more resolution-specific "variants", see

0 commit comments

Comments
 (0)