Created
March 12, 2018 09:37
-
-
Save johanlantz/e692f237668222e6d8153645ad69647c 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
class Bowling { | |
constructor() { | |
this.scoreBoard = new Array(22); | |
this.STRIKE = 10; | |
this.SPARE = 10; | |
} | |
startNewRound() { | |
this.scoreBoard.fill(0); | |
this.currentRoll = 0; | |
this.currentScore = 0; | |
} | |
printScoreBoard() { | |
//Row 1: Headers | |
for (var i = 1; i <= 10; i++) { | |
process.stdout.write(i + "\t"); | |
} | |
console.log("Extra"); | |
//Row 2: Round scores | |
for (var i = 0; i < this.scoreBoard.length; i=i+2) { | |
if (this.scoreBoard[i] == this.STRIKE) { | |
process.stdout.write("X\t"); | |
} else if(this.scoreBoard[i] + this.scoreBoard[i+1] == this.SPARE) { | |
process.stdout.write(this.scoreBoard[i].toString() + " /\t"); | |
} else { | |
process.stdout.write(this.scoreBoard[i].toString() + " " + this.scoreBoard[i+1].toString() + "\t"); | |
} | |
} | |
console.log(""); | |
//Row 3: Accumulated scores | |
for (var i = 0; i < 20; i=i+2) { | |
if (this.scoreBoard[i] == this.STRIKE) { | |
this.currentScore = this.currentScore + this.STRIKE + this.scoreBoard[i+2] + this.scoreBoard[i+3]; | |
} else if(this.scoreBoard[i] + this.scoreBoard[i+1] == this.SPARE) { | |
this.currentScore = this.currentScore + this.SPARE + this.scoreBoard[i+2]; | |
} else { | |
this.currentScore = this.currentScore + this.scoreBoard[i] + this.scoreBoard[i+1]; | |
} | |
process.stdout.write(this.currentScore + "\t") | |
} | |
console.log("") | |
} | |
roll() { | |
var isEvenRoll = this.currentRoll % 2 == 0 ? true : false; | |
var availablePins = isEvenRoll ? 10 : 10 - this.scoreBoard[this.currentRoll-1]; | |
var pinsDown = 0; | |
var rand = Math.random(); | |
if (availablePins != 0) { | |
pinsDown = (rand != 0) ? Math.floor((rand*availablePins) + 1) : 0; | |
} | |
this.scoreBoard[this.currentRoll++] = pinsDown; | |
} | |
canRollAgain() { | |
if (this.currentRoll < 20) { | |
return true; | |
} else if ((this.currentRoll == 20) && (this.scoreBoard[this.currentRoll-2] == this.STRIKE)) { | |
return true; | |
} else if ((this.currentRoll == 21) && (this.scoreBoard[this.currentRoll-3] == this.STRIKE)) { | |
return true; | |
} else if (this.currentRoll == 20 && (this.scoreBoard[this.currentRoll-1] + this.scoreBoard[this.currentRoll-2] == this.SPARE)) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} | |
var bowling = new Bowling(); | |
bowling.startNewRound(); | |
while (bowling.canRollAgain()) { | |
bowling.roll(); | |
} | |
bowling.printScoreBoard(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bowling scoreboard. 1h coding dojo challenge. Missing tests but should be accurate.