您的位置:首页 > 编程语言

敏捷软件开发:原则、模式与实践 一次编程实践 保龄球记分代码

2018-08-09 23:19 811 查看
//类Score
package com.java.bowlingscore;
public class Scorer {
public void addThrow(int pins){
itsThrows[itsCurrentThrow++]=pins;
}
public int scoreForFrame(int theFrame){
int score = 0;
ball = 0;
for(int currentFrame=0;currentFrame<theFrame;
currentFrame++){
if(strike()){
score +=10 + nextTwoBallsForStrike();
ball++;
}else if(spare()){
score+=10+nextBallForSpare();
ball+=2;
}else{
score +=twoBallsInFrame();
ball+=2;
}
}
return score;
}
private boolean strike(){
return itsThrows[ball]==10;
}
private boolean spare() {
return (itsThrows[ball]+itsThrows[ball+1]==10);
}
private int nextTwoBallsForStrike(){
return itsThrows[ball+1]+itsThrows[ball+2];
}
private int nextBallForSpare(){
return itsThrows[ball+2];
}
private int twoBallsInFrame(){
return itsThrows[ball]+itsThrows[ball+1];
}
private int ball;
private int[] itsThrows = new int[21];
private int itsCurrentThrow=0;
}
类Game
package com.java.bowlingscore;
public class Game {
public int score(){
return scoreForFrame(itsCurrentFrame);
}
public int getCurrentFrame(){
return itsCurrentThrow;
}
public void add(int pins){
itsScorer.addThrow(pins);
adjustCurrentFrame(pins);
}
private void adjustCurrentFrame(int pins) {
if(lastBallinFrame(pins)){
advanceFrame();
}else{
firstThrowInFrame = false;
}
}
private boolean lastBallinFrame(int pins) {
return strike(pins)||(!firstThrowInFrame);
}
private boolean strike(int pins) {
return (firstThrowInFrame&&pins==10);
}
private void advanceFrame() {
itsCurrentFrame = Math.min(10, itsCurrentFrame+1);
}
public int scoreForFrame(int theFrame){
return itsScorer.scoreForFrame(theFrame);
}
private Scorer itsScorer = new Scorer();
private boolean firstThrowInFrame=true;
private int itsCurrentFrame=1;
private int itsCurrentThrow=0;
}



晚上看着书一步一步敲出的,在代码重构方面学习到了不少,明天自己试着写一个.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  保龄球 记分
相关文章推荐