Created
October 23, 2013 16:08
-
-
Save safx/7121561 to your computer and use it in GitHub Desktop.
ボウリングのスコアを計算するスクリプト
This file contains hidden or 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
#_ = require \prelude-ls | |
class Frame | |
(pin, prev)-> | |
@cell = pin | |
@prev = prev | |
@next = null | |
prev.next = this if prev? | |
#frameScore: -> _.fold (+), 0, @cell | |
frameScore: -> @cell .reduce (+), 0 | |
isStrike: -> @frameScore! == 10 and @cell.length == 1 | |
isSpare: -> @frameScore! == 10 and @cell.length == 2 | |
takeNextOneCellScore: -> | |
if @next? then @next.cell[0] else undefined | |
takeNextTwoCellsScore: -> | |
return undefined unless @next | |
if @next.cell.length >= 2 | |
@next.cell[0] + @next.cell[1] | |
else | |
if @next.next? | |
@next.frameScore! + @next.next.cell[0] | |
else | |
0 | |
bonusScore: -> | |
if @isStrike! | |
@takeNextTwoCellsScore! | |
else if @isSpare! | |
@takeNextOneCellScore! | |
else | |
0 | |
score: -> | |
bonus = @bonusScore! | |
return undefined unless bonus? | |
(if @prev? then @prev.score! else 0) + @frameScore! + bonus | |
toString: -> | |
(@cell .join \,) + ' | ' + @score! + ' ||| ' + @frameScore! + ' ' + @bonusScore! + ' ' + @isStrike! + ' ' + @isSpare! | |
finalScore: -> | |
f = this | |
while f.next? | |
f = f.next | |
f.score! | |
function showGame g | |
while g? | |
console.log g.toString! | |
g = g.next | |
function makeGame ary | |
q = ary .reduce (m, a) -> | |
new Frame(a, m) | |
, null | |
while q.prev? | |
q = q.prev | |
q | |
function parse text | |
a = [] | |
f = [] | |
t = 0 | |
for i from 0 to text.length - 1 | |
++t | |
c = text[i] | |
if c == 'X' | |
t = 2 | |
s = 10 | |
else if c == '/' | |
s = 10 - f[0] | |
else if c == '-' | |
s = 0 | |
else | |
s = parseInt c, 10 | |
f.push s | |
if a.length < 9 and t == 2 | |
a.push f | |
f = [] | |
t = 0 | |
a.push f | |
makeGame a | |
function test text, exprect | |
g = parse text | |
s = g.finalScore! | |
console.log text, exprect, '=>', s | |
throw 'Error!!' unless s == exprect | |
test '9-9-9-9-9-9-9-9-9-9-', 90 | |
test 'X54-----------------', 28 | |
test '1/5-----------------', 20 | |
test '1/5-2/-/8-----------', 56 | |
test '------XX----------', 30 | |
test '------XXX--------', 60 | |
test 'XXXXXXXXXXXX', 300 | |
test '--------------------', 0 | |
test '-------------------/5', 15 | |
test '------------------X54', 19 | |
test '5/5/5/5/5/5/5/5/5/5/5', 150 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment