Skip to content
Snippets Groups Projects
Commit 39176665 authored by Benoît Harrault's avatar Benoît Harrault
Browse files

Normalize game architecture

parent 7e4ac2c5
No related branches found
No related tags found
1 merge request!13Resolve "Normalize game architecture"
Pipeline #5687 passed
Showing
with 976 additions and 418 deletions
part of 'settings_global_cubit.dart';
@immutable
class GlobalSettingsState extends Equatable {
const GlobalSettingsState({
required this.settings,
});
final GlobalSettings settings;
@override
List<dynamic> get props => <dynamic>[
settings,
];
}
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'theme_state.dart';
class ThemeCubit extends HydratedCubit<ThemeModeState> {
ThemeCubit() : super(const ThemeModeState());
void getTheme(ThemeModeState state) {
emit(state);
}
@override
ThemeModeState? fromJson(Map<String, dynamic> json) {
switch (json['themeMode']) {
case 'ThemeMode.dark':
return const ThemeModeState(themeMode: ThemeMode.dark);
case 'ThemeMode.light':
return const ThemeModeState(themeMode: ThemeMode.light);
case 'ThemeMode.system':
default:
return const ThemeModeState(themeMode: ThemeMode.system);
}
}
@override
Map<String, String>? toJson(ThemeModeState state) {
return <String, String>{'themeMode': state.themeMode.toString()};
}
}
part of 'theme_cubit.dart';
@immutable
class ThemeModeState extends Equatable {
const ThemeModeState({
this.themeMode,
});
final ThemeMode? themeMode;
@override
List<Object?> get props => <Object?>[
themeMode,
];
}
import 'package:flutter/material.dart';
import 'package:calculus/provider/data.dart';
import 'package:calculus/utils/game_utils.dart';
class Game {
static Widget buildGameWidget(Data myProvider) {
final bool gameIsFinished = myProvider.isGameFinished();
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 8),
Game.buildTopIndicatorWidget(myProvider),
const SizedBox(height: 2),
const Expanded(
child: Text('GAME'),
),
const SizedBox(height: 2),
SizedBox(
height: 150,
width: double.maxFinite,
child:
gameIsFinished ? Game.buildEndGameMessage(myProvider) : const Text('CONTROLS'),
),
],
);
}
static Widget buildTopIndicatorWidget(Data myProvider) {
return Table(
children: const [
TableRow(
children: [
Column(children: [
Text(
'SCORE',
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
Text(
'TARGET',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: Colors.grey,
),
),
]),
Column(children: [
Text(
'INFOS',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.green,
),
),
]),
],
),
],
);
}
static TextButton buildRestartGameButton(Data myProvider) {
return TextButton(
child: const Image(
image: AssetImage('assets/icons/button_back.png'),
fit: BoxFit.fill,
),
onPressed: () => GameUtils.resetGame(myProvider),
);
}
static Widget buildEndGameMessage(Data myProvider) {
String decorationImageAssetName = '';
if (myProvider.gameWon) {
decorationImageAssetName = 'assets/icons/game_win.png';
} else {
decorationImageAssetName = 'assets/icons/game_fail.png';
}
Image decorationImage =
Image(image: AssetImage(decorationImageAssetName), fit: BoxFit.fill);
return Container(
margin: const EdgeInsets.all(2),
padding: const EdgeInsets.all(2),
child: Table(defaultColumnWidth: const IntrinsicColumnWidth(), children: [
TableRow(
children: [
Column(children: [decorationImage]),
Column(children: [buildRestartGameButton(myProvider)]),
Column(children: [decorationImage]),
],
),
]));
}
}
import 'package:flutter/material.dart';
import 'package:calculus/provider/data.dart';
import 'package:calculus/utils/game_utils.dart';
class Parameters {
static Widget buildParametersSelector(Data myProvider) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 5),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Parameters.buildParameterSelector(myProvider, 'level'),
const SizedBox(height: 5),
Parameters.buildParameterSelector(myProvider, 'skin'),
const SizedBox(height: 5),
],
),
),
const SizedBox(height: 5),
Container(
child: Parameters.buildStartGameButton(myProvider),
),
],
);
}
static Widget buildStartGameButton(Data myProvider) {
Column decorationImage = const Column(children: [
Image(
image: AssetImage('assets/icons/game_win.png'),
fit: BoxFit.fill,
),
]);
return Container(
margin: const EdgeInsets.all(2),
padding: const EdgeInsets.all(2),
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
children: [
TableRow(
children: [
decorationImage,
Column(children: [
TextButton(
child: const Image(
image: AssetImage('assets/icons/button_start.png'),
fit: BoxFit.fill,
),
onPressed: () => GameUtils.startGame(myProvider),
),
]),
decorationImage,
],
),
],
),
);
}
static Widget buildParameterSelector(Data myProvider, String parameterCode) {
List availableValues = myProvider.getParameterAvailableValues(parameterCode);
if (availableValues.length == 1) {
return const SizedBox(height: 1);
}
return Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
children: [
TableRow(
children: [
for (var index = 0; index < availableValues.length; index++)
Column(children: [
_buildParameterButton(myProvider, parameterCode, availableValues[index])
]),
],
),
],
);
}
static TextButton _buildParameterButton(
Data myProvider,
String parameterCode,
String parameterValue,
) {
String currentValue = myProvider.getParameterValue(parameterCode).toString();
bool isActive = (parameterValue == currentValue);
String imageAsset = 'assets/icons/${parameterCode}_$parameterValue.png';
return TextButton(
child: Container(
padding: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: isActive ? Colors.blue : Colors.white,
width: 10,
),
),
child: Image(
image: AssetImage(imageAsset),
fit: BoxFit.fill,
),
),
onPressed: () => myProvider.setParameterValue(parameterCode, parameterValue),
);
}
}
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hive/hive.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';
import 'package:calculus/provider/data.dart';
import 'package:calculus/screens/home.dart';
import 'package:calculus/config/theme.dart';
import 'package:calculus/cubit/game_cubit.dart';
import 'package:calculus/cubit/nav_cubit.dart';
import 'package:calculus/cubit/theme_cubit.dart';
import 'package:calculus/cubit/settings_game_cubit.dart';
import 'package:calculus/cubit/settings_global_cubit.dart';
import 'package:calculus/ui/skeleton.dart';
void main() {
void main() async {
// Initialize packages
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
final Directory tmpDir = await getTemporaryDirectory();
Hive.init(tmpDir.toString());
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: tmpDir,
);
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((value) => runApp(const MyApp()));
.then((value) => runApp(EasyLocalization(
path: 'assets/translations',
supportedLocales: const <Locale>[
Locale('en'),
Locale('fr'),
],
fallbackLocale: const Locale('en'),
useFallbackTranslations: true,
child: const MyApp(),
)));
}
class MyApp extends StatelessWidget {
......@@ -17,23 +44,58 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (BuildContext context) => Data(),
child: Consumer<Data>(builder: (context, data, child) {
return OverlaySupport(
child: MaterialApp(
final List<String> assets = getImagesAssets();
for (String asset in assets) {
precacheImage(AssetImage(asset), context);
}
return MultiBlocProvider(
providers: [
BlocProvider<NavCubit>(create: (context) => NavCubit()),
BlocProvider<ThemeCubit>(create: (context) => ThemeCubit()),
BlocProvider<GameCubit>(create: (context) => GameCubit()),
BlocProvider<GlobalSettingsCubit>(create: (context) => GlobalSettingsCubit()),
BlocProvider<GameSettingsCubit>(create: (context) => GameSettingsCubit()),
],
child: BlocBuilder<ThemeCubit, ThemeModeState>(
builder: (BuildContext context, ThemeModeState state) {
return MaterialApp(
title: 'Calculus',
home: const SkeletonScreen(),
// Theme stuff
theme: lightTheme,
darkTheme: darkTheme,
themeMode: state.themeMode,
// Localization stuff
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: const Home(),
routes: {
Home.id: (context) => const Home(),
);
},
),
);
}),
);
}
List<String> getImagesAssets() {
final List<String> assets = [];
const List<String> gameImages = [
'button_back',
'button_delete_saved_game',
'button_resume_game',
'button_start',
'game_fail',
'game_win',
'placeholder',
];
for (String image in gameImages) {
assets.add('assets/ui/$image.png');
}
return assets;
}
}
import 'package:calculus/models/settings/settings_game.dart';
import 'package:calculus/models/settings/settings_global.dart';
import 'package:calculus/utils/tools.dart';
class Game {
Game({
// Settings
required this.gameSettings,
required this.globalSettings,
// State
this.isRunning = false,
this.isStarted = false,
this.isFinished = false,
this.animationInProgress = false,
// Base data
required this.items,
// Game data
this.score = 0,
});
// Settings
final GameSettings gameSettings;
final GlobalSettings globalSettings;
// State
bool isRunning;
bool isStarted;
bool isFinished;
bool animationInProgress;
// Base data
final List<String> items;
// Game data
int score;
factory Game.createEmpty() {
return Game(
gameSettings: GameSettings.createDefault(),
globalSettings: GlobalSettings.createDefault(),
items: [],
);
}
factory Game.createNew({
GameSettings? gameSettings,
GlobalSettings? globalSettings,
}) {
final GameSettings newGameSettings = gameSettings ?? GameSettings.createDefault();
final GlobalSettings newGlobalSettings = globalSettings ?? GlobalSettings.createDefault();
return Game(
// Settings
gameSettings: newGameSettings,
globalSettings: newGlobalSettings,
// State
isRunning: true,
// Base data
items: [],
);
}
bool get canBeResumed => isStarted && !isFinished;
bool get gameWon => isRunning && isStarted && isFinished;
void dump() {
printlog('');
printlog('## Current game dump:');
printlog('');
printlog('$Game:');
printlog(' Settings');
gameSettings.dump();
globalSettings.dump();
printlog(' State');
printlog(' isRunning: $isRunning');
printlog(' isStarted: $isStarted');
printlog(' isFinished: $isFinished');
printlog(' animationInProgress: $animationInProgress');
printlog(' Base data');
printlog(' items: $items');
printlog(' Game data');
printlog(' score: $score');
printlog('');
}
@override
String toString() {
return '$Game(${toJson()})';
}
Map<String, dynamic>? toJson() {
return <String, dynamic>{
// Settings
'gameSettings': gameSettings.toJson(),
'globalSettings': globalSettings.toJson(),
// State
'isRunning': isRunning,
'isStarted': isStarted,
'isFinished': isFinished,
'animationInProgress': animationInProgress,
// Base data
'items': items,
// Game data
'score': score,
};
}
}
import 'package:calculus/config/default_game_settings.dart';
import 'package:calculus/utils/tools.dart';
class GameSettings {
final String itemsCount;
final String timerValue;
GameSettings({
required this.itemsCount,
required this.timerValue,
});
// Getters to convert String to int
int get itemsCountValue => int.parse(itemsCount);
int get timerCountValue => int.parse(timerValue);
static String getItemsCountValueFromUnsafe(String itemsCount) {
if (DefaultGameSettings.allowedItemsCountValues.contains(itemsCount)) {
return itemsCount;
}
return DefaultGameSettings.defaultItemsCountValue;
}
static String getTimerValueFromUnsafe(String timerValue) {
if (DefaultGameSettings.allowedTimerValues.contains(timerValue)) {
return timerValue;
}
return DefaultGameSettings.defaultTimerValue;
}
factory GameSettings.createDefault() {
return GameSettings(
itemsCount: DefaultGameSettings.defaultItemsCountValue,
timerValue: DefaultGameSettings.defaultTimerValue,
);
}
void dump() {
printlog('$GameSettings:');
printlog(' ${DefaultGameSettings.parameterCodeItemsCount}: $itemsCount');
printlog(' ${DefaultGameSettings.parameterCodeTimerValue}: $timerValue');
printlog('');
}
@override
String toString() {
return '$GameSettings(${toJson()})';
}
Map<String, dynamic>? toJson() {
return <String, dynamic>{
DefaultGameSettings.parameterCodeItemsCount: itemsCount,
DefaultGameSettings.parameterCodeTimerValue: timerValue,
};
}
}
import 'package:calculus/config/default_global_settings.dart';
import 'package:calculus/utils/tools.dart';
class GlobalSettings {
String skin;
GlobalSettings({
required this.skin,
});
static String getSkinValueFromUnsafe(String skin) {
if (DefaultGlobalSettings.allowedSkinValues.contains(skin)) {
return skin;
}
return DefaultGlobalSettings.defaultSkinValue;
}
factory GlobalSettings.createDefault() {
return GlobalSettings(
skin: DefaultGlobalSettings.defaultSkinValue,
);
}
void dump() {
printlog('$GlobalSettings:');
printlog(' ${DefaultGlobalSettings.parameterCodeSkin}: $skin');
printlog('');
}
@override
String toString() {
return '$GlobalSettings(${toJson()})';
}
Map<String, dynamic>? toJson() {
return <String, dynamic>{
DefaultGlobalSettings.parameterCodeSkin: skin,
};
}
}
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Data extends ChangeNotifier {
// Configuration available values
final List<String> _availableLevelValues = ['easy', 'medium', 'hard'];
final List<String> _availableSkinValues = ['default', 'images'];
List<String> get availableLevelValues => _availableLevelValues;
List<String> get availableSkinValues => _availableSkinValues;
// Application default configuration
String _parameterLevel = '';
final String _parameterLevelDefault = 'medium';
String _parameterSkin = '';
final String _parameterSkinDefault = 'default';
// Application current configuration
String get parameterLevel => _parameterLevel;
String get parameterSkin => _parameterSkin;
// Game data
bool _gameIsRunning = false;
bool _gameWon = false;
void updateParameterLevel(String parameterLevel) {
_parameterLevel = parameterLevel;
notifyListeners();
}
void updateParameterSkin(String parameterSkin) {
_parameterSkin = parameterSkin;
notifyListeners();
}
String getParameterValue(String parameterCode) {
switch (parameterCode) {
case 'level':
{
return _parameterLevel;
}
case 'skin':
{
return _parameterSkin;
}
}
return '';
}
List getParameterAvailableValues(String parameterCode) {
switch (parameterCode) {
case 'level':
{
return _availableLevelValues;
}
case 'skin':
{
return _availableSkinValues;
}
}
return [];
}
setParameterValue(String parameterCode, String parameterValue) async {
switch (parameterCode) {
case 'level':
{
updateParameterLevel(parameterValue);
}
break;
case 'skin':
{
updateParameterSkin(parameterValue);
}
break;
}
final prefs = await SharedPreferences.getInstance();
prefs.setString(parameterCode, parameterValue);
}
void initParametersValues() async {
final prefs = await SharedPreferences.getInstance();
setParameterValue('level', prefs.getString('level') ?? _parameterLevelDefault);
setParameterValue('skin', prefs.getString('skin') ?? _parameterSkinDefault);
}
bool get gameIsRunning => _gameIsRunning;
void updateGameIsRunning(bool gameIsRunning) {
_gameIsRunning = gameIsRunning;
notifyListeners();
}
bool isGameFinished() {
return _gameWon;
}
bool get gameWon => _gameWon;
void updateGameWon(bool gameWon) {
_gameWon = gameWon;
notifyListeners();
}
void resetGame() {
_gameIsRunning = false;
_gameWon = false;
notifyListeners();
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:calculus/layout/game.dart';
import 'package:calculus/layout/parameters.dart';
import 'package:calculus/provider/data.dart';
import 'package:calculus/utils/game_utils.dart';
class Home extends StatefulWidget {
const Home({super.key});
static const String id = 'home';
@override
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
@override
void initState() {
super.initState();
Data myProvider = Provider.of<Data>(context, listen: false);
myProvider.initParametersValues();
}
@override
Widget build(BuildContext context) {
final Data myProvider = Provider.of<Data>(context);
final List<Widget> menuActions = [];
if (myProvider.gameIsRunning) {
menuActions.add(
TextButton(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: Colors.blue,
width: 4,
),
),
margin: const EdgeInsets.all(8),
child: const Image(
image: AssetImage('assets/icons/button_back.png'), fit: BoxFit.fill),
),
onPressed: () => toast('Long press to quit game...'),
onLongPress: () => GameUtils.resetGame(myProvider),
),
);
}
return Scaffold(
appBar: AppBar(
actions: menuActions,
),
body: SafeArea(
child: Center(
child: myProvider.gameIsRunning
? Game.buildGameWidget(myProvider)
: Parameters.buildParametersSelector(myProvider)),
));
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:calculus/cubit/game_cubit.dart';
import 'package:calculus/models/game/game.dart';
import 'package:calculus/ui/widgets/actions/button_game_quit.dart';
class GameEndWidget extends StatelessWidget {
const GameEndWidget({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<GameCubit, GameState>(
builder: (BuildContext context, GameState gameState) {
final Game currentGame = gameState.currentGame;
final Image decorationImage = Image(
image: AssetImage(
currentGame.gameWon ? 'assets/ui/game_win.png' : 'assets/ui/game_fail.png'),
fit: BoxFit.fill,
);
return Container(
margin: const EdgeInsets.all(2),
padding: const EdgeInsets.all(2),
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
children: [
TableRow(
children: [
Column(
children: [decorationImage],
),
Column(
children: [
currentGame.animationInProgress == true
? decorationImage
: const QuitGameButton()
],
),
Column(
children: [decorationImage],
),
],
),
],
),
);
},
);
}
}
import 'package:flutter/material.dart';
import 'package:calculus/ui/widgets/indicators/indicator_score.dart';
class GameTopWidget extends StatelessWidget {
const GameTopWidget({super.key});
@override
Widget build(BuildContext context) {
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ScoreIndicator(),
],
);
}
}
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
class AppHeader extends StatelessWidget {
const AppHeader({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
return Text(
tr(text),
textAlign: TextAlign.start,
style: Theme.of(context).textTheme.headlineMedium!.apply(fontWeightDelta: 2),
);
}
}
class AppTitle extends StatelessWidget {
const AppTitle({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
return Text(
tr(text),
textAlign: TextAlign.start,
style: Theme.of(context).textTheme.titleLarge!.apply(fontWeightDelta: 2),
);
}
}
import 'package:flutter/material.dart';
import 'package:calculus/utils/color_extensions.dart';
class OutlinedText extends StatelessWidget {
const OutlinedText({
super.key,
required this.text,
required this.fontSize,
required this.textColor,
this.outlineColor,
});
final String text;
final double fontSize;
final Color textColor;
final Color? outlineColor;
@override
Widget build(BuildContext context) {
final double delta = fontSize / 30;
return Text(
text,
style: TextStyle(
inherit: true,
fontSize: fontSize,
fontWeight: FontWeight.w600,
color: textColor,
shadows: [
Shadow(
offset: Offset(-delta, -delta),
color: outlineColor ?? textColor.darken(),
),
Shadow(
offset: Offset(delta, -delta),
color: outlineColor ?? textColor.darken(),
),
Shadow(
offset: Offset(delta, delta),
color: outlineColor ?? textColor.darken(),
),
Shadow(
offset: Offset(-delta, delta),
color: outlineColor ?? textColor.darken(),
),
],
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:calculus/cubit/game_cubit.dart';
import 'package:calculus/models/game/game.dart';
import 'package:calculus/ui/game/game_end.dart';
import 'package:calculus/ui/game/game_top.dart';
import 'package:calculus/ui/widgets/game/game_board.dart';
class GameLayout extends StatelessWidget {
const GameLayout({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<GameCubit, GameState>(
builder: (BuildContext context, GameState gameState) {
final Game currentGame = gameState.currentGame;
return Container(
alignment: AlignmentDirectional.topCenter,
padding: const EdgeInsets.all(4),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const GameTopWidget(),
const SizedBox(height: 8),
const GameBoardWidget(),
const SizedBox(height: 8),
const Expanded(child: SizedBox.shrink()),
currentGame.isFinished ? const GameEndWidget() : const SizedBox.shrink(),
],
),
);
},
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:calculus/config/default_game_settings.dart';
import 'package:calculus/config/default_global_settings.dart';
import 'package:calculus/cubit/settings_game_cubit.dart';
import 'package:calculus/cubit/settings_global_cubit.dart';
import 'package:calculus/ui/parameters/parameter_image.dart';
import 'package:calculus/ui/parameters/parameter_painter.dart';
import 'package:calculus/ui/widgets/actions/button_delete_saved_game.dart';
import 'package:calculus/ui/widgets/actions/button_game_start_new.dart';
import 'package:calculus/ui/widgets/actions/button_resume_saved_game.dart';
class ParametersLayout extends StatelessWidget {
const ParametersLayout({super.key, required this.canResume});
final bool canResume;
final double separatorHeight = 8.0;
@override
Widget build(BuildContext context) {
final List<Widget> lines = [];
// Game settings
for (String code in DefaultGameSettings.availableParameters) {
lines.add(Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: buildParametersLine(
code: code,
isGlobal: false,
),
));
lines.add(SizedBox(height: separatorHeight));
}
lines.add(SizedBox(height: separatorHeight));
if (canResume == false) {
// Start new game
lines.add(const Expanded(
child: StartNewGameButton(),
));
} else {
// Resume game
lines.add(const Expanded(
child: ResumeSavedGameButton(),
));
// Delete saved game
lines.add(SizedBox.square(
dimension: MediaQuery.of(context).size.width / 4,
child: const DeleteSavedGameButton(),
));
}
lines.add(SizedBox(height: separatorHeight));
// Global settings
for (String code in DefaultGlobalSettings.availableParameters) {
lines.add(Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: buildParametersLine(
code: code,
isGlobal: true,
),
));
lines.add(SizedBox(height: separatorHeight));
}
return Column(
children: lines,
);
}
List<Widget> buildParametersLine({
required String code,
required bool isGlobal,
}) {
final List<Widget> parameterButtons = [];
final List<String> availableValues = isGlobal
? DefaultGlobalSettings.getAvailableValues(code)
: DefaultGameSettings.getAvailableValues(code);
if (availableValues.length <= 1) {
return [];
}
for (String value in availableValues) {
final Widget parameterButton = BlocBuilder<GameSettingsCubit, GameSettingsState>(
builder: (BuildContext context, GameSettingsState gameSettingsState) {
return BlocBuilder<GlobalSettingsCubit, GlobalSettingsState>(
builder: (BuildContext context, GlobalSettingsState globalSettingsState) {
final GameSettingsCubit gameSettingsCubit =
BlocProvider.of<GameSettingsCubit>(context);
final GlobalSettingsCubit globalSettingsCubit =
BlocProvider.of<GlobalSettingsCubit>(context);
final String currentValue = isGlobal
? globalSettingsCubit.getParameterValue(code)
: gameSettingsCubit.getParameterValue(code);
final bool isActive = (value == currentValue);
final double displayWidth = MediaQuery.of(context).size.width;
final double itemWidth = displayWidth / availableValues.length - 26;
final bool displayedWithAssets =
DefaultGlobalSettings.displayedWithAssets.contains(code) ||
DefaultGameSettings.displayedWithAssets.contains(code);
return TextButton(
child: Container(
child: displayedWithAssets
? SizedBox.square(
dimension: itemWidth,
child: ParameterImage(
code: code,
value: value,
isSelected: isActive,
),
)
: CustomPaint(
size: Size(itemWidth, itemWidth),
willChange: false,
painter: ParameterPainter(
code: code,
value: value,
isSelected: isActive,
gameSettings: gameSettingsState.settings,
globalSettings: globalSettingsState.settings,
),
isComplex: true,
),
),
onPressed: () {
isGlobal
? globalSettingsCubit.setParameterValue(code, value)
: gameSettingsCubit.setParameterValue(code, value);
},
);
},
);
},
);
parameterButtons.add(parameterButton);
}
return parameterButtons;
}
}
import 'package:flutter/material.dart';
class ParameterImage extends StatelessWidget {
const ParameterImage({
super.key,
required this.code,
required this.value,
required this.isSelected,
});
final String code;
final String value;
final bool isSelected;
static const Color buttonBackgroundColor = Colors.white;
static const Color buttonBorderColorActive = Colors.blue;
static const Color buttonBorderColorInactive = Colors.white;
static const double buttonBorderWidth = 8.0;
static const double buttonBorderRadius = 8.0;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: buttonBackgroundColor,
borderRadius: BorderRadius.circular(buttonBorderRadius),
border: Border.all(
color: isSelected ? buttonBorderColorActive : buttonBorderColorInactive,
width: buttonBorderWidth,
),
),
child: Image(
image: AssetImage('assets/ui/${code}_$value.png'),
fit: BoxFit.fill,
),
);
}
}
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:calculus/config/default_game_settings.dart';
import 'package:calculus/models/settings/settings_game.dart';
import 'package:calculus/models/settings/settings_global.dart';
import 'package:calculus/utils/tools.dart';
class ParameterPainter extends CustomPainter {
const ParameterPainter({
required this.code,
required this.value,
required this.isSelected,
required this.gameSettings,
required this.globalSettings,
});
final String code;
final String value;
final bool isSelected;
final GameSettings gameSettings;
final GlobalSettings globalSettings;
@override
void paint(Canvas canvas, Size size) {
// force square
final double canvasSize = min(size.width, size.height);
const Color borderColorEnabled = Colors.blue;
const Color borderColorDisabled = Colors.white;
// "enabled/disabled" border
final paint = Paint();
paint.style = PaintingStyle.stroke;
paint.color = isSelected ? borderColorEnabled : borderColorDisabled;
paint.strokeJoin = StrokeJoin.round;
paint.strokeWidth = 10;
canvas.drawRect(
Rect.fromPoints(const Offset(0, 0), Offset(canvasSize, canvasSize)), paint);
// content
switch (code) {
case DefaultGameSettings.parameterCodeItemsCount:
paintItemsCountParameterItem(value, canvas, canvasSize);
break;
case DefaultGameSettings.parameterCodeTimerValue:
paintTimerParameterItem(value, canvas, canvasSize);
break;
default:
printlog('Unknown parameter: $code/$value');
paintUnknownParameterItem(value, canvas, canvasSize);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
// "unknown" parameter -> simple block with text
void paintUnknownParameterItem(
final String value,
final Canvas canvas,
final double size,
) {
final paint = Paint();
paint.strokeJoin = StrokeJoin.round;
paint.strokeWidth = 3;
paint.color = Colors.grey;
paint.style = PaintingStyle.fill;
canvas.drawRect(Rect.fromPoints(const Offset(0, 0), Offset(size, size)), paint);
final textSpan = TextSpan(
text: '?\n$value',
style: const TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold,
),
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
textAlign: TextAlign.center,
);
textPainter.layout();
textPainter.paint(
canvas,
Offset(
(size - textPainter.width) * 0.5,
(size - textPainter.height) * 0.5,
),
);
}
void paintItemsCountParameterItem(
final String value,
final Canvas canvas,
final double size,
) {
Color backgroundColor = Colors.grey;
String text = '';
switch (value) {
case DefaultGameSettings.itemsCountValueNoLimit:
backgroundColor = Colors.grey;
text = '⭐';
break;
default:
printlog('Wrong value for itemsCount parameter value: $value');
}
final paint = Paint();
paint.strokeJoin = StrokeJoin.round;
paint.strokeWidth = 3 / 100 * size;
// Colored background
paint.color = backgroundColor;
paint.style = PaintingStyle.fill;
canvas.drawRect(Rect.fromPoints(const Offset(0, 0), Offset(size, size)), paint);
// centered text value
final textSpan = TextSpan(
text: text,
style: TextStyle(
color: Colors.black,
fontSize: size / 2.6,
fontWeight: FontWeight.bold,
),
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
textAlign: TextAlign.center,
);
textPainter.layout();
textPainter.paint(
canvas,
Offset(
(size - textPainter.width) * 0.5,
(size - textPainter.height) * 0.5,
),
);
}
void paintTimerParameterItem(
final String value,
final Canvas canvas,
final double size,
) {
Color backgroundColor = Colors.grey;
String text = '';
switch (value) {
case DefaultGameSettings.timerValueNoTimer:
backgroundColor = Colors.grey;
text = '⭐';
break;
default:
printlog('Wrong value for itemsCount parameter value: $value');
}
final paint = Paint();
paint.strokeJoin = StrokeJoin.round;
paint.strokeWidth = 3;
// Colored background
paint.color = backgroundColor;
paint.style = PaintingStyle.fill;
canvas.drawRect(Rect.fromPoints(const Offset(0, 0), Offset(size, size)), paint);
// centered text value
final textSpan = TextSpan(
text: text,
style: TextStyle(
color: Colors.black,
fontSize: size / 2.6,
fontWeight: FontWeight.bold,
),
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
textAlign: TextAlign.center,
);
textPainter.layout();
textPainter.paint(
canvas,
Offset(
(size - textPainter.width) * 0.5,
(size - textPainter.height) * 0.5,
),
);
}
}
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:calculus/ui/helpers/app_titles.dart';
class PageAbout extends StatelessWidget {
const PageAbout({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
const SizedBox(height: 8),
const AppTitle(text: 'about_title'),
const Text('about_content').tr(),
FutureBuilder<PackageInfo>(
future: PackageInfo.fromPlatform(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
return const Text('about_version').tr(
namedArgs: {
'version': snapshot.data!.version,
},
);
default:
return const SizedBox();
}
},
),
],
),
);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment