【发布时间】:2025-12-03 19:40:01
【问题描述】:
我很无聊,所以我决定尝试制作一个我自己的 Yahtzee 游戏,规则与实际游戏完全相同,只是想测试一下我的编程技巧(目前还不够出色)。
下面发布的代码用于检查顺子(小号和大号)。 我相信你可以自己看,但万一你看不到,它的工作原理是这样的:
所有 5 个骰子的值都放在一个 List 中,然后使用 List<T>.Sort() 方法对其进行排序。
现在它们应该在列表中按升序排序(例如 1、2、3、4、5)。
为了确定它是否是一条大直线,我只需使用一个 int 值,如果检测到一条小直线,它的值会加 1,然后由于我的“大直线 = 小直线 * 2”而找到一条大直线逻辑,这可能有缺陷,但对我来说似乎很有意义:)。
这可行,但并非总是如此,正如您可能看到的那样,如果我在中间某处有重复值(例如 1、2、3、3、4、6),则此代码将不起作用。这一系列数字应该仍然给我一个小顺,但它不会。
现在至于我的实际问题:如何修改此代码,以便它始终检测大小直道?
List<int> valList = new List<int>();
foreach (Dice d in dList)
{
valList.Add(d.Value);
}
valList.Sort();
txtSmall.Text = "0";
txtLarge.Text = "0";
int straight = 0;
if (valList[0] == valList[1] - 1 && valList[1] == valList[2] - 1 && valList[2] == valList[3] - 1)
straight++;
if (valList[1] == valList[2] - 1 && valList[2] == valList[3] - 1 && valList[3] == valList[4] - 1)
straight++;
switch (straight)
{
case 1:
if (txtSmall.IsEnabled)
txtSmall.Text = "30";
break;
case 2:
if (txtSmall.IsEnabled)
txtSmall.Text = "30";
if (txtLarge.IsEnabled)
txtLarge.Text = "40";
break;
}
PS:以防你想知道我的Dice 课程是怎么上的,这里是(尽管我不明白你为什么需要它):
class Dice
{
private static CryptoRandom r = new CryptoRandom();
public static int uBound = 1;
public static int lBound = 7;
public string Path { get; set; }
private int value;
public int Value
{
get { return value; }
}
private bool locked;
public bool Locked
{
get { return locked; }
}
public Dice(int lowerBound = 1, int upperBound = 6)
{
uBound = upperBound + 1;
lBound = lowerBound;
this.Roll();
this.locked = false;
}
public void Roll()
{
this.value = r.Next(lBound, uBound);
}
public void Lock()
{
this.locked = true;
}
public void Unlock()
{
this.locked = false;
}
}
PPS:如果有更好的方法来检测这些东西,请随时分享,但也请尝试回答我的问题 :)。
【问题讨论】: