我正在C#做一个抽搐脚趾游戏。每个方格都有一个字符串变量。我想要这样做,这样用户就可以输入正方形名称,即(topMiddle)。然后声明输入playerInput。我想使用str.Replace(‘','x');但是,我使用的不是str,而是框的名称,即(TopMiddle)。如何使用控制台输入检索该变量?
到目前为止,我的代码如下:
using System;
namespace TicTac_toe
{
public class CreateVariables
{
public static void Main (string[] args)
{
string topRight = " ";
string topMiddle = " ";
string topLeft = " ";
string middleLeft = " ";
string center = " ";
string middleRight = " ";
string bottomLeft = " ";
string bottomMiddle = " ";
string bottomRight = " ";
string line = "|";
string dash = "_ _ _";
string xInput;
string oInput;
bool player1;
System.Console.WriteLine (topLeft + line + topMiddle + line + topRight + "\n" + dash + "\n" + "\n" + middleLeft + line + center + line + middleRight + "\n" + dash + "\n" + "\n" + bottomLeft + line + bottomMiddle + line + bottomRight);
System.Console.WriteLine ("Player 1, it is your turn. WHat box will you mark?");
xInput = System.Console.ReadLine ();
topRight = xInput.Replace (' ', 'X');
System.Console.Clear ();
System.Console.WriteLine (topLeft + line + topMiddle + line + topRight + "\n" + dash + "\n" + "\n" + middleLeft + line + center + line + middleRight + "\n" + dash + "\n" + "\n" + bottomLeft + line + bottomMiddle + line + bottomRight);对不起,如果我的代码混乱,我的问题是一个简单的修复。这是我使用c#的第四天,所以我还有很多东西要学。
发布于 2016-03-26 19:26:47
您需要编写一个if语句,以确保使用用户的输入选择正确的变量名。在您的问题中,您可以声明ReadLine()存储在一个playerInput变量中,但是您的代码示例显示了两个名为xInput和oInput的变量。为了保持这个简单,我的答案使用了您在问题中提到的单个playerInput变量。例如:
if (playerInput == "topLeft")
{
topLeft = "X";
}
else if (playerInput == "topMiddle")
{
topMiddle = "X";
}
...
else if (playerInput == "bottomRight")
{
bottomRight = "X";
}这就是如何确保在程序中更新正确的变量的方法。与您在这里采用的方法相比,实现tic toe游戏的方法肯定更优雅,因此,在完成此工作之后,请考虑重申以使代码更简洁。
https://softwareengineering.stackexchange.com/questions/313910
复制相似问题