Skip to content

Instantly share code, notes, and snippets.

@BoHellgren
Last active April 17, 2023 02:05
Show Gist options
  • Save BoHellgren/21ac6e40d57a9e0ca458f4f9482d1870 to your computer and use it in GitHub Desktop.
Save BoHellgren/21ac6e40d57a9e0ca458f4f9482d1870 to your computer and use it in GitHub Desktop.
Game main.dart final version
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flame/components/component.dart';
import 'package:flame/sprite.dart';
import 'package:flame/flame.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:firebase_admob/firebase_admob.dart';
// Create the following file with this command: flutter pub run flappy_translator
import 'i18n.dart';
import 'gameclasses.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: TextTheme(
body1: TextStyle(
fontSize: 16.0,
color: Colors.black,
backgroundColor: Colors.white),
)),
localizationsDelegates: [
const I18nDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: I18nDelegate.supportedLocals,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
MyGame _myGame;
bool _gameInProgress = false;
int _level;
SharedPreferences _prefs;
bool _showMessages = false;
String levelText, resultText, gameOverText, wellDoneText;
@override
void initState() {
super.initState();
FirebaseAdMob.instance
.initialize(appId: 'ca-app-pub-dddddddddddddddd~dddddddddd');
MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
testDevices: <String>["637A4D56EC1A28C5F00BEE979DE04922"],
);
BannerAd myBanner = BannerAd(
adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx',
// adUnitId: 'ca-app-pub-3940256099942544/6300978111', // Test unit
size: AdSize.largeBanner,
targetingInfo: targetingInfo,
);
myBanner
..load()
..show(
anchorOffset: 0.0,
horizontalCenterOffset: 0.0,
anchorType: AnchorType.bottom,
);
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
//title: Text('Kill the gnats!'),
title: Text(I18n.appTitle),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
color: Colors.white,
height: 30.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_level == null
? FutureBuilder<SharedPreferences>(
future: SharedPreferences.getInstance(),
builder: (BuildContext context,
AsyncSnapshot<SharedPreferences> snapshot) {
if (snapshot.hasData) {
_prefs = snapshot.data;
_level = _prefs.getInt('level') ?? 1;
// return Text('Your current level is '
return Text(I18n.currentLevel(
lev: _level, gnats: 2 * _level + 2));
} else
return Text('wait');
})
: Text(I18n.currentLevel(
lev: _level, gnats: 2 * _level + 2)),
FlatButton(
color: Colors.white,
textColor: Colors.white,
padding: EdgeInsets.all(0.0),
onPressed: () {
_level = 1;
_prefs.setInt('level', 1);
setState(() {});
},
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Text(
" Reset ",
style: TextStyle(
fontSize: 18.0, backgroundColor: Colors.red[400]),
),
),
)
],
),
),
Expanded(
child: Stack(
children: [
Container(
color: Colors.lightBlue[100],
child: _myGame == null
// Text('Tap the button to let in the gnats!',
? Text(I18n.instruction, // Tap the button to let in the gnats
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
))
: _myGame.widget,
),
_showMessages
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(gameOverText,
style: TextStyle(
fontSize: 50.0,
color: Colors.red,
fontStyle: FontStyle.italic),
),
Text(resultText), // You killed 3 knats in 5 seconds
Text(levelText), // You advance to level 4 or You stay on level 3
],
))
: Container(),
],
)),
Container(
height: 100.0, // For largeBanner ads
)
],
),
),
floatingActionButton: Padding(
padding: const EdgeInsets.only(bottom: 100.0),
child: FloatingActionButton(
onPressed: () => _newGame(),
child: Icon(Icons.add),
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _newGame() async {
if (_gameInProgress) return; // Only allow one game at a time
_gameInProgress = true;
AudioPlayer _audioPlayer =
await Flame.audio.playLongAudio('188708__zywx__flying-mosquito.wav');
_myGame = new MyGame(); // This kills the remaining gnats but not the timer
MyGame.kills = 0;
_level = _prefs.getInt('level') ?? 1;
MyGame.target = 2 * _level + 2;
Sprite sprite = await Sprite.loadSprite('gnat.png');
for (int i = 0; i < MyGame.target; i++) {
SpriteComponent gnat = Gnat(sprite);
_myGame.add(gnat);
}
setState(() {
_showMessages = false;
});
int seconds;
for (seconds = 0; seconds < 10; seconds++) {
print('seconds $seconds');
await Future.delayed(const Duration(seconds: 1), () {});
if (MyGame.kills == MyGame.target) break;
}
_gameInProgress = false;
if (MyGame.kills == MyGame.target) {
_level++;
_prefs.setInt('level', _level);
// gameOverText = 'Well Done';
gameOverText = I18n.wellDoneText;
// resultText = 'You killed ${MyGame.target} gnats in $seconds seconds';
resultText = I18n.resultTextGood(gnats: MyGame.target, sec: seconds);
// levelText = 'You advance to level $_level.';
levelText = I18n.levelTextAdvance(lev: _level);
Flame.audio.play('397354__plasterbrain__tada-fanfare-f.flac');
_audioPlayer.stop(); // Stop the background sound
} else {
// gameOverText = 'Game Over!';
gameOverText = I18n.gameOverText;
// resultText = 'You only killed ${MyGame.kills} gnats.';
resultText = I18n.resultTextBad(gnats: MyGame.kills);
// levelText = 'You stay on level $_level.';
levelText = I18n.levelTextStay(lev: _level);
Flame.audio.play('350984__cabled-mess__lose-c-03.wav');
}
setState(() {
_showMessages = true;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment