c# - 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
任何帮助,将不胜感激
解决方案
您可以尝试的一种方法是创建一个 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);
}
希望你能明白
推荐阅读
- google-sheets - 将 IMPORTDATA() 与来自谷歌存储桶的对象一起使用
- c++ - 对 OpenMP 缩减子句中的变量进行原子操作
- javascript - 使用 javascript 为现有表单字段添加值
- google-chrome - WebRTC:检测 P2P 呼叫中远程对等点的流类型(视频/屏幕)
- python - 通过巧妙的导入管理 Python 模块依赖项
- python - Python:在不更改 csv 文件的情况下将列添加到加载的 csv 文件
- python-3.x - 如何计算多维列表中的重复项
- xml - 从具有相似块的 XML 文件中提取数据
- python - 在底图中部分填充 shapefile 多边形
- c# - 如何在代码后面和不可见时为数据网格单元格着色