基于回合制的纸牌游戏中的命令模式

时间:2014-06-12 01:00:48

标签: java design-patterns client-server command-pattern

我正在尝试构建一个小型多客户端/服务器回合制卡片游戏。我正在利用命令模式来更新我的GameInstance'保持整个游戏状态的对象(游戏牌,弃牌堆,所有玩家[反过来握着自己的牌]等)。

我的基本命令如下:

public interface IGameCommand extends Serializable {
    public abstract boolean isValid();
    public abstract void execute();
}

因此,当客户端(其中引用了' GameInstance')创建了一个具体的命令,比如说," DrawCardCommand"它看起来像这样:

public class DrawCardCommand extends GameCommand {

private static final long serialVersionUID = 4815250478595425060L;
private static Logger log = Logger.getLogger(DrawCardCommand.class);

/***
 * opponent = player making command, GameInstance = game to apply changes to
 */
public DrawCardCommand(Opponent opponent, GameInstance instance){
    super(opponent, instance);
}

@Override
public boolean isValid() {

    // the super (abstract) class will verify that the 
    // player making the command, actually has control of
    // game play and that the game status is 'in-play'
    if(!super.isValid()){
        return false;
    }

    // game must be 'WAITING_FOR_DRAW' status
    if(this.instance.getStatus().compareTo(GameStatus.WAITING_FOR_DRAW) != 0){
        return false;
    }

    // are there cards in the deck to draw from?
    if(this.instance.getDeck().getCardCount() < 1){
        return false;
    }

    return true;
}

@Override
public void execute() {
    // draw the top card from the deck
    ICard drawnCard = this.instance.getDeck().drawFromTop();

    // get the drawn card and give it to the current player
    IPlayerConfig player =  this.instance.getPlayerConfig(this.currentPlayer);

    if(null == player){
        log.error(String.format("Failed during execute. PlayerConfig not found for player %s in game %d",
                                this.currentPlayer.toString(),
                            this.instance.getInstanceId()));
        return;
    }

    // place the drawn card in the players hand
    player.getHand().placeOnBottom(drawnCard);

    // update the status of the game (waiting for player
    // to negotiate)
    this.instance.setStatus(GameStatus.WAITING_FOR_OFFER);  
}

因此,当客户端创建此具体命令时,如果命令有效,则调用isValid()然后调用execute(),这将更新传递给DrawCardCommand构造函数的GameInstance对象。

我的问题是:一旦玩家(客户端)将命令应用到他们的游戏状态,我就通过网络将命令发送到服务器。如何将这些更改(使用此命令模式)应用于服务器端游戏状态?

我无法抓住它并重新应用它,因为再次呼叫execute()会重做“移动”。

我不应该在客户端应用命令吗?只验证移动然后将其发送到服务器?

而且,我应该在哪里放置代码来更新数据库? (我有一个DAO层)。当然,不是在execute()方法中,因为它在客户端没有上下文---只在服务器端?

提前感谢所有人!

0 个答案:

没有答案