如何在控制台中显示变量
本文关键字:显示 变量 控制台 | 更新日期: 2023-09-27 18:07:20
我正在尝试创造一款简单的主机游戏,你可以通过喂养自己来照顾自己。
using System;
namespace Project1
{
static class Program
{
static void Main(string[] args)
{
int hunger = 100;
Console.WriteLine("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Good choice, " + name);
Console.WriteLine("Press SPACE to continue");
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Spacebar))
{
// do something
int h = hunger - 2;
}
Console.WriteLine("You are hungry," + name);
Console.WriteLine("Press F to feed");
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.F))
{
// do something
int food = hunger;
}
}
}
}
如何在更改后显示当前饥饿?我想显示食物等级,这样玩家就知道该喂饱它,而不会意外地喂饱它。有没有可能有办法回到之前的那行这样我就不用一直复制粘贴了?谢谢。
看起来这个问题要回答得很宽泛,所以我将把它保留得很抽象。您需要在方法中放入可重用的逻辑。你需要一个"游戏循环"或"输入循环"。你需要了解变量并将它们传递给方法。
您还可能希望引入Player
类,而不是各种变量来保存单独的值。
你的游戏循环可能是这样的:
ConsoleKey input = null;
do
{
var player = DoGameLogic(input, player);
PrintGameInfo(player);
input = ReadInput(player);
}
while (input != ConsoleKey.Q)
当你把所有这些都整理好,并且你想让输出看起来不错时,看看使用Console在同一位置写字符串。用c# 2.0编写,. net中的高级控制台IO
您可以使用Console.CursorLeft
和Console.CursorTop
来修改光标的位置,并覆盖之前的值。
Cursor.Left = 0;
Console.Write("Hunger: {0:0.00}", hunger);
编辑:正如"CodeMaster"提到的,你可以这样做:
Console.Write("Test {0:0.0}".PadRight(20), hunger);
这是你想要实现的吗? -
static void Main(string[] args)
{
const int MAX_FEED_LEVEL = 3; //configure it as per your need
const int HIGHEST_HUNGER_LEVEL = 0; //0 indicates the Extreme hunger
int hunger = MAX_FEED_LEVEL, foodLevel = HIGHEST_HUNGER_LEVEL;
string name = string.Empty;
char finalChoice = 'N', feedChoice = 'N';
Console.Write("Enter your name: ");
name = Console.ReadLine();
Console.Write("Good choice, {0}!", name);
Console.WriteLine();
do
{
Console.WriteLine();
Console.WriteLine("current hunger level : {0}", hunger);
if (hunger > 0)
Console.WriteLine("You are hungry, {0}", name);
Console.Write("Press F to feed : ");
feedChoice = (char)Console.ReadKey(true).Key;
if (feedChoice == 'F' || feedChoice == 'f')
{
if (foodLevel <= MAX_FEED_LEVEL && hunger > HIGHEST_HUNGER_LEVEL)
{
hunger = hunger - 1; //decrementing hunger by 1 units
foodLevel += 1; //incrementing food level
Console.WriteLine();
Console.WriteLine("Feeded!");
Console.WriteLine("Current Food Level : {0}", foodLevel);
}
else
{
Console.WriteLine();
Console.WriteLine("Well Done! {0} you're no more hungry!", name);
goto END_OF_PLAY;
}
}
else
{
Console.Clear();
Console.WriteLine();
Console.Write("You chose not to feed !");
}
Console.WriteLine();
Console.Write("want to continue the game ? (Y(YES) N(NO))");
finalChoice = (char)Console.ReadKey(true).Key;
} while (finalChoice == 'Y' || finalChoice == 'y');
END_OF_PLAY:
Console.WriteLine();
Console.Write("===GAME OVER===");
Console.ReadKey();
}