我正在编写一个基于文本的冒险游戏,在该游戏中,我想从一种方法中使用的类访问另一种方法中的信息。我打算做的是将角色信息放在一个线程中,然后在游戏期间的任何时候都以类似于暂停菜单的方式将其打印到文本文档中。

我将在下面尝试写一个示例。

class Player
{
    public int health;
}

public class Program
{
    public static void Main(string[] args)
    {
        Player player = new Player();
        player.health = 20;
    }

    public static void method2()
    {
        //Here I want to access the "player" in the Main method.

        //Then I want to print this and other stats to a text document:
        string[] lines = { "Stat 1", "Stat 2", "Stat 3" };

         System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
        Process.Start(@"C:\Users\Public\TestFolder\WriteLines.txt");
    }
}

最佳答案

我建议将所有内容都从主游戏中剔除,然后制作一个包含玩家的游戏类。这样,您就可以在需要时访问播放器,而不必来回传递。您还可以在实例化播放器的状态时对其进行初始化。

public class Program
{
    public static void Main()
    {
        Game myGame = new Game();
        myGame.PlayGame();
    }
}
public class Game
{
    public Player myPlayer = new Player();

    public void PlayGame()
    {
        // place your loop / logic here to request input from the user and update your game state
    }

    public void WritePLayerStats()
    {
        string[] lines = { myPlayer.stat1, myPlayer.stat2 };

        File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

        Process.Start(@"C:\Users\Public\TestFolder\WriteLines.txt");
    }

}

public class Player
{
    public int health = 20;

    public string stat1 = "";

    public string stat2 = "";
}

10-06 05:53