Java - 简单游戏的设计建议

5 java class

我正在实施一个简单的"正确播放你的牌"(也就是所谓的更高/更低)游戏.如果您在规则非常简单之前没有遇到过它.使用一套卡片(例如心形).一次绘制一张牌,目的是正确猜测下一张牌的面值是高于还是低于先前绘制的牌的面值.

游戏的逻辑并不是特别复杂,我并不担心.我想出了一个设计,但我并不完全满意.有几个方面我确信它可以改进,这就是我想要你的建议.这是该类的接口(有关其他理解的注释,而不是真正的注释):

public interface PlayYourCardsRight {

/**
 * Get the number of cards remaining with higher face values than the previously
 * drawn card
 * @return
 */

public abstract int getNumberCardsHigher();

/**
 * Get the number of cards remaining with lower face values than the previously
 * drawn card
 * @return
 */

public abstract int getNumberCardsLower();

/**
 * Get all cards that have already been drawn in the order they were drawn in
 * 
 */

public abstract List<Card> getPlayedCards();

/**
 * Simple prediction algorithm  - if there are more cards left in the deck with
 * lower face values than the previous card, then predict 'Lower', if there 
 * are more cards left in the deck with higher face values then predict
 * 'Higher', if there are equal numbers of higher/lower cards pick 'higher' or     'lower'
 * at random
 *
 * Prediction is an Enum (Higher/Lower/None)
 *
 */

public abstract Prediction getPrediction();

/*
 * Draw the next card at random
 */

public abstract void nextRound();

/**
 * Specifiy what the next card should be
 * 
 * @param card
 */

public abstract void nextRound(Card card);

}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,这些都是相当自我解释和简单的.这是我的问题:

我不希望构造函数自动绘制卡片.这意味着最初没有"先前抽取的卡片".我NO PREDICTIONPrediction枚举中有一个值,但由于没有"先前绘制的卡片",getNumberCardsHigher()因此getNumberCardsLower()方法无法返回合理的值(当绘制了所有卡牌时,它们也无法返回合理的值).

显然,我可以简单地抛出异常,但这看起来有点过分 - 特别是因为所有对方法的调用都必须包含在try/catches中.我也不满意返回一个负值,因为如果有人忘记/无法检查它们,这很容易导致一些错误.

欢迎所有建议!

Bil*_*l K 3

就我个人而言,我认为在参数检查的情况下抛出未经检查的异常根本不是矫枉过正——这是假设您的代码断言无效状态(您不应该使用处于该状态的对象调用这些方法,永远)。

我通常使用 IllegalArgumentException 来表明传入的参数不符合方法调用的约定,并使用 IllegalStateException 来表明对象此时不处于处理方法调用的状态。

由于它们都是未经检查的异常,因此您不必尝试/捕获它们,只需让它们冒泡即可,它们会做异常擅长的事情——它们为您提供堆栈跟踪并准确地告诉您错误在哪里,包括调用者它不正确。

顺便说一句,我通常使用某种字符串,在你的情况下它可能是:

throw new IllegalStateException("You cannot call this method until a card has been drawn");
Run Code Online (Sandbox Code Playgroud)

从逻辑上讲,询问该卡是否高于或低于不存在的卡是没有意义的。

现在,如果您的方法实际上抛出了该异常,那么您必须继续并修复您的代码,以便它在抽出一张牌之前不会调用该方法 - 所以您必须弄清楚如何抽出您的第一张牌,无论如何。

注意:异常仅用于错误检测,避免将它们用于流量控制。这意味着您不应该尝试捕获异常并使用它来抽牌然后再次调用!相反,您应该以确保在第一次调用方法之前抽牌的方式进行编程。