summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/esense_input.dart83
-rw-r--r--lib/game_over_stats.dart4
-rw-r--r--lib/level.dart68
-rw-r--r--lib/level_selection.dart128
-rw-r--r--lib/simfile.dart9
5 files changed, 158 insertions, 134 deletions
diff --git a/lib/esense_input.dart b/lib/esense_input.dart
new file mode 100644
index 0000000..705bd5f
--- /dev/null
+++ b/lib/esense_input.dart
@@ -0,0 +1,83 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:esense_flutter/esense.dart';
+import 'package:flutter/material.dart';
+import 'package:permission_handler/permission_handler.dart';
+
+class ESenseInput {
+ static final instance = ESenseInput._();
+
+ ESenseManager eSenseManager = ESenseManager('unknown');
+ ValueNotifier<String> deviceStatus = ValueNotifier('');
+
+ String eSenseDeviceName = '';
+ bool connected = false;
+ bool sampling = false;
+
+ ESenseInput._() {
+ _listenToESense();
+ }
+
+ Future<void> _askForPermissions() async {
+ if (!Platform.isAndroid && !Platform.isIOS) return;
+ if (!(await Permission.bluetoothScan.request().isGranted &&
+ await Permission.bluetoothConnect.request().isGranted)) {
+ print(
+ 'WARNING - no permission to use Bluetooth granted. Cannot access eSense device.');
+ }
+ // for some strange reason, Android requires permission to location for Bluetooth to work.....?
+ if (Platform.isAndroid) {
+ if (!(await Permission.locationWhenInUse.request().isGranted)) {
+ print(
+ 'WARNING - no permission to access location granted. Cannot access eSense device.');
+ }
+ }
+ }
+
+ StreamSubscription _listenToESense() {
+ // if you want to get the connection events when connecting,
+ // set up the listener BEFORE connecting...
+ return eSenseManager.connectionEvents.listen((event) {
+ print('CONNECTION event: $event');
+
+ // when we're connected to the eSense device, we can start listening to events from it
+ // if (event.type == ConnectionType.connected) _listenToESenseEvents();
+
+ connected = false;
+ switch (event.type) {
+ case ConnectionType.connected:
+ deviceStatus.value = 'connected';
+ connected = true;
+ break;
+ case ConnectionType.unknown:
+ deviceStatus.value = 'unknown';
+ break;
+ case ConnectionType.disconnected:
+ deviceStatus.value = 'disconnected';
+ sampling = false;
+ break;
+ case ConnectionType.device_found:
+ deviceStatus.value = 'device_found';
+ break;
+ case ConnectionType.device_not_found:
+ deviceStatus.value = 'device_not_found';
+ break;
+ }
+ });
+ }
+
+ Future<void> connectToESense(String deviceName) async {
+ if (!connected) {
+ await _askForPermissions();
+ print('Trying to connect to eSense device namend \'$deviceName\'');
+ eSenseDeviceName = deviceName;
+ eSenseManager.deviceName = deviceName;
+ connected = await eSenseManager.connect();
+ print('Trying to connect to eSense device namend \'${eSenseManager.deviceName}\'');
+
+ deviceStatus.value = connected ? 'connecting...' : 'connection failed';
+ print(deviceStatus.value);
+ }
+ }
+}
diff --git a/lib/game_over_stats.dart b/lib/game_over_stats.dart
index a80617c..0e73024 100644
--- a/lib/game_over_stats.dart
+++ b/lib/game_over_stats.dart
@@ -50,8 +50,8 @@ class GameOverStats extends StatelessWidget {
]),
TextButton(
onPressed: () {
- Route route = MaterialPageRoute(
- builder: (context) => Level(stepmaniaFolderPath: simfile.directoryPath));
+ Route route =
+ MaterialPageRoute(builder: (context) => Level(simfile));
Navigator.pushReplacement(context, route);
},
child: Text('Retry'))
diff --git a/lib/level.dart b/lib/level.dart
index cc17efb..4f69b67 100644
--- a/lib/level.dart
+++ b/lib/level.dart
@@ -1,5 +1,4 @@
import 'dart:async';
-import 'dart:io';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
@@ -9,8 +8,8 @@ import 'package:sense_the_rhythm/game_over_stats.dart';
import 'package:sense_the_rhythm/simfile.dart';
class Level extends StatefulWidget {
- const Level({super.key, required this.stepmaniaFolderPath});
- final String stepmaniaFolderPath;
+ const Level(this.simfile, {super.key});
+ final Simfile simfile;
@override
State<Level> createState() => _LevelState();
@@ -23,9 +22,8 @@ class InputDirection {
bool right = false;
}
-class _LevelState extends State<Level> {
+class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
final player = AudioPlayer();
- Simfile? simfile;
bool _isPlaying = true;
Duration? _duration;
Duration? _position;
@@ -36,8 +34,13 @@ class _LevelState extends State<Level> {
final FocusNode _focusNode = FocusNode();
InputDirection inputDirection = InputDirection();
+ String hitOrMissMessage = 'Play!';
+
List<Note> notes = [];
+ late AnimationController _animationController;
+ late Animation<double> _animation;
+
@override
void setState(VoidCallback fn) {
// Subscriptions only can be closed asynchronously,
@@ -50,6 +53,15 @@ class _LevelState extends State<Level> {
@override
void initState() {
super.initState();
+
+ _animationController = AnimationController(
+ vsync: this,
+ duration: Duration(seconds: 2),
+ );
+ _animation =
+ Tween<double>(begin: 1.0, end: 0.0).animate(_animationController);
+ _animationController.forward();
+
// Use initial values from player
player.getDuration().then(
(value) => setState(() {
@@ -77,7 +89,7 @@ class _LevelState extends State<Level> {
player.onPlayerComplete.listen((void _) {
Route route = MaterialPageRoute(
builder: (context) => GameOverStats(
- simfile: simfile!,
+ simfile: widget.simfile,
notes: notes,
));
Navigator.pushReplacement(context, route);
@@ -110,31 +122,25 @@ class _LevelState extends State<Level> {
if (keypressCorrect) {
print("you hit!");
note.wasHit = true;
-
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('Great!'),
- duration: Duration(milliseconds: 500),
- ),
- );
+ _animationController.reset();
+ _animationController.forward();
+ setState(() {
+ hitOrMissMessage = 'Great!';
+ });
}
} else if (note.position < -0.5 * 1.0 / 60.0) {
print("Missed");
note.wasHit = false;
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('Missed!'),
- duration: Duration(milliseconds: 500),
- ),
- );
+ _animationController.reset();
+ _animationController.forward();
+ setState(() {
+ hitOrMissMessage = 'Missed';
+ });
}
}
});
- simfile = Simfile(widget.stepmaniaFolderPath);
- simfile!.load();
-
- simfile!.chartSimplest!.beats.forEach((time, noteData) {
+ widget.simfile.chartSimplest!.beats.forEach((time, noteData) {
int arrowIndex = noteData.indexOf('1');
if (arrowIndex < 0 || arrowIndex > 3) {
return;
@@ -142,7 +148,7 @@ class _LevelState extends State<Level> {
notes.add(Note(time: time, direction: ArrowDirection.values[arrowIndex]));
});
- player.play(DeviceFileSource(simfile!.audioPath!));
+ player.play(DeviceFileSource(widget.simfile.audioPath!));
}
@override
@@ -192,7 +198,7 @@ class _LevelState extends State<Level> {
}
},
),
- title: Text(widget.stepmaniaFolderPath.split('/').last),
+ title: Text(widget.simfile.tags['TITLE']!),
actions: [
IconButton(
icon: Icon(Icons.close),
@@ -219,10 +225,13 @@ class _LevelState extends State<Level> {
top: 50,
width: MediaQuery.of(context).size.width,
left: 0,
- child: Text(
- "Great!",
- textScaler: TextScaler.linear(4),
- textAlign: TextAlign.center,
+ child: FadeTransition(
+ opacity: _animation,
+ child: Text(
+ hitOrMissMessage,
+ textScaler: TextScaler.linear(4),
+ textAlign: TextAlign.center,
+ ),
),
),
Positioned(
@@ -242,6 +251,7 @@ class _LevelState extends State<Level> {
@override
void dispose() {
+ _animationController.dispose();
_durationSubscription?.cancel();
_positionSubscription?.cancel();
player.dispose();
diff --git a/lib/level_selection.dart b/lib/level_selection.dart
index 5359d66..33d8c8b 100644
--- a/lib/level_selection.dart
+++ b/lib/level_selection.dart
@@ -1,10 +1,11 @@
import 'dart:io';
-import 'package:esense_flutter/esense.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sense_the_rhythm/esense_connect_dialog.dart';
+import 'package:sense_the_rhythm/esense_input.dart';
+import 'package:sense_the_rhythm/simfile.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'level.dart';
@@ -18,90 +19,14 @@ class LevelSelection extends StatefulWidget {
class _LevelSelectionState extends State<LevelSelection> {
String? stepmaniaCoursesPath;
- List<FileSystemEntity> stepmaniaCoursesFolders = [];
-
- String eSenseDeviceName = '';
- ESenseManager? eSenseManager;
- ValueNotifier<String> _deviceStatus = ValueNotifier('');
- // String _deviceStatus = '';
- bool connected = false;
- bool sampling = false;
+ List<Simfile> stepmaniaCoursesFolders = [];
@override
void initState() {
super.initState();
- _listenToESense();
loadFolderPath();
}
- Future<void> _askForPermissions() async {
- if (!(await Permission.bluetoothScan.request().isGranted &&
- await Permission.bluetoothConnect.request().isGranted)) {
- print(
- 'WARNING - no permission to use Bluetooth granted. Cannot access eSense device.');
- }
- // for some strange reason, Android requires permission to location for Bluetooth to work.....?
- if (Platform.isAndroid) {
- if (!(await Permission.locationWhenInUse.request().isGranted)) {
- print(
- 'WARNING - no permission to access location granted. Cannot access eSense device.');
- }
- }
- }
-
- Future<void> _listenToESense() async {
- await _askForPermissions();
-
- // if you want to get the connection events when connecting,
- // set up the listener BEFORE connecting...
- eSenseManager!.connectionEvents.listen((event) {
- print('CONNECTION event: $event');
-
- // when we're connected to the eSense device, we can start listening to events from it
- // if (event.type == ConnectionType.connected) _listenToESenseEvents();
-
- setState(() {
- connected = false;
- switch (event.type) {
- case ConnectionType.connected:
- _deviceStatus.value = 'connected';
- connected = true;
- break;
- case ConnectionType.unknown:
- _deviceStatus.value = 'unknown';
- break;
- case ConnectionType.disconnected:
- _deviceStatus.value = 'disconnected';
- sampling = false;
- break;
- case ConnectionType.device_found:
- _deviceStatus.value = 'device_found';
- break;
- case ConnectionType.device_not_found:
- _deviceStatus.value = 'device_not_found';
- break;
- }
- });
- });
- }
-
- Future<void> _connectToESense(String deviceName) async {
- if (!connected) {
- await _askForPermissions();
- print('Trying to connect to eSense device...');
- setState(() {
- eSenseDeviceName = deviceName;
- });
- print(eSenseDeviceName);
- eSenseManager = ESenseManager(eSenseDeviceName);
- connected = await eSenseManager!.connect();
- print('success!');
-
- setState(() {
- _deviceStatus.value = connected ? 'connecting...' : 'connection failed';
- });
- }
- }
Future<void> loadFolderPath() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
@@ -109,8 +34,9 @@ class _LevelSelectionState extends State<LevelSelection> {
prefs.getString('stepmania_courses');
if (stepmaniaCoursesPathSetting == null) return;
- List<FileSystemEntity> stepmaniaCoursesFoldersFuture = await listFilesAndFolders(stepmaniaCoursesPathSetting);
-
+ List<Simfile> stepmaniaCoursesFoldersFuture =
+ await listFilesAndFolders(stepmaniaCoursesPathSetting);
+
setState(() {
stepmaniaCoursesPath = stepmaniaCoursesPathSetting;
stepmaniaCoursesFolders = stepmaniaCoursesFoldersFuture;
@@ -118,6 +44,7 @@ class _LevelSelectionState extends State<LevelSelection> {
}
Future<void> selectFolder() async {
+ await Permission.manageExternalStorage.request();
String? selectedFolder = await FilePicker.platform.getDirectoryPath();
if (selectedFolder != null) {
@@ -129,15 +56,21 @@ class _LevelSelectionState extends State<LevelSelection> {
}
}
- Future<List<FileSystemEntity>> listFilesAndFolders(
- String directoryPath) async {
+ Future<List<Simfile>> listFilesAndFolders(String directoryPath) async {
final directory = Directory(directoryPath);
try {
// List all files and folders in the directory
- return directory
+ List<Simfile> simfiles = directory
.listSync()
.where((entity) => FileSystemEntity.isDirectorySync(entity.path))
- .toList();
+ .map((entity) {
+ Simfile simfile = Simfile(entity.path);
+ simfile.load();
+ return simfile;
+ }).toList();
+ simfiles.sort((a,b) => a.tags['TITLE']!.compareTo(b.tags['TITLE']!));
+
+ return simfiles;
} catch (e) {
print("Error reading directory: $e");
return [];
@@ -155,10 +88,10 @@ class _LevelSelectionState extends State<LevelSelection> {
context: context,
builder: (BuildContext context) {
return ESenseConnectDialog(
- deviceStatus: _deviceStatus,
- connect: (String name) {
- _connectToESense(name);
- });
+ deviceStatus: ESenseInput.instance.deviceStatus,
+ connect: (String name) {
+ ESenseInput.instance.connectToESense(name);
+ });
},
),
icon: const Icon(Icons.bluetooth))
@@ -176,26 +109,17 @@ class _LevelSelectionState extends State<LevelSelection> {
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
itemBuilder: (context, index) {
- String thumbnailPath = Directory(
- stepmaniaCoursesFolders[index].path)
- .listSync()
- .firstWhere(
- (file) => file.path.toLowerCase().endsWith('banner.png'),
- orElse: () => File(''))
- .path;
return ListTile(
- leading: Image.file(File(thumbnailPath)),
+ leading: Image.file(
+ File(stepmaniaCoursesFolders[index].bannerPath!)),
trailing: Icon(Icons.play_arrow),
- title:
- Text(stepmaniaCoursesFolders[index].path.split('/').last),
+ title: Text(stepmaniaCoursesFolders[index].tags["TITLE"]!),
subtitle: Text('3:45'),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
- builder: (BuildContext context) => Level(
- stepmaniaFolderPath:
- stepmaniaCoursesFolders[index].path,
- ))),
+ builder: (BuildContext context) =>
+ Level(stepmaniaCoursesFolders[index]))),
);
},
);
diff --git a/lib/simfile.dart b/lib/simfile.dart
index 764e3aa..7bdf5c0 100644
--- a/lib/simfile.dart
+++ b/lib/simfile.dart
@@ -124,7 +124,8 @@ class Simfile {
simfilePath = Directory(directoryPath)
.listSync()
.firstWhere((entity) => entity.path.endsWith('.sm'),
- orElse: () => File('')).path;
+ orElse: () => File(''))
+ .path;
audioPath = Directory(directoryPath)
.listSync()
@@ -132,6 +133,12 @@ class Simfile {
orElse: () => File(''))
.path;
+ bannerPath = Directory(directoryPath)
+ .listSync()
+ .firstWhere((file) => file.path.toLowerCase().endsWith('banner.png'),
+ orElse: () => File(''))
+ .path;
+
lines = File(simfilePath!).readAsStringSync();
RegExp commentsRegExp = RegExp(r'//.*$');