单人纸牌(Elevens Lab)活动9:实现Elevens牌局
导言
在活动8中,我们重构(refactor,重新组织)了原本的class ElevensBoard
,将其改写为新的class Board
和一个更小的class ElevensBoard
。这个改动的目的是为着在诸如Tens和Thirteens等新游戏中重用代码。现在你需要完成重构后的class ElevensBoard
中相关method的实现。
练习
- 完成目录中的
class ElevensBoard
,实现下列method。
class Board
的abstract
method:isLegal
——该method的行为由其名字和注释描述。其实现应该检查所选择扑克牌的数目并利用ElevensBoard
的助手method。/** * Determines if the selected cards form a valid group for removal. * In Elevens, the legal groups are (1) a pair of non-face cards * whose values add to 11, and (2) a group of three cards consisting of * a jack, a queen, and a king in some order. * @param selectedCards the list of the indexes of the selected cards. * @return true if the selected cards form a valid group for removal; * false otherwise. */ @Override public boolean isLegal(List<Integer> selectedCards)
anotherPlayIsPossible
——该method也利用助手method,正确的实现不会太复杂。/** * Determine if there are any legal plays left on the board. * In Elevens, there is a legal play if the board contains * (1) a pair of non-face cards whose values add to 11, or (2) a group * of three cards consisting of a jack, a queen, and a king in some order. * @return true if there is a legal play left on the board; * false otherwise. */ @Override public boolean anotherPlayIsPossible()
ElevensBoard
助手method:containsPairSum11
——该method判断所选的cards
元素是否包括一堆点数值之和为11的牌。/** * Check for an 11-pair in the selected cards. * @param selectedCards selects a subset of this board. It is this list * of indexes into this board that are searched * to find an 11-pair. * @return true if the board entries indexed in selectedCards * contain an 11-pair; false otherwise. */ private boolean containsPairSum11(List<Integer> selectedCards)
containsJQK
——该method判断所选的cards
元素是否为J、Q、K的一种组合。/** * Check for a JQK in the selected cards. * @param selectedCards selects a subset of this board. It is this list * of indexes into this board that are searched * to find a JQK-triplet. * @return true if the board entries indexed in selectedCards * include a jack, a queen, and a king; false otherwise. */ private boolean containsJQK(List<Integer> selectedCards)
完成这些method后,运行ElevensGUIRunner.java
中的main
method。确保Elevens游戏能够正确工作。注意cards
目录应该与.class
文件在同一级。
问题
- Elevens和Thirteens的桌面牌数相差一。为什么
size
不是abstract
method? - 为什么没有处理选择数组
cards
中被移除/替换牌的abstract
method? - 创建is-a的另一种方式是实现interface。不创建
abstract class Board
的话,我们可以写如下这个interface Board
,并让ElevensBoard
实现它。这个新方案能让Elevens的GUI多态调用isLegal
和anotherPlayIsPossible
么?这种设计方案会和abstract class Board
一样好么?为什么?public interface Board { boolean isLegal(List<Integer> selectedCards); boolean anotherPlayIsPossible(); }
0 条评论