我在一个正在实施Monopoly Game仿真的课程中,非常简单,只需将每个回合的结果打印到控制台供用户查看,最终我们会将其移动到GUI但是现在我们只是每个玩家都可以在控制台上看到结果。
这些结果是从Player类打印的。播放器类基本上保存了在一个地方打印所需的所有信息(即playerName,rollTotal,origSquareLocation,newSquareLocation)。
我试图绕过观察者设计模式并使MonopolyGame类成为观察者,将播放器类作为Observable。这是可能的还是让我倒退,因为MonopolyGame Class正在构建玩家?我是否需要制作一个单独的GameObserver类来使其工作?
这是我的MonopolyGame课程:
public class MonopolyGame {
private static final int ROUNDS_TOTAL = 40;
private static final int PLAYERS_TOTAL = 2;
private List<Player> players = new ArrayList<Player>(PLAYERS_TOTAL);
private Board board = new Board();
private Die[] dice = { new Die(), new Die() };
/**
* Default Constructor
*/
public MonopolyGame() {
Player p = new Player("Horse", dice, board);
players.add(p);
p = new Player("Car", dice, board);
players.add(p);
}
/**
* Method: playGame()
*
* starts a new MonopolyGame for the assigned amount of rounds.
*/
public void playGame() {
for (int i = 0; i < ROUNDS_TOTAL; i++) {
playRound();
}
}
/**
* Method: playRound()
*
* allows each player by iterator to take their turn for each round played.
*/
public void playRound() {
for (Iterator<Player> iter = players.iterator(); iter.hasNext(); ) {
Player player = iter.next();
player.takeTurn();
}
}
} // End MonopolyGame Class
这是我的玩家类:
public class Player {
private String name;
private Piece piece;
private Board board;
private Die[] dice;
public Player(String name, Die[] dice, Board board) {
this.name = name;
this.dice = dice;
this.board = board;
this.piece = new Piece(board.getStartSquare());
}
public void takeTurn() {
// Roll the dice
int rollTotal = 0;
for (int i = 0; i < dice.length; i++) {
dice[i].roll();
rollTotal += dice[i].getFaceValue();
}
// place the Players piece in the correct location.
Square newLoc = board.getSquare(piece.getLocation(), rollTotal);
piece.setLocation(newLoc);
System.out.println(getName() + " has rolled a " + rollTotal + " and landed on " + getLocation().getName());
}
public Square getLocation() {
return piece.getLocation();
}
public String getName() {
return name;
}
} // End Player Class
答案 0 :(得分:1)
当然可以使用该模式。但对这种模式更自然(至少对我来说)的用法就像是&#34; ConsolePrinter&#34;或者&#34; GuiBoardWindow&#34;观察者和观察者的游戏(或玩家)。因为观察者模式的主要思想是解耦不直接相关的部分。游戏的状态和玩家对象对我来说非常重要,你可能不想让它们分离。至少没有更新的玩家或游戏是游戏机制的实际模型/实体旁边的任何东西。