Skip to content

Commit

Permalink
argument handling in Context
Browse files Browse the repository at this point in the history
  • Loading branch information
Stevertus committed Jan 6, 2024
1 parent 11010ff commit 4a54181
Show file tree
Hide file tree
Showing 9 changed files with 208 additions and 43 deletions.
7 changes: 5 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

## 0.4.6

- added UUID object to represent uuids consisting out of 4 integers
- added arguments methods on context to generate macro commands introduced in 1.20.2
- added serializable UUID object to represent uuids consisting out of 4 integers
- added Random Widget
- added Return.run and Return.fail subcommands
- added arguments field for File.execute to run functions with arguments
- updated blocks, items, particles and entities to include content from 1.20.4 and 23w51b
- changed TextComponent & Entity to be gson serializable, so you don't have to call toMap manually
- refactored Title widget
- fixed function tags load/tick generating with paths with `.mcfunction`
- fixed Storage.copyScore ignoring the scale parameter
- fixed Entity to introduce a trailing comma when given empty tags
- fixed Github testing workflows to run with Dart 3
- fixed Github testing workflows to run with Dart 3 and provide Code Coverage

## 0.4.5

Expand Down
9 changes: 9 additions & 0 deletions lib/src/basic/command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ class Command extends RestActionAble {
}
@override
Widget generate(Context context) {
if (context.macros.isNotEmpty &&
context.macros.entries
.any((element) => _command.contains(element.key))) {
_command = '\$${context.macros.entries.where((e) => e.value != null).fold(
_command,
(command, entry) =>
command.replaceAll(entry.key, '\${${entry.value}}'),
)}';
}
return Text(_command);
}

Expand Down
46 changes: 23 additions & 23 deletions lib/src/basic/score.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class Score extends RestActionAble {
);
}

String _getESStr({Entity? entity, String? score}) {
String toString({Entity? entity, String? score}) {
entity ??= this.entity;
score ??= this.score;
return '$entity $score';
Expand Down Expand Up @@ -245,7 +245,7 @@ class Score extends RestActionAble {
Score set(int val) {
return addCommandRet(
Command(
'scoreboard players set ${_getESStr()} $val',
'scoreboard players set ${toString()} $val',
),
);
}
Expand All @@ -254,7 +254,7 @@ class Score extends RestActionAble {
Score reset() {
return addCommandRet(
Command(
'scoreboard players reset ${_getESStr()}',
'scoreboard players reset ${toString()}',
),
);
}
Expand All @@ -263,7 +263,7 @@ class Score extends RestActionAble {
Score add([int val = 1]) {
return addCommandRet(
Command(
'scoreboard players add ${_getESStr()} $val',
'scoreboard players add ${toString()} $val',
),
);
}
Expand All @@ -272,7 +272,7 @@ class Score extends RestActionAble {
Score subtract([int val = 1]) {
return addCommandRet(
Command(
'scoreboard players remove ${_getESStr()} $val',
'scoreboard players remove ${toString()} $val',
),
);
}
Expand All @@ -281,7 +281,7 @@ class Score extends RestActionAble {
Score get() {
return addCommandRet(
Command(
'scoreboard players get ${_getESStr()}',
'scoreboard players get ${toString()}',
),
);
}
Expand All @@ -300,7 +300,7 @@ class Score extends RestActionAble {
Score swapWith(Score score) {
return addCommandRet(
Command(
'scoreboard players operation ${_getESStr()} >< ${_getESStr(entity: score.entity, score: score.score)}',
'scoreboard players operation ${toString()} >< ${toString(entity: score.entity, score: score.score)}',
),
);
}
Expand All @@ -327,7 +327,7 @@ class Score extends RestActionAble {
Score addScore(Score score) {
return addCommandRet(
Command(
'scoreboard players operation ${_getESStr()} += ${_getESStr(entity: score.entity, score: score.score)}',
'scoreboard players operation ${toString()} += ${toString(entity: score.entity, score: score.score)}',
),
);
}
Expand All @@ -336,7 +336,7 @@ class Score extends RestActionAble {
Score subtractScore(Score score) {
return addCommandRet(
Command(
'scoreboard players operation ${_getESStr()} -= ${_getESStr(entity: score.entity, score: score.score)}',
'scoreboard players operation ${toString()} -= ${toString(entity: score.entity, score: score.score)}',
),
);
}
Expand All @@ -345,7 +345,7 @@ class Score extends RestActionAble {
Score multiplyByScore(Score score) {
return addCommandRet(
Command(
'scoreboard players operation ${_getESStr()} *= ${_getESStr(entity: score.entity, score: score.score)}',
'scoreboard players operation ${toString()} *= ${toString(entity: score.entity, score: score.score)}',
),
);
}
Expand All @@ -354,7 +354,7 @@ class Score extends RestActionAble {
Score divideByScore(Score score) {
return addCommandRet(
Command(
'scoreboard players operation ${_getESStr()} /= ${_getESStr(entity: score.entity, score: score.score)}',
'scoreboard players operation ${toString()} /= ${toString(entity: score.entity, score: score.score)}',
),
);
}
Expand All @@ -363,7 +363,7 @@ class Score extends RestActionAble {
Score modulo(Score score) {
return addCommandRet(
Command(
'scoreboard players operation ${_getESStr()} %= ${_getESStr(entity: score.entity, score: score.score)}',
'scoreboard players operation ${toString()} %= ${toString(entity: score.entity, score: score.score)}',
),
);
}
Expand All @@ -376,7 +376,7 @@ class Score extends RestActionAble {
return addCommandRet(
Builder(
(c) => Command(
'execute store result score ${_getESStr()} run data get ${data.getTarget(c)} ${data.path} ${data.scale ?? 1}',
'execute store result score ${toString()} run data get ${data.getTarget(c)} ${data.path} ${data.scale ?? 1}',
),
),
);
Expand All @@ -389,7 +389,7 @@ class Score extends RestActionAble {
Score setToResult(Command commmand, {bool useSuccess = false}) {
return addCommandRet(
Command(
'execute store ${useSuccess ? 'success' : 'result'} score ${_getESStr()} run $commmand',
'execute store ${useSuccess ? 'success' : 'result'} score ${toString()} run $commmand',
),
);
}
Expand All @@ -399,7 +399,7 @@ class Score extends RestActionAble {
Group setToWidget(Widget widget, {bool useSuccess = false}) {
return Group(
prefix:
'execute store ${useSuccess ? 'success' : 'result'} score ${_getESStr()} run',
'execute store ${useSuccess ? 'success' : 'result'} score ${toString()} run',
children: [widget],
);
}
Expand All @@ -408,7 +408,7 @@ class Score extends RestActionAble {
Score setToCondition(Condition cond, {bool useSuccess = false}) {
return addCommandRet(
Command(
'execute store ${useSuccess ? 'success' : 'result'} score ${_getESStr()} ${Condition.getPrefixes(cond.getList())[0]}',
'execute store ${useSuccess ? 'success' : 'result'} score ${toString()} ${Condition.getPrefixes(cond.getList())[0]}',
),
);
}
Expand Down Expand Up @@ -453,45 +453,45 @@ class Score extends RestActionAble {
Score isEqual(Score score) {
return Score.str(
'${_getESStr()} = ${_getESStr(entity: score.entity, score: score.score)}',
'${toString()} = ${toString(entity: score.entity, score: score.score)}',
);
}

Score isSmaller(Score score) {
return Score.str(
'${_getESStr()} < ${_getESStr(entity: score.entity, score: score.score)}',
'${toString()} < ${toString(entity: score.entity, score: score.score)}',
);
}

Score isSmallerOrEqual(Score score) {
return Score.str(
'${_getESStr()} <= ${_getESStr(entity: score.entity, score: score.score)}',
'${toString()} <= ${toString(entity: score.entity, score: score.score)}',
);
}

Score isBiggerOrEqual(Score score) {
return Score.str(
'${_getESStr()} >= ${_getESStr(entity: score.entity, score: score.score)}',
'${toString()} >= ${toString(entity: score.entity, score: score.score)}',
);
}

Score isBigger(Score score) {
return Score.str(
'${_getESStr()} > ${_getESStr(entity: score.entity, score: score.score)}',
'${toString()} > ${toString(entity: score.entity, score: score.score)}',
);
}

String _match = '0';
String getMatch() => _match;
Score matches(int value) {
_match = value.toString();
return Score.str('${_getESStr()} matches $_match',
return Score.str('${toString()} matches $_match',
score: score, match: _match);
}

Score matchesRange(Range range) {
_match = range.toString();
return Score.str('${_getESStr()} matches $_match',
return Score.str('${toString()} matches $_match',
score: score, match: _match);
}

Expand Down
16 changes: 4 additions & 12 deletions lib/src/basic/types/item.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:gson/gson.dart';
import 'package:objd/src/basic/widgets.dart';
import 'package:objd/src/wrappers/summon.dart';
import 'package:deep_collection/deep_collection.dart';

export 'items.dart';

Expand Down Expand Up @@ -249,7 +250,9 @@ class Item {
List<TextComponent>? lore,
Map<String, dynamic>? nbt,
}) {
final t = tag != null ? _copyDeepMap(tag) : <String, dynamic>{};
final t = tag != null
? tag!.deepCopy().cast<String, dynamic>()
: <String, dynamic>{};

Check warning on line 255 in lib/src/basic/types/item.dart

View check run for this annotation

Codecov / codecov/patch

lib/src/basic/types/item.dart#L253-L255

Added lines #L253 - L255 were not covered by tests
_checkTags(model, type, hideFlags, name, lore, nbt, t);

return Item(
Expand Down Expand Up @@ -356,17 +359,6 @@ class BookPage {
}
}

Map<String, dynamic> _copyDeepMap(Map<String, dynamic>? map) {
final newMap = <String, dynamic>{};

map?.forEach((key, value) {
newMap[key] =
(value is Map) ? _copyDeepMap(value.cast<String, dynamic>()) : value;
});

return newMap;
}

class UUID extends GsonValue {
final int i1;
final int i2;
Expand Down
91 changes: 90 additions & 1 deletion lib/src/build/context.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import 'dart:math';

import 'package:gson/values.dart';
import 'package:objd/src/basic/score.dart';
import 'package:objd/src/basic/types/entity.dart';
import 'package:objd/src/basic/types/location.dart';

/// Maybe you already wondered what this context argument here is.
///
/// The Context is a way to get certain important information from the parents.
Expand Down Expand Up @@ -27,6 +34,7 @@ class Context {
double version;
Path path;
final Map<Type, dynamic> _heredityTraits;
final Map<String, String?> macros;

/// Maybe you already wondered what this context argument here is
/// The Context is a way to get certain important information from the parents.
Expand All @@ -50,8 +58,10 @@ class Context {
this.mainFile = 'main',
this.version = 20.4,
this.path = const Path([]),
Map<String, String?>? macros,
Map<Type, dynamic>? traits,
}) : _heredityTraits = traits ?? {};
}) : _heredityTraits = traits ?? {},
macros = macros ?? {};

Context.clone(Context context)
: this(
Expand All @@ -63,6 +73,7 @@ class Context {
loadFile: context.loadFile,
mainFile: context.mainFile,
traits: context._heredityTraits,
macros: Map.of(context.macros),
version: context.version,
path: context.path.copyWith(),
);
Expand Down Expand Up @@ -91,6 +102,84 @@ class Context {
T traitOf<T>() {
return (_heredityTraits[T] as T);
}

String stringArgument(String name) {
macros['\${$name}'] = name;
return '\${$name}';
}

int intArgument(String name) {
int i = 0;
const limit = 0x3FFFFFFF;
do {
i = Random().nextInt(limit) + limit;
} while (macros.containsKey(i.toString()));
macros[i.toString()] = name;
return i;
}

double doubleArgument(String name) {
return buildArgument(
name,
(d) => (d, Double(d).toString()),
replaceDouble: true,
);
}

Entity entityArgument(String name) {
return buildArgument(
name,
(d) => (Entity(level: Range.exact(d)), null),
);
}

Score scoreArgument(String name) {
return buildArgument(
name,
(d) {
return (
Score(Entity(level: Range.to(d)), d.toString(), addNew: false),
null
);
},
);
}

Location locationArgument(String name) {
return buildArgument(
name,
(d) => (Location.local(x: d, y: d, z: d), null),
);
}

T buildArgument<T>(
String name,
(T, String?) Function(double) builder, {
bool replaceDouble = false,
}) {
double num = 0;
late T t;
String? str;
do {
num = (Random().nextDouble() * 2 - 1) * double.maxFinite / 2;
(t, str) = builder(num);
} while (macros.containsKey(str ?? t.toString()) ||
macros.containsKey(num.toString()));

macros[str ?? t.toString()] = name;
macros[num.toString()] = replaceDouble ? name : null;
return t;
}

T argument<T>(String name) => switch (T) {
const (String) => stringArgument(name) as T,
const (int) => intArgument(name) as T,
const (double) => doubleArgument(name) as T,
const (Score) => scoreArgument(name) as T,
const (Entity) => entityArgument(name) as T,
const (Location) => locationArgument(name) as T,
_ => throw ArgumentError('Unsupported argument type $T'),

Check warning on line 181 in lib/src/build/context.dart

View check run for this annotation

Codecov / codecov/patch

lib/src/build/context.dart#L181

Added line #L181 was not covered by tests
};
}

// A simple utility to collect path segments and generate a String
Expand Down
Loading

0 comments on commit 4a54181

Please sign in to comment.