Skip to content

Commit

Permalink
Luaでボーリングのスコア計算
Browse files Browse the repository at this point in the history
  • Loading branch information
steelpipe75 committed May 7, 2024
1 parent 479c237 commit 05ef36b
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
64 changes: 64 additions & 0 deletions lua/bowling_game/bowling_game.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
-- ボーリングのスコア計算クラス
local BowlingGame = {}

-- 初期化
function BowlingGame:new()
local game = {
rolls = {}, -- 倒したピンの数を記録する配列
MAX_FRAMES = 10 -- 最大フレーム数
}
setmetatable(game, self)
self.__index = self
return game
end

-- 投球の記録
function BowlingGame:roll(pins)
table.insert(self.rolls, pins) -- 倒したピンの数を配列に追加
end

-- スコア計算
function BowlingGame:score()
local score = 0
local rollIndex = 1 -- 現在の投球のインデックス
local maxIndex = #self.rolls
self:roll(0)
self:roll(0)

for frame = 1, self.MAX_FRAMES do
if self:isStrike(rollIndex) then -- ストライクの場合
score = score + self:strikeScore(rollIndex)
rollIndex = rollIndex + 1
elseif self:isSpare(rollIndex) then -- スペアの場合
score = score + self:spareScore(rollIndex)
rollIndex = rollIndex + 2
else -- 通常の投球
score = score + self.rolls[rollIndex] + self.rolls[rollIndex + 1]
rollIndex = rollIndex + 2
end
end

return score
end

-- ストライクのボーナス
function BowlingGame:strikeScore(rollIndex)
return 10 + self.rolls[rollIndex + 1] + self.rolls[rollIndex + 2]
end

-- スペアのボーナス
function BowlingGame:spareScore(rollIndex)
return self.rolls[rollIndex + 2]
end

-- ストライクかどうかの判定
function BowlingGame:isStrike(rollIndex)
return self.rolls[rollIndex] == 10
end

-- スペアかどうかの判定
function BowlingGame:isSpare(rollIndex)
return self.rolls[rollIndex] + self.rolls[rollIndex + 1] == 10
end

return BowlingGame
42 changes: 42 additions & 0 deletions lua/bowling_game/main.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
-- コマンドライン引数からファイル名を取得
local filename = arg[1]

-- ファイルが指定されていない場合は終了
if not filename then
print("Usage: lua script.lua <filename>")
return
end

-- ファイルを開く
local file = io.open(filename, "r")

-- ファイルが開けない場合はエラーを表示して終了
if not file then
print("Error: Unable to open file")
return
end

local BowlingGame = require("bowling_game")
local bg = BowlingGame:new()

-- ファイルから一行ずつ読み込んで処理する
for line in file:lines() do
-- 整数値に変換して二倍にする
local number = tonumber(line)
if number then
if number < 0 then
-- print("Error: Negative number encountered")
break
else
bg:roll(number)
end
else
print("Error: Invalid number encountered")
break
end
end

-- ファイルを閉じる
file:close()

print(bg:score())

0 comments on commit 05ef36b

Please sign in to comment.