Winforms C#垄断-在木板上移动播放器

时间:2018-12-17 16:58:15

标签: c# winforms

我正在尝试使用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之后的数字,也许像这样;

pictureBox(playerPosition).Location 

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

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

向玩家类添加一个属性,以跟踪它们是什么正方形,并将该位置与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);

}

希望您能理解

答案 1 :(得分:0)

我设法找到了一种简单的方法,尽管这只是为一个玩家设置的,所以将来我需要对其进行调整。

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

        Control[] pB = this.Controls.Find("pictureBox" + (playerPosition + 1).ToString(), true);

        playerIcon1.Location = pB[0].Location;
        player1Offset();
    }