gpt4 book ai didi

c# - 为扫雷游戏动态创建一个游戏板

转载 作者:行者123 更新时间:2023-11-30 15:36:37 25 4
gpt4 key购买 nike

为了学习 C#、XAML,尤其是 MVVM,我开始编写扫雷游戏。我制作的第一个版本没有 MVVM 部分,我在其中使用 C# 代码创建并添加了按钮,而不是通过 MVVM 方式在 XAML 中进行操作。现在我尝试将 MVVM 模式应用到游戏中。

我制作了一个自己的用户控件,其中包含一个代表雷区部分的按钮。这个控件还有一个 ViewModel 和一个 Model 类来存储一些状态数据和处理一些命令。在一个测试项目中,我创建了 4 个自己的用户控件,并尝试将它们放在一个网格中,其中按钮形成一个 2 x 2 按钮的正方形。在后面的代码中,按钮被放在一个 ObservableCollection 对象中。我假设在此对象中,按钮的列出和索引如下:

Button1
Button2
Button3
Button4

但在演示网格中,我希望按钮显示为

Button1 | Button2
--------+--------
Button3 | Button4

问题是:我如何动态地做到这一点?因为在我的测试项目中,我测试了 4 个按钮,但在我想使用它的项目中,按钮的数量可能会有所不同,具体取决于玩家选择的游戏难度。

第二个问题是我如何弄清楚按钮的邻居是什么。因此,如果网格是 4 x 5,包含 20 个按钮。例如,我选择按钮 8,它的相邻按钮编号为 2、3、4、7、9、12、13 和 14。列出这些按钮后,我如何才能到达这些相邻按钮?

我希望我的问题足够清楚。

提前致谢!

最佳答案

您可以使用 ItemsControl 显示您的收藏有它的 ItemsPanel设置为 GridUniformGrid .我有一些ItemsControl例子 here这可能对您有所帮助,因为我发现 MDSN 的示例不是很有帮助。

A UniformGrid如果你能绑定(bind)你的 Rows 就最简单了和 Columns属性到您的 ViewModel 中的属性,但是这需要所有单元格的大小相同,我不记得属性 Rows 是不是和 Columns是是否参与绑定(bind)系统的 DependencyProperties。

<ItemsControl ItemsSource="{Binding MyCollection}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="{Binding ColumnCount}"
Rows="{Binding RowCount}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

如果这对您不起作用,您可以使用 Grid作为 ItemsPanel并设置 Grid.RowGrid.Column ItemContainerStyle 中的绑定(bind).

这将要求您在 ObservableCollection 中的每个单元格对象上都有属性说出该单元格所在的行/列,但是我怀疑您无论如何都需要这些来确定点击命令中的相邻单元格之类的东西。

此外,没有内置的方法来绑定(bind) Grid 中的行数/列数。 , 所以我倾向于使用一些 custom attached properties这将动态构建网格的 RowDefinitionsColumnDefinitions基于绑定(bind)值。

因此,如果您使用网格,您的最终结果可能看起来像这样:

<ItemsControl ItemsSource="{Binding Cells}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!-- This is assuming you use the attached properties linked above -->
<Grid local:GridHelpers.RowCount="{Binding Height}"
local:GridHelpers.ColumnCount="{Binding Width}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

<!-- ItemContainerStyle -->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column"
Value="{Binding ColumnIndex}" />
<Setter Property="Grid.Row"
Value="{Binding RowIndex}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>

模型/ View 模型看起来像这样

public class GameViewModel
{
// These should be full properties w/ property change notification
// but leaving that out for simplicity right now
public int Height;
public int Width;
public ObservableCollection<CellModel> Cells;
}

public class CellModel
{
// Same thing, full properties w/ property change notification
public int ColumnIndex;
public int RowIndex;
public bool IsVisible;
public bool IsMine;
public int NumberAdjacentMines;
}

关于c# - 为扫雷游戏动态创建一个游戏板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13587311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com