Scratch And Win
Main.dart
import 'package:flutter/material.dart';
import 'HomePage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scratch and Win',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.pink,
),
home: HomePage(),
);
}
}
HomePage.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// import images
AssetImage circle = AssetImage('images/circle.png');
AssetImage lucky = AssetImage('images/rupee.png');
AssetImage unlucky = AssetImage('images/sadFace.png');
// get an array
List<String> itemArray = [];
int luckyNumber = 0;
// initialize array with 25 element
@override
void initState() {
super.initState();
itemArray = List<String>.generate(25, (index) => 'empty');
generateRandomNumber();
}
generateRandomNumber() {
int rnd = Random().nextInt(25);
setState(() {
luckyNumber = rnd;
});
}
// define a getimage method
AssetImage getImage(int index) {
String currState = itemArray[index];
switch (currState) {
case 'lucky':
return lucky;
break;
case 'unlucky':
return unlucky;
break;
}
return circle;
}
// play game method
playGame(int index) {
if (luckyNumber == index) {
setState(() {
itemArray[index] = 'lucky';
});
} else {
setState(() {
itemArray[index] = 'unlucky';
});
}
}
// show all method
showAll() {
setState(() {
itemArray = List<String>.filled(25, 'unlucky');
itemArray[luckyNumber] = 'lucky';
});
}
// reset game
resetGame() {
setState(() {
itemArray = List<String>.filled(25, 'empty');
});
generateRandomNumber();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Scratch & Win'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: GridView.builder(
padding: EdgeInsets.all(20.0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
childAspectRatio: 1.0,
crossAxisCount: 5,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
),
itemCount: itemArray.length,
itemBuilder: (context, i) => SizedBox(
width: 50.0,
height: 50.0,
child: RaisedButton(
onPressed: () {
this.playGame(i);
},
child: Image(
image: this.getImage(i),
),
),
),
),
),
Container(
margin: EdgeInsets.all(15.0),
child: RaisedButton(
onPressed: () {
this.showAll();
},
color: Colors.pink,
padding: EdgeInsets.all(20.0),
child: Text(
'SHOW ALL',
style: TextStyle(color: Colors.white, fontSize: 15.0),
),
),
),
Container(
margin: EdgeInsets.all(15.0),
child: RaisedButton(
onPressed: () {
this.resetGame();
},
color: Colors.pink,
padding: EdgeInsets.all(20.0),
child: Text(
'RESET',
style: TextStyle(color: Colors.white, fontSize: 15.0),
),
),
),
],
),
);
}
}
OUTPUT
Comments
Post a Comment