Skip to content

Instantly share code, notes, and snippets.

@drobune
Last active July 10, 2023 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drobune/73cc40eacc599a9ea9e491991428acb5 to your computer and use it in GitHub Desktop.
Save drobune/73cc40eacc599a9ea9e491991428acb5 to your computer and use it in GitHub Desktop.
ChatGPTボウリング実装チャレンジ、SRPヴァージョン
import java.util.ArrayList;
import java.util.List;
class Game {
private List<Frame> frames;
public Game() {
frames = new ArrayList<>();
}
public void addFrame(Frame frame) {
frames.add(frame);
}
public int calculateScore() {
Scorer scorer = new Scorer();
return scorer.calculateScore(frames);
}
}
class Frame {
private List<Integer> rolls;
public Frame(int... pins) {
rolls = new ArrayList<>();
for (int pin : pins) {
rolls.add(pin);
}
}
public int getFirstRoll() {
return rolls.get(0);
}
public int getScore() {
int score = 0;
for (int roll : rolls) {
score += roll;
}
return score;
}
public boolean isStrike() {
return rolls.size() == 1 && getFirstRoll() == 10;
}
public boolean isSpare() {
return rolls.size() == 2 && getScore() == 10;
}
}
class Scorer {
public int calculateScore(List<Frame> frames) {
int totalScore = 0;
int frameIndex = 0;
for (int frameNumber = 0; frameNumber < 10; frameNumber++) {
Frame currentFrame = frames.get(frameIndex);
if (currentFrame.isStrike()) {
totalScore += 10 + getStrikeBonus(frameIndex, frames);
frameIndex++;
} else if (currentFrame.isSpare()) {
totalScore += 10 + getSpareBonus(frameIndex, frames);
frameIndex += 2;
} else {
totalScore += currentFrame.getScore();
frameIndex += 2;
}
}
return totalScore;
}
private int getStrikeBonus(int frameIndex, List<Frame> frames) {
Frame nextFrame = frames.get(frameIndex + 1);
int bonus = nextFrame.getScore();
if (nextFrame.isStrike()) {
Frame nextNextFrame = frames.get(frameIndex + 2);
bonus += nextNextFrame.getFirstRoll();
}
return bonus;
}
private int getSpareBonus(int frameIndex, List<Frame> frames) {
Frame nextFrame = frames.get(frameIndex + 1);
return nextFrame.getFirstRoll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment