简体   繁体   中英

How do I move coordinates [x,y] from a 2D array to the right? c#

Hello so recently I have been given an assignment to create a small game, but see I have ran into a problem. When I try to move my Player who starts out at a set position he will shift to the right once but it seems he is still locked at the starting spot and upon entering the number to shift him right again, the same answer(coordinates I have printed out) are the same and game board is also the same. https://gyazo.com/9f23419a3300232d3f3d9e1168202cf3

    public string player(int movement)
    {
        int playerX = map.GetLength(0)-3; //rows
        int playerY = map.GetLength(1)-25; //columns

        if (movement == 8)
        {
            playerX--;
            map[playerX, playerY] = "P";
            Console.WriteLine("The player is located at: " + playerX +","+ playerY);
        }
        else if (movement == 6)
        {
            playerY++;
            map[playerX, playerY] = "P";
            Console.WriteLine("The player is located at: " + playerX + "," + playerY);
        }
        else if (movement == 2)
        {
            playerX++;
            map[playerX, playerY] = "P";
            Console.WriteLine("The player is located at: " + playerX + "," + playerY);
        }
        else if (movement == 4)
        {
            playerY--;
            map[playerX, playerY] = "P";
            Console.WriteLine("The player is located at: " + playerX + "," + playerY);
        }  
        else
        {
            map[playerX,playerY] = "P";
        }
        return "";
    }

Every time you call the player method, the position is the same because you are using local variables to store the position.

What I assume you want is to use a global variable, and set the position when the game starts.

Move the variable declarations outside of your method: (Put these inside the class but not inside the method)

int playerX, playerY;

Set the position when the map is created.

map = // Something
playerX = map.GetLength(0)-3; //rows
playerY = map.GetLength(1)-25; //columns

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