首页 > 解决方案 > Winforms C# Monopoly - 在棋盘上移动玩家

问题描述

我正在尝试使用 Winforms 在 C# 中创建一个垄断游戏,我需要处理在棋盘上移动的玩家图标。

我正在考虑这样做;

    private void movePlayerToNewSquare(int playerPos)
    {
        int playerPosition = playerPos;

        switch (playerPosition)
        {
            case 0:
                playerIcon1.Location = pictureBox1.Location;
                break;
            case 1:
                playerIcon1.Location = pictureBox2.Location;
                break;

playerPos 来自较早的函数,是一个从 0 到 39 的整数,它们在棋盘上的位置是棋盘上所有方格列表中的那个数字,即 0 = “Go”,1 = “Old Kent Road”等。我正在考虑为板上的每个方格设置一个不同的案例。但这似乎是一种冗长的做事方式。

我想知道在 C# 中是否有一种方法可以使用 playerPosition 整数作为图片框后面的数字,可能类似于;

pictureBox(playerPosition).Location 

任何帮助,将不胜感激

标签: c#winforms

解决方案


您可以尝试的一种方法是创建一个 GameSquare 类并从 PictureBox 继承。然后在 GameSquare 中创建一个 Id 属性,生成一个 ID 为 1 - 40 的 Gamesquares 列表。

向您的玩家类添加一个属性以跟踪它们是什么正方形并将位置与 GameSqaure 位置匹配。像这样的东西:

public class Player : PictureBox
{
    public int id { get; set; }
    public string name { get; set; }
    public int currentGameSquare { get; set; }
    //etc, etc
}
public class GameSquare : PictureBox
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Value { get; set; }
    //etc..etc.     
}

 public class Game
{
   private List<GameSquare> gameBoard;
   private Player p;

    //you're going to populate square values and title somewhere else in your code.
    Dictionary<string, int> squareValues = new Dictionary<string, int>();

    public Game()
    {
        gameBoard = new List<GameSquare>();
        p = new Player();

        GenerateGameBoard(40);
    }

   public void GenerateGameBoard(int numSquares)
   {
       for (int i = 0; i < gameBoard.Count(); i++)
        {
            GameSquare s = new GameSquare()
            {
                Id = i,
                Name = gameBoard.ElementAt(i).Key
                Value = gameBoard.ElementAt(i).Value
                Location = new Point(someX, someY)  //however your assigning the board layout
                //Assign the rest of the properties however you're doing it
            };
            gameBoard.Add(s);
        }
    }
}

现在,当玩家滚动时,您可以执行以下操作:

Random r = new Random();

int[] dice = new int[2];
dice[0] = r.Next(1,6);
dice[1] = r.Next(1,6);
movePlayertoNewSquare(dice);

private void movePlayerToNewSquare(int[] diceroll)
{
    p.currentGameSquare += diceroll.Sum();
    //You would need logic to determine if the player passed go and account for that

    p.Location = gameBoard.Where(x => x.id == p.currentGameSquare).Single().Location);

}

希望你能明白


推荐阅读