【发布时间】:2023-03-31 01:40:01
【问题描述】:
private Optional<Player> playerWithMostCards()
{
Player scoringPlayer = null;
int maxCount = 0;
for(Player p : players)
{
final int count = p.pile.size();
if(count > maxCount)
{
scoringPlayer = p;
maxCount = count;
}
else if(count == maxCount)
{
scoringPlayer = null;
}
}
return Optional.ofNullable(scoringPlayer);
}
private Optional<Player> playerWithMostSevens()
{
Player scoringPlayer = null;
int maxCount = 0;
for(Player p : players)
{
int count = 0;
for(Card c : p.pile)
{
if(c.is(Card.Value.SEVEN))
{
count++;
}
}
if(count > maxCount)
{
scoringPlayer = p;
maxCount = count;
}
else if(count == maxCount)
{
scoringPlayer = null;
}
}
return Optional.ofNullable(scoringPlayer);
}
private Optional<Player> playerWithMostSpades()
{
Player scoringPlayer = null;
int maxCount = 0;
for(Player p : players)
{
int count = 0;
for(Card c : p.pile)
{
if(c.is(Card.Suit.SPADES))
{
count++;
}
}
if(count > maxCount)
{
scoringPlayer = p;
maxCount = count;
}
else if(count == maxCount)
{
scoringPlayer = null;
}
}
return Optional.ofNullable(scoringPlayer);
}
private Optional<Player> playerWithSevenOfSpades()
{
for(Player p : players)
{
for(Card c : p.pile)
{
if(c == new Card("7S"))
{
return Optional.of(p);
}
}
}
return Optional.empty();
}
private void updateScores()
{
for(Player p : players)
{
p.score = p.scopas;
}
playerWithMostCards().ifPresent(p -> p.score += 1);
playerWithMostSevens().ifPresent(p -> p.score += 1);
playerWithMostSpades().ifPresent(p -> p.score += 1);
playerWithSevenOfSpades().ifPresent(p -> p.score += 1);
}
基本上,我正在制作一个纸牌游戏(称为 Scopa),当调用 updateScores() 时,应该更新每个玩家的分数。玩家可以通过拥有最多的牌、拥有最多的 7 或拥有黑桃 7 来获得积分。确定谁拥有最多的牌、7 和黑桃的逻辑非常相似。如何避免在这三种方法中重复逻辑?谢谢。
【问题讨论】:
标签: java code-duplication