如何通过正确使用开关盒来减少线路
本文关键字:线路 开关 何通过 | 更新日期: 2023-09-27 18:33:48
我正在做一个二十一点游戏项目。我有一个helper()
的方法来帮助用户的行为。例如:
经销商的UP卡是:8
玩家的手牌总数为:16
玩家不确定,他应该击中还是留下来。 helper()
函数在此处执行操作。
它基本上是计算牌组上好牌的数量(playerTotal
+ goodcard
<= 21)
所以我正在考虑以这种方式做(伪代码)
public void helper() {
remain = 21 - playerTotal;
if (remain == 1) {
for (int i = 0; i < deck.last(); i++) {
switch (deck[i]) {
case A: numOfGood += 1
default: numOfBad +=1
}
}
}
else if (remain == 2) {
for (....) {
switch (deck[i]) {
case A: numOfGood += 1
case 2: numOfGood += 1
default: numOfBad +=1
}
}
}
//goes like this
}
我需要为所有卡(A,2,3,4,5,6,7,8,9,J,K,Q,K)构建一个开关盒和for循环,但这似乎是一个巨大的混乱。如何通过执行不同操作来减少行数?
首先编写一个可以计算卡的(最小)数值的GetValue
方法。 您可以使用switch
或其他任何您想要的方式实现它:
public static int GetValue(char card)
{
//...
}
一旦你有了这个,你的方法的实现就会变得更短和更简单:
foreach(var card in deck)
if(GetValue(card) <= remain)
numOfGood++;
else
numOfBad++;
另请注意,您可以只计算好牌或坏牌的数量,并在需要时使用剩余卡的总数量来计算另一张卡。
var oddsOfSuccessfulHit = deck.Count(card => GetValue(card) <= remain) /
(double) deck.Count;
您可以使用HashSet
,使用switch
可能会更有效,但是如果您想保存行...
var goodCards = new HashSet<char>(new[] { 'A', '2' });
然后像这样,
var numOfGood = deck.Count(card => goodCards.Contains(card));
var numOfBad = deck.Count - numOfGood;
或者,由于卡值的逻辑无法更改,因此无需对其进行编码 - 只需将其存储为数据即可。
struct CardEffect
{
public string CardGlyph;
public int MinValue;
public int MaxValue;
}
... load from XML file or some other location and load into ...
public Dictionary<string, CardEffect> cardValues;
然后使用Servy建议的逻辑。