0

I am making a tic-tac-toe game in C#. I have a string variable for each square. I want to make it so the user inputs the square name i.e. (topMiddle). Then I declare the input playerInput. I want to use str.Replace(' ', 'x'); but instead of str I would use the name of the box i.e.(topMiddle). How would I retrieve that variable using the console input?

Here is my code so far:

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);

Sorry if my code is messy and my problem is a simple fix. This is my fourth-day using c# so I still have a lot to learn.

1
  • 2
    Number your squares 1 through 9, and have the user enter the number 2 instead of "topMiddle". Easier for everyone. Mar 26, 2016 at 14:57

1 Answer 1

-2

You will need to write an if statement to ensure you select the correct variable name using the user's input. In your question you state the ReadLine() is stored in a playerInput variable but your code sample shows two variables named xInput and oInput. For the sake of keeping this simple my answer uses the single playerInput variable you mention in your question. For example:

if (playerInput == "topLeft")
{ 
   topLeft = "X";
}
else if (playerInput == "topMiddle")
{
   topMiddle = "X";
}
...
else if (playerInput == "bottomRight")
{
   bottomRight = "X";
}

This is how you can ensure the correct variable is updated in your program. There are definitely more elegant ways to implement your tic tac toe game than the approach you've taken here, so after you get this working, consider reiterating to make the code cleaner.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.