Refactor JS endGame function