fix: reduce visibility of attributes and methods to a minimum

This commit is contained in:
Orangerot 2025-01-14 18:09:58 +01:00
parent ff0517d435
commit deab0ecfaf
5 changed files with 92 additions and 97 deletions

View file

@ -20,7 +20,7 @@ class Level extends StatefulWidget {
}
class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
final player = AudioPlayer();
final _player = AudioPlayer();
bool _isPlaying = true;
Duration? _duration;
Duration? _position;
@ -30,11 +30,11 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
StreamSubscription? _buttonSubscription;
final FocusNode _focusNode = FocusNode();
InputDirection inputDirection = InputDirection();
final InputDirection _inputDirection = InputDirection();
String hitOrMissMessage = 'Play!';
String _hitOrMissMessage = 'Play!';
List<Note> notes = [];
final List<Note> _notes = [];
late AnimationController _animationController;
late Animation<double> _animation;
@ -62,12 +62,12 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
_animationController.forward();
// Use initial values from player
player.getDuration().then(
_player.getDuration().then(
(value) => setState(() {
_duration = value;
}),
);
player.getCurrentPosition().then(
_player.getCurrentPosition().then(
(value) => setState(() {
_position = value;
}),
@ -75,24 +75,24 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
// listen for new values from player
_durationSubscription =
player.onDurationChanged.listen((Duration duration) {
_player.onDurationChanged.listen((Duration duration) {
setState(() => _duration = duration);
});
_positionSubscription =
player.onPositionChanged.listen((Duration position) {
_player.onPositionChanged.listen((Duration position) {
setState(() => _position = position);
for (final note in notes) {
for (final note in _notes) {
_noteHitCheck(note, position);
}
});
// go to GameOverStats when level finishes
player.onPlayerComplete.listen((void _) {
_player.onPlayerComplete.listen((void _) {
Route route = MaterialPageRoute(
builder: (context) => GameOverStats(
simfile: widget.simfile,
notes: notes,
notes: _notes,
));
Navigator.pushReplacement(context, route);
});
@ -112,10 +112,10 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
if (arrowIndex < 0 || arrowIndex > 3) {
return;
}
notes.add(Note(time: time, direction: ArrowDirection.values[arrowIndex]));
_notes.add(Note(time: time, direction: ArrowDirection.values[arrowIndex]));
});
player.play(DeviceFileSource(widget.simfile.audioPath!));
_player.play(DeviceFileSource(widget.simfile.audioPath!));
}
@override
@ -124,19 +124,19 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
_durationSubscription?.cancel();
_positionSubscription?.cancel();
_buttonSubscription?.cancel();
player.dispose();
_player.dispose();
super.dispose();
}
/// toggle between pause and resume
void _pauseResume() {
if (_isPlaying) {
player.pause();
_player.pause();
setState(() {
_isPlaying = false;
});
} else {
player.resume();
_player.resume();
setState(() {
_isPlaying = true;
});
@ -155,25 +155,25 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
// combine keyboard and esense input
InputDirection esenseDirection =
ESenseInput.instance.getInputDirection(note.direction);
inputDirection.up |= esenseDirection.up;
inputDirection.down |= esenseDirection.down;
inputDirection.left |= esenseDirection.left;
inputDirection.right |= esenseDirection.right;
_inputDirection.up |= esenseDirection.up;
_inputDirection.down |= esenseDirection.down;
_inputDirection.left |= esenseDirection.left;
_inputDirection.right |= esenseDirection.right;
// check if input matches arrow direction
bool keypressCorrect = false;
switch (note.direction) {
case ArrowDirection.up:
keypressCorrect = inputDirection.up;
keypressCorrect = _inputDirection.up;
break;
case ArrowDirection.down:
keypressCorrect = inputDirection.down;
keypressCorrect = _inputDirection.down;
break;
case ArrowDirection.right:
keypressCorrect = inputDirection.right;
keypressCorrect = _inputDirection.right;
break;
case ArrowDirection.left:
keypressCorrect = inputDirection.left;
keypressCorrect = _inputDirection.left;
break;
}
if (keypressCorrect) {
@ -181,9 +181,9 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
note.wasHit = true;
_animationController.reset();
_animationController.forward();
inputDirection.reset();
_inputDirection.reset();
setState(() {
hitOrMissMessage = 'Great!';
_hitOrMissMessage = 'Great!';
});
}
} else if (note.position < -0.5 * 1.0 / 60.0) {
@ -191,9 +191,9 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
note.wasHit = false;
_animationController.reset();
_animationController.forward();
inputDirection.reset();
_inputDirection.reset();
setState(() {
hitOrMissMessage = 'Missed';
_hitOrMissMessage = 'Missed';
});
}
}
@ -210,16 +210,16 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
}
switch (event.logicalKey) {
case LogicalKeyboardKey.arrowUp:
inputDirection.up = isDown;
_inputDirection.up = isDown;
break;
case LogicalKeyboardKey.arrowDown:
inputDirection.down = isDown;
_inputDirection.down = isDown;
break;
case LogicalKeyboardKey.arrowLeft:
inputDirection.left = isDown;
_inputDirection.left = isDown;
break;
case LogicalKeyboardKey.arrowRight:
inputDirection.right = isDown;
_inputDirection.right = isDown;
break;
}
}
@ -254,7 +254,7 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
)),
),
body: Stack(children: [
Arrows(notes: notes),
Arrows(notes: _notes),
Positioned(
top: 50,
width: MediaQuery.of(context).size.width,
@ -262,7 +262,7 @@ class _LevelState extends State<Level> with SingleTickerProviderStateMixin {
child: FadeTransition(
opacity: _animation,
child: Text(
hitOrMissMessage,
_hitOrMissMessage,
textScaler: TextScaler.linear(4),
textAlign: TextAlign.center,
),

View file

@ -17,36 +17,35 @@ class LevelSelection extends StatefulWidget {
}
class _LevelSelectionState extends State<LevelSelection> {
String? stepmaniaCoursesPath;
List<Simfile> stepmaniaCoursesFolders = [];
List<Simfile> stepmaniaCoursesFoldersFiltered = [];
String searchString = '';
String? _stepmaniaCoursesPath;
List<Simfile> _stepmaniaCoursesFolders = [];
List<Simfile> _stepmaniaCoursesFoldersFiltered = [];
@override
void initState() {
super.initState();
loadFolderPath();
_loadFolderPath();
}
/// gets folder path from persistent storage and updates state with loaded simfiles
Future<void> loadFolderPath() async {
Future<void> _loadFolderPath() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final String? stepmaniaCoursesPathSetting =
prefs.getString('stepmania_courses');
if (stepmaniaCoursesPathSetting == null) return;
List<Simfile> stepmaniaCoursesFoldersFuture =
await listFilesAndFolders(stepmaniaCoursesPathSetting);
await _listFilesAndFolders(stepmaniaCoursesPathSetting);
setState(() {
stepmaniaCoursesPath = stepmaniaCoursesPathSetting;
stepmaniaCoursesFolders = stepmaniaCoursesFoldersFuture;
stepmaniaCoursesFoldersFiltered = stepmaniaCoursesFoldersFuture;
_stepmaniaCoursesPath = stepmaniaCoursesPathSetting;
_stepmaniaCoursesFolders = stepmaniaCoursesFoldersFuture;
_stepmaniaCoursesFoldersFiltered = stepmaniaCoursesFoldersFuture;
});
}
/// open folder selection dialog and save selected folder in persistent storage
Future<void> selectFolder() async {
Future<void> _selectFolder() async {
await Permission.manageExternalStorage.request();
String? selectedFolder = await FilePicker.platform.getDirectoryPath();
@ -55,12 +54,12 @@ class _LevelSelectionState extends State<LevelSelection> {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('stepmania_courses', selectedFolder);
loadFolderPath();
_loadFolderPath();
}
}
/// load all simfiles from a [directoryPath]
Future<List<Simfile>> listFilesAndFolders(String directoryPath) async {
Future<List<Simfile>> _listFilesAndFolders(String directoryPath) async {
final directory = Directory(directoryPath);
try {
// List all files and folders in the directory
@ -90,9 +89,9 @@ class _LevelSelectionState extends State<LevelSelection> {
}
/// filter stepmaniaCoursesFolders based on [input]
void filterLevels(String input) {
void _filterLevels(String input) {
setState(() {
stepmaniaCoursesFoldersFiltered = stepmaniaCoursesFolders
_stepmaniaCoursesFoldersFiltered = _stepmaniaCoursesFolders
.where((simfile) => simfile.tags["TITLE"]!
.toLowerCase()
.contains(input.toLowerCase()))
@ -119,9 +118,9 @@ class _LevelSelectionState extends State<LevelSelection> {
],
),
body: Builder(builder: (context) {
if (stepmaniaCoursesPath == null) {
if (_stepmaniaCoursesPath == null) {
return Text('Add a Directory with Stepmania Songs on \'+\'');
} else if (stepmaniaCoursesFolders.isEmpty) {
} else if (_stepmaniaCoursesFolders.isEmpty) {
return Text(
'Folder empty. Add Stepmania Songs to Folder or select a different folder on \'+\'');
} else {
@ -131,7 +130,7 @@ class _LevelSelectionState extends State<LevelSelection> {
padding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 0.0),
child: TextField(
onChanged: filterLevels,
onChanged: _filterLevels,
decoration: InputDecoration(
// icon: Icon(Icons.search),
hintText: 'Search'),
@ -139,11 +138,11 @@ class _LevelSelectionState extends State<LevelSelection> {
),
Expanded(
child: ListView.separated(
itemCount: stepmaniaCoursesFoldersFiltered.length,
itemCount: _stepmaniaCoursesFoldersFiltered.length,
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
itemBuilder: (context, index) {
Simfile simfile = stepmaniaCoursesFoldersFiltered[index];
Simfile simfile = _stepmaniaCoursesFoldersFiltered[index];
return LevelListEntry(simfile: simfile);
},
),
@ -154,7 +153,7 @@ class _LevelSelectionState extends State<LevelSelection> {
}),
floatingActionButton: FloatingActionButton(
onPressed: () {
selectFolder();
_selectFolder();
},
child: Icon(Icons.add)),
);

View file

@ -15,18 +15,17 @@ class ESenseInput {
ESenseManager eSenseManager = ESenseManager('unknown');
// valuenotifier allows widgets to rerender when the value changes
ValueNotifier<String> deviceStatus = ValueNotifier('Disconnected');
StreamSubscription? subscription;
StreamSubscription? _subscription;
String eSenseDeviceName = '';
bool connected = false;
bool sampling = false;
int sampleRate = 20;
final int _sampleRate = 20;
InputDirection inputDirection = InputDirection();
int x = 0;
int y = 0;
int z = 0;
final InputDirection _inputDirection = InputDirection();
int _x = 0;
int _y = 0;
int _z = 0;
ESenseInput._() {
_listenToESense();
@ -83,7 +82,6 @@ class ESenseInput {
break;
case ConnectionType.disconnected:
deviceStatus.value = 'Disconnected';
sampling = false;
_pauseListenToSensorEvents();
break;
case ConnectionType.device_found:
@ -107,7 +105,7 @@ class ESenseInput {
void _startListenToSensorEvents() async {
// // any changes to the sampling frequency must be done BEFORE listening to sensor events
print('setting sampling frequency...');
bool successs = await eSenseManager.setSamplingRate(sampleRate);
bool successs = await eSenseManager.setSamplingRate(_sampleRate);
if (successs) {
print('setSamplingRate success');
} else {
@ -115,19 +113,17 @@ class ESenseInput {
}
// subscribe to sensor event from the eSense device
subscription = eSenseManager.sensorEvents.listen((event) {
_subscription = eSenseManager.sensorEvents.listen((event) {
// print('SENSOR event: $event');
if (event.gyro != null) {
_parseGyroData(event.gyro!);
}
});
sampling = true;
}
/// cancels the sensorEvents listening
void _pauseListenToSensorEvents() async {
subscription?.cancel();
sampling = false;
_subscription?.cancel();
}
/// add up all new gyro [data] in the form of deg/s multiplied by scaling factor
@ -135,42 +131,42 @@ class ESenseInput {
void _parseGyroData(List<int> data) {
// Float value in deg/s = Gyro value / Gyro scale factor
// The default configuration is +- 500deg/s for the gyroscope.
x = (x + (15 * data[0] ~/ (500 * sampleRate))) % 360;
y = (y + (15 * data[1] ~/ (500 * sampleRate))) % 360;
z = (z + (15 * data[2] ~/ (500 * sampleRate))) % 360;
print('$x, $y, $z');
_x = (_x + (15 * data[0] ~/ (500 * _sampleRate))) % 360;
_y = (_y + (15 * data[1] ~/ (500 * _sampleRate))) % 360;
_z = (_z + (15 * data[2] ~/ (500 * _sampleRate))) % 360;
print('$_x, $_y, $_z');
// print('${(z.toDouble() / 500.0 * (1.0 / sampleRate.toDouble())) * 7.5}');
// print('${z.toDouble() / 500.0 * (1.0 / 10.0)}');
}
/// nulls all angles and reset inputDirection
void resetAngles() {
inputDirection.reset();
x = 0;
y = 0;
z = 0;
_inputDirection.reset();
_x = 0;
_y = 0;
_z = 0;
}
/// get InputDirection by checking if angels are in defined ranges and
/// calibrating based on the [expect]ed direction from ArrowDirection
InputDirection getInputDirection(ArrowDirection expect) {
// check if angle is in range
inputDirection.up = z > 180 && z < 340;
inputDirection.down = z > 20 && z < 180;
inputDirection.left = y > 0 && y < 180;
inputDirection.right = y > 180 && y < 360;
_inputDirection.up = _z > 180 && _z < 340;
_inputDirection.down = _z > 20 && _z < 180;
_inputDirection.left = _y > 0 && _y < 180;
_inputDirection.right = _y > 180 && _y < 360;
// calibrate based on expected directoin from ArrowDirection
if (expect == ArrowDirection.up && inputDirection.up ||
expect == ArrowDirection.down && inputDirection.down) {
y = 0;
if (expect == ArrowDirection.up && _inputDirection.up ||
expect == ArrowDirection.down && _inputDirection.down) {
_y = 0;
}
if (expect == ArrowDirection.left && inputDirection.left ||
expect == ArrowDirection.right && inputDirection.right) {
z = 0;
if (expect == ArrowDirection.left && _inputDirection.left ||
expect == ArrowDirection.right && _inputDirection.right) {
_z = 0;
}
return inputDirection;
return _inputDirection;
}
/// connect to ESense with [deviceName] by first asking for permissions

View file

@ -17,7 +17,7 @@ class ESenseConnectDialog extends StatefulWidget {
}
class _ESenseConnectDialogState extends State<ESenseConnectDialog> {
String eSenseDeviceName = '';
String _eSenseDeviceName = '';
@override
Widget build(BuildContext context) {
@ -31,7 +31,7 @@ class _ESenseConnectDialogState extends State<ESenseConnectDialog> {
TextField(
onChanged: (input) {
setState(() {
eSenseDeviceName = input;
_eSenseDeviceName = input;
});
},
decoration: InputDecoration(
@ -54,7 +54,7 @@ class _ESenseConnectDialogState extends State<ESenseConnectDialog> {
child: const Text('Disconnect'),
)
: TextButton(
onPressed: () => widget.connect(eSenseDeviceName),
onPressed: () => widget.connect(_eSenseDeviceName),
child: const Text('Connect'),
),
],

View file

@ -17,13 +17,13 @@ class LevelListEntry extends StatelessWidget {
final Simfile simfile;
/// navigates to level screen
void navigateToLevel(BuildContext context) {
void _navigateToLevel(BuildContext context) {
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) => Level(simfile)));
}
/// opens ESenseConnectDialog
void openESenseConnectDialog(context) {
void _openESenseConnectDialog(context) {
showDialog(
context: context,
builder: (BuildContext context) {
@ -41,19 +41,19 @@ class LevelListEntry extends StatelessWidget {
}
/// when clocked on the level, warn if not connected to ESense
void tapHandler(BuildContext context) {
void _tapHandler(BuildContext context) {
if (ESenseInput.instance.connected) {
navigateToLevel(context);
_navigateToLevel(context);
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return ESenseNotConnectedDialog(
onCancel: () {
openESenseConnectDialog(context);
_openESenseConnectDialog(context);
},
onContinue: () {
navigateToLevel(context);
_navigateToLevel(context);
},
);
},
@ -88,7 +88,7 @@ class LevelListEntry extends StatelessWidget {
),
),
onTap: () {
tapHandler(context);
_tapHandler(context);
},
);
}