gpt4 book ai didi

C# - 控制台如何获取每一帧的输入

转载 作者:行者123 更新时间:2023-11-30 20:35:07 25 4
gpt4 key购买 nike

所以,我很无聊,决定用 C# 编写一个 ASCII 游戏来玩一玩,我有绘图、清除、更新等。虽然,我卡在了一个部分,输入。我想在每一帧都获得输入,而无需玩家按下回车键,到目前为止,玩家必须按下回车键,但它什么也没做。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace ASCII
{
public static class Game
{
static string map = File.ReadAllText("Map.txt");
public static void Draw()
{
Console.CursorVisible = false;
Console.WriteLine(map);
}

public static void Update()
{
Clear();
Input();
}

public static void Input()
{
string input = Console.ReadLine();

switch (input)
{
case "a":
//Do something
break;
}
}

public static void Clear()
{
Console.Clear();
Draw();
}
}
}

正如您在 Input() void 中看到的那样,它在每一帧都获得输入,但我只想获得一次,执行移动方法或稍后我将实现的方法。

BTW Map.txt 显示这个:

###################

##

#@##

#########

##

##

##

##

##

##

##

###################

最佳答案

Console.ReadLine 将等待回车键继续使应用程序成为模态。相反,您想要的是在控制台上处理键盘事件。因此,您可以改用 ReadKey:

var input = Console.ReadKey(true);

switch (input.Key)
{
case ConsoleKey.A:
//Do something
break;
}

要坚持移动,您可以在循环中实现它。这里的关键是记住您当前的操作,直到下一个关键事件通过

int action = 0;
while(!exit)
{
// handle the action
myPlayer.X += action; // move player left or right depending on the previously pressed key (A or D)

if(!Console.KeyAvailable) continue;
var input = Console.ReadKey(true);

switch (input.Key)
{
case ConsoleKey.A:
action = -1
break;
case ConsoleKey.D:
action = 1
break;
}
}

关于C# - 控制台如何获取每一帧的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com