我正在尝试在 Dart 中制作一个简单的 RPG。我需要在 div 的屏幕上显示文本,并且我需要让程序在显示下一段文本之前等待用户输入。
例如:
void main() {
showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
print("showText has finished");
}
Run Code Online (Sandbox Code Playgroud)
"showText has finished"在显示文本并且玩家按下回车键之前不应显示。这是我到目前为止的(在我看来很丑陋)代码:
void showText(String text) {
var textBox = querySelector("#sample_text_id")
..text = "";
var timer;
var out;
out = ([int i = 0]) {
textBox.text += text[i];
if (i < text.length - 1) timer = new Timer(const Duration(milliseconds: 10), () => out(i + 1));
};
out();
}
Run Code Online (Sandbox Code Playgroud)
Timerout()异步运行该函数,我不希望它这样做。理想情况下,我想写这样的东西:
void showText(String text) {
var textBox = querySelector("#sample_text_id")
..text = "";
for(int i = 0; i < text.length; i++) {
textBox.text += text[i];
pause(const Duration(milliseconds: 10)); // pause the program for given duration
}
waitFor(KeyEnum.ENTER, KeyStateEnum.DOWN); // pause until key is pressed (pseudo Enum contains char codes)
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?
以下是如何使用新的 async/await 功能执行此操作的示例。注意方法主体开始处的异步声明,以及调用 pause() 和 showText() 之前的 await 语句。
Future pause(Duration d) => new Future.delayed(d);
Future waitFor(int c) => document.body.onKeyDown.firstWhere((e) => e.keyCode == c);
Future showText(String text) async {
var textBox = querySelector("#sample_text_id")
..text = "";
for(int i = 0; i < text.length; i++) {
textBox.text += text[i];
await pause(const Duration(milliseconds: 100)); // pause the program for given duration
}
return waitFor(KeyCode.ENTER); // pause until key is pressed
}
main() async {
await showText("Hello, Adventurer! Welcome to the land of Dartia! (Press ENTER to continue...)");
print("showText has finished");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3736 次 |
| 最近记录: |