Ad Code

Snake game by flutter

 Snake game: Created by flutter framework

Home screen


Game screen


Game's video






Code here

main.dart
import 'package:flutter/material.dart';
import 'package:snake/cover_page.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: MyCoverPage(),
);
}
}

cover_page.dart
import 'package:avatar_glow/avatar_glow.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'home_page.dart';

class MyCoverPage extends StatefulWidget {
const MyCoverPage({Key? key}) : super(key: key);

@override
State<MyCoverPage> createState() => _MyCoverPageState();
}

class _MyCoverPageState extends State<MyCoverPage> {
static var myNewFont = GoogleFonts.pressStart2p(
textStyle: const TextStyle(
color: Colors.black,
letterSpacing: 3,
));

static var myNewFontWhite = GoogleFonts.pressStart2p(
textStyle:
const TextStyle(color: Colors.white, letterSpacing: 3, fontSize: 15));

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[800],
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: Center(
child: Text(
'S N A K E',
style: myNewFontWhite,
))),
Expanded(
flex: 2,
child: AvatarGlow(
endRadius: 140,
duration: const Duration(seconds: 2),
repeat: true,
repeatPauseDuration: const Duration(seconds: 1),
startDelay: const Duration(seconds: 1),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
style: BorderStyle.none
),
),
child: CircleAvatar(
backgroundColor: Colors.grey[800],
radius: 80.0,
child: Image.asset(
'assets/images/snake.png',
fit: BoxFit.scaleDown,
color: Colors.white,
),
),
),
)),
Expanded(
child: Center(
child: Text(
'@MS HASAN',
style: myNewFontWhite,
))),

GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context) => const HomePage()));
},
child: Padding(
padding: const EdgeInsets.only(left: 30, right: 30, bottom: 60),
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.all(8.0),
color: Colors.white,
child: Text('PLAY GAME', style: myNewFont,),
),
),
),
)
],
),
);
}
}

home_page.dart
import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

import 'cover_page.dart';


class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


//snake position
static List<int> snakePosition = [45, 65, 85, 105, 125];
final int numberOfSquare = 760;
bool gameIsRunning = false;


//google fonts
static var myNewFontWhite = GoogleFonts.pressStart2p(
textStyle: const TextStyle(
letterSpacing: 3, color: Colors.white
)
);

static var myNewFont = GoogleFonts.pressStart2p(
textStyle: const TextStyle(
letterSpacing: 3, fontSize: 15
)
);

//Direction
var direction = 'down';


//Food topics
static var randomNumber = Random();
int foodPosition = randomNumber.nextInt(740);


//generate random position for food
void generateNewFood(){
foodPosition = randomNumber.nextInt(740);
}

void startGame(){
snakePosition = [45, 65, 85, 105, 125];
if(!gameIsRunning){
Timer.periodic(const Duration(milliseconds: 400), (timer) {
upDateSnake();
gameIsRunning = true;
if(gameIsOver()){
timer.cancel();
gameIsRunning = false;
showDialogBox();
}
});
}
}

bool gameIsOver(){
for(int i= 0; i < snakePosition.length; i++){
int counter = 0;
for(int j = 0; j < snakePosition.length; j++){
if(snakePosition[i] == snakePosition[j]){
counter += 1;
}
if(counter == 2){
return true;
}
}
}
return false;
}


showDialogBox(){
return showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context){
return AlertDialog(
title: Text('Game over!', style: myNewFont,),
content: Text('Play Again?', style: myNewFont,),
actions: [
ElevatedButton(
onPressed: (){
setState(() {
Navigator.push(context, MaterialPageRoute(builder: (context) => const MyCoverPage()));
});
},
child: Text('No', style: myNewFont,)
),
ElevatedButton(
onPressed: (){
startGame();
Navigator.of(context).pop();
},
child: Text('Yse', style: myNewFont,)
),
],
);
}
);
}

void upDateSnake(){
setState(() {
switch(direction){
case 'down':
if(snakePosition.last > 740){
snakePosition.add(snakePosition.last + 20 - 760);
}else{
snakePosition.add(snakePosition.last + 20);
}
break;

case 'up':
if(snakePosition.last < 20){
snakePosition.add(snakePosition.last - 20 + 760);
}else{
snakePosition.add(snakePosition.last - 20);
}
break;
case 'left':
if(snakePosition.last % 20 == 0){
snakePosition.add(snakePosition.last - 1 + 20);
}else{
snakePosition.add(snakePosition.last - 1);
}
break;

case 'right':
if((snakePosition.last + 1) % 20 == 0){
snakePosition.add(snakePosition.last + 1 - 20);
}else{
snakePosition.add(snakePosition.last + 1);
}
break;

default:

}

if(snakePosition.last == foodPosition){
generateNewFood();
}else{
snakePosition.removeAt(0);
}
});
}



@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[800],
body: Column(
children: [
Expanded(
child: GestureDetector(
onVerticalDragUpdate: (update){
setState(() {
if(direction != 'up' && update.delta.dy > 0){
direction = 'down';
}else if(direction != 'down' && update.delta.dy < 0){
direction = 'up';
}
});
},
onHorizontalDragUpdate: (update){
setState(() {
if(direction != 'left' && update.delta.dx > 0){
direction = 'right';
}else if(direction != 'right' && update.delta.dx < 0){
direction = 'left';
}
});
},
child: GridView.builder(
physics: const NeverScrollableScrollPhysics(),
itemCount: numberOfSquare,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 20),
itemBuilder: (BuildContext context, int index) {

if (foodPosition == index){
return Center(
child: Padding(
padding: const EdgeInsets.all(2.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(5),
child: Container(
color: Colors.yellow,
),
),
),
);
}
if (snakePosition.contains(index)) {
return Center(
child: Padding(
padding: const EdgeInsets.all(2.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(5),
child: Container(
color: Colors.white,
),
),
),
);
}
return Center(
child: Padding(
padding: const EdgeInsets.all(2.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(5),
child: Container(
color: Colors.grey[700],
),
),
),
);
}),
),
),

Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text('Score ${snakePosition.length -5}', style: myNewFont,),
),

Padding(
padding: const EdgeInsets.only(left: 10, right: 10, bottom: 30.0, top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onTap: (){
setState(() {
if(!gameIsRunning){
startGame();
}
});
},
child: Text('START' , style: myNewFontWhite,),
),
Text('@MS HASAN', style: myNewFontWhite,),
],
),
),
],
),
);
}
}


Post a Comment

0 Comments