在cc++语言中,有一个函数是在 conio.h
头文件,称为 getch()
它只让你输入一个字符,并且不在屏幕上呼应,一旦输入了这个字符,它就会自动进入下一行代码,而不需要按回车键。
我试过用 stdin.readByteSync()
的功能,但它并没有给我提供 getch()
cc++中给出的函数。我想知道是否有办法在dart中建立一个函数或方法,其行为方式与 getch()
在cc++中是这样的。谢谢你。
你只需要将以下选项设置为false即可。https:/api.dart.devstable2.8.2dart-ioStdinlineMode.html。
如果你使用的是Windows,你还需要根据文档先将以下设置为false。https:/api.dart.devstable2.8.2dart-ioStdinechoMode.html。
一个简单的工作例子,只是重复你输入的内容,可以这样做。它不能在IntelliJ内部工作,但可以在CMD、PowerShell和Linux bash中工作。
import 'dart:convert';
import 'dart:io';
void main() {
stdin.echoMode = false;
stdin.lineMode = false;
stdin.transform(utf8.decoder).forEach((element) => print('Got: $element'));
}
通过这样做,我们也可以做你自己的建议,并使用... ... stdin.readByteSync()
(只是注意,如果你得到UTF-8的输入,一个字符可以包含多个字节。
import 'dart:io';
void main() {
print(getch());
}
int getch() {
stdin.echoMode = false;
stdin.lineMode = false;
return stdin.readByteSync();
}
谢谢大家的贡献。然而补充到我得到的答案是这样的
import 'dart:io';
void main() {
print(getch());
}
int getch() {
stdin.echoMode = false;
stdin.lineMode = false;
return stdin.readByteSync();
}
我决定添加一些东西,让它更像c语言中conio.h头文件中的getch()函数。代码是这样的
import 'dart:io';
void main() {
print(getch());
}
String getch() {
stdin.echoMode = false;
stdin.lineMode = false;
int a = stdin.readByteSync();
return String.fromCharCode(a);
}
虽然只能在cmd、powerhell和linux终端上使用,不能在intelliJ上使用,但聊胜于无。最重要的是,对于flutter和web这样的东西,要打好dart的基础。而有了这些小知识,我是把它付诸实践,用dart做了一个简单而基本的打字游戏。代码如下。
import 'dart:io';
import 'dart:convert';
import 'dart:core';
void main() {
Stopwatch s = Stopwatch();
String sentence = 'In the famous battle of Thermopylae in 480 BC, one of the most famous battles in history, King Leonidas of Sparta said the phrase'
' Molon Labe which means \"come and take them\" in ancient greek to Xerxes I of Persia when the Persians asked the Spartans to lay'
' down their arms and surrender.';
List<String> sentenceSplit = sentence.split(' ');
int wordCount = sentenceSplit.length;
print('Welcome to this typing game. Type the words you see on the screen below\n\n$sentence\n\n');
for (int i=0; i<sentence.length; i++) {
if(i==1) {
s.start(); // start the timer after first letter is clicked
}
if(getch() == sentence[i]) {
stdout.write(sentence[i]);
}
else {
i--;
continue;
}
}
s.stop(); // stop the timer
int typingSpeed = wordCount ~/ (s.elapsed.inSeconds/60);
print('\n\nWord Count:\t$wordCount words');
print('Elapsed time:\t${s.elapsed.inSeconds} seconds');
print('Typing speed:\t$typingSpeed WPM');
}
String getch() {
stdin.echoMode = false;
stdin.lineMode = false;
int a = stdin.readByteSync();
return String.fromCharCode(a);
}
你可以继续前进,使它成为一种方式,当用户再次启动游戏时,它应该显示不同的文本,这样他们就不会习惯了。但无论如何,这个问题就到此为止了。正式结束了。不过,如果你还有什么要补充的,欢迎在这里留言。谢谢大家