1

在 c/c++ 语言中,conio.h头文件中有一个名为的函数,getch()它允许您仅输入 1 个字符,并且不会在屏幕上回显它,一旦键入该字符,它会自动转到下一行代码,而无需必须按回车。

我试过使用stdin.readByteSync()in dart,但它没有给我getch()在 c/c++ 中提供的功能。我想知道是否有一种方法可以在 dart 中创建一个函数或方法,其行为方式与getch()c/c++ 中的行为方式相同。谢谢你。

4

2 回答 2

1

您只需将以下选项设置为 false: https ://api.dart.dev/stable/2.8.2/dart-io/Stdin/lineMode.html

如果您使用的是 Windows,您还需要根据文档首先将以下内容设置为 false: https ://api.dart.dev/stable/2.8.2/dart-io/Stdin/echoMode.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();
}
于 2020-05-15T16:30:03.083 回答
0

谢谢大家的贡献。但是添加到我得到的答案是这样的

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、powershell 和 linux 终端,而不适用于 intelliJ,但总比没有好。最重要的是为flutter和web之类的东西打下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);
}

您可以继续前进,使其成为一种方式,当用户再次开始游戏时,它应该显示不同的文本,这样他们就不会习惯它。但无论如何,这就是这个问题。它正式关闭。虽然,如果您还有要添加的内容,请随时将其放在这里。谢谢!

于 2020-05-16T16:06:41.947 回答