-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
49bcb87
commit fbd9f1e
Showing
2 changed files
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<?php | ||
|
||
class BowlingGame { | ||
private $rolls = []; | ||
|
||
// 投球を登録するメソッド | ||
public function roll($pins) { | ||
$this->rolls[] = $pins; | ||
} | ||
|
||
// スコアを計算するメソッド | ||
public function score() { | ||
$score = 0; | ||
$frameIndex = 0; | ||
|
||
for ($frame = 0; $frame < 10; $frame++) { | ||
if ($this->isStrike($frameIndex)) { // ストライク | ||
$score += 10 + $this->rolls[$frameIndex + 1] + $this->rolls[$frameIndex + 2]; | ||
$frameIndex++; | ||
} elseif ($this->isSpare($frameIndex)) { // スペア | ||
$score += 10 + $this->rolls[$frameIndex + 2]; | ||
$frameIndex += 2; | ||
} else { | ||
$score += $this->rolls[$frameIndex] + $this->rolls[$frameIndex + 1]; | ||
$frameIndex += 2; | ||
} | ||
} | ||
|
||
return $score; | ||
} | ||
|
||
// ストライクかどうかを判定するメソッド | ||
private function isStrike($frameIndex) { | ||
return $this->rolls[$frameIndex] == 10; | ||
} | ||
|
||
// スペアかどうかを判定するメソッド | ||
private function isSpare($frameIndex) { | ||
return $this->rolls[$frameIndex] + $this->rolls[$frameIndex + 1] == 10; | ||
} | ||
} | ||
|
||
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
<?php | ||
|
||
require_once 'bowling_game.php'; | ||
|
||
// 引数の数が正しいか確認 | ||
if ($argc != 2) { | ||
echo "Usage: php script.php <filename>\n"; | ||
exit(1); | ||
} | ||
|
||
// ファイルの存在を確認 | ||
$filename = $argv[1]; | ||
if (!file_exists($filename)) { | ||
echo "Error: File not found.\n"; | ||
exit(1); | ||
} | ||
|
||
// ファイルを開く | ||
$file = fopen($filename, "r"); | ||
if (!$file) { | ||
echo "Error: Unable to open file.\n"; | ||
exit(1); | ||
} | ||
|
||
$bg = new BowlingGame(); | ||
|
||
// ファイルから整数を読み込み | ||
while (($line = fgets($file)) !== false) { | ||
$number = intval(trim($line)); | ||
if ($number < 0) { | ||
break; | ||
} | ||
$bg->roll($number); | ||
} | ||
|
||
// ファイルを閉じる | ||
fclose($file); | ||
$score = $bg->score(); | ||
echo "$score\n"; | ||
?> |