简体   繁体   中英

Replacing specific values in a string array

my goal for this program is to create a grid where a user navigates through it. I have so far created the grid but I am stuck on how to have it so that at any location of the array string[3,6] i can replace one of the "-" with the player symbol "P" and that every time the player moves the console will print the location of the player.

EG. i want player to start at string[2,5], the the "-" would be replaced with a "P", and that after the player moves the "-" at [2,5] returns.

But my primary focus is to find out how to replace any point of the array with the player.

Hopefully it is clear

string[,] table = new string[3,6] { {"-","-","-","-","-","-"},
                                    {"-","-","-","-","-","-"},
                                    {"-","-","-","-","-","-"}}; 
int rows = grid.GetLength(0);
        int col = grid.GetLength(0);

        for (int x = 0; x < rows; x++) 
        {
            for (int y = 0; y < col; y++) 
            {
                Console.Write ("{0} ", grid [x, y]);
            }
            Console.Write (Environment.NewLine + Environment.NewLine);
        }

i have tried using .Replace but have had no success so far

I'd do something like this:

private static int playerX, playerY;
public static void MovePlayer(int x, int y)
{
     table[playerX, playerY] = "-"; //Remove old position
     table[x, y] = "P"; //Update new position
     playerX = x; //Save current position
     playerY = y;

     UpdateGrid();
}

All you have to do is set the element to "P" to change it, nothing fancy.

To update your grid you have two options, to either re-draw everything, or to set the cursor position and change the character.

Example:

SetCursorPosition(playerX, playerY);
Console.Write("-");
SetCursorPosition(x, y);
Console.Write("P");

Or, use the code you have now to call it again to re-write everything.

另一种方法是通过使用Console.SetCursorPosition()将玩家吸引到正确的位置-有关示例,请参阅我的博客文章

As an alternative you could drop the grid altogether:

Point playerLocation = new Point(10, 10);
Size boundary = new Size(20, 20);

void Draw()
{
    for (int y = 0; y < boundary.Height; y++)
        for (int x = 0; x <= boundary.Width; x++)
            Console.Write(GetSymbolAtPosition(x, y));
}

string GetSymbolAtPosition(int x, int y)
{
    if (x >= boundary.Width)
        return Environment.NewLine;

    if (y == playerLocation.Y && x == playerLocation.X)
        return "P";

    return "-";
}

This way you won't have to update the grid in order to update the screen. When you change the player's position it will update the screen on next draw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM