Skip to content

Instantly share code, notes, and snippets.

@felipernb
Created August 13, 2012 18:39
Show Gist options
  • Select an option

  • Save felipernb/3343051 to your computer and use it in GitHub Desktop.

Select an option

Save felipernb/3343051 to your computer and use it in GitHub Desktop.
The Bowling Game Kata
//bowling.go
package bowling
type Game struct {
rolls []int
currentRoll int
}
func NewGame() *Game {
return &Game{make([]int, 21), 0}
}
func (g *Game) Roll(p int) {
g.rolls[g.currentRoll] = p
g.currentRoll++
}
func (g *Game) Score() int {
score := 0
frame := 0
for i := 0; i < 10; i++ {
if g.isStrike(frame) {
score += 10 + g.strikeBonus(frame)
frame++
} else if g.isSpare(frame) {
score += 10 + g.spareBonus(frame)
frame += 2
} else {
score += g.sumOfRolls(frame)
frame += 2
}
}
return score
}
func (g *Game) isStrike(frame int) bool {
return g.rolls[frame] == 10
}
func (g *Game) isSpare(frame int) bool {
return g.sumOfRolls(frame) == 10
}
func (g *Game) strikeBonus(frame int) int {
return g.rolls[frame+1] + g.rolls[frame+2]
}
func (g *Game) spareBonus(frame int) int {
return g.rolls[frame+2]
}
func (g *Game) sumOfRolls(frame int) int {
return g.rolls[frame] + g.rolls[frame+1]
}
//bowling_test.go
package bowling
import (
"testing"
"fmt"
)
func rollMany(n, pins int, g *Game) {
for i := 0; i < n; i++ {
g.Roll(pins)
}
}
func assertScore(n int, g *Game, t *testing.T) {
score := g.Score()
if score != n {
t.Fail()
fmt.Printf("Expected score %d and got %d", n, score)
}
}
func TestZero(t *testing.T) {
g := NewGame()
rollMany(20, 0, g)
assertScore(0, g, t)
}
func TestAllOnes(t *testing.T) {
g := NewGame()
rollMany(20, 1, g)
assertScore(20, g, t)
}
func TestOneSpare(t *testing.T) {
g := NewGame()
g.Roll(5)
g.Roll(5) // spare
g.Roll(3)
rollMany(17, 0, g)
assertScore(16, g, t)
}
func TestOneStrike(t *testing.T) {
g := NewGame()
g.Roll(10) //strike
g.Roll(3)
g.Roll(4)
rollMany(16, 0, g)
assertScore(24, g, t)
}
func TestPerfectGame(t *testing.T) {
g := NewGame()
rollMany(12, 10, g)
assertScore(300, g, t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment