Skip to content

Instantly share code, notes, and snippets.

@MNovak12
Created October 17, 2017 20:44
Show Gist options
  • Save MNovak12/d373cb4c073c4725eb5eaf2839f1d233 to your computer and use it in GitHub Desktop.
Save MNovak12/d373cb4c073c4725eb5eaf2839f1d233 to your computer and use it in GitHub Desktop.
A bowling simulation
import random
def take_turn(player, total, scores, frame):
roll = []
first_ball = first_roll()
second_ball = 0
# If it's a strike, add 0 to score this turn
if is_strike(first_ball):
roll.append('X')
# second_ball = 0
print 'STRIKE'
else:
roll.append(first_ball)
score = first_ball
second_ball = random.randint(0, 10 - first_ball)
# If it's a spare, add the score from the first ball
if is_spare(first_ball, second_ball):
print 'SPARE'
roll.append('/')
else:
# If it's a normal roll, add the score from the second ball
roll.append(second_ball)
# Score for this round
score = first_ball + second_ball
# If last round was a spare or strike, add points from this round plus the points that were not added from the last round
if frame > 1:
if was_strike(player[frame - 2]):
total += first_ball + second_ball
scores[frame - 2] = scores[frame - 2] + first_ball + second_ball
elif was_spare(player[frame - 2]):
total += first_ball
scores[frame - 2] = scores[frame - 2] + first_ball
# Different scoring rules for the last frame
if frame == NUM_FRAMES:
if was_strike(roll):
print 'STRIKE'
second_attempt = first_roll()
if is_strike(second_attempt):
third_attempt = first_roll()
else:
third_attempt = random.randint(0, 10 - second_attempt)
score += second_attempt + third_attempt
roll.append(second_attempt)
roll.append(third_attempt)
elif was_spare(roll):
print 'SPARE'
third_attempt = first_roll()
score += third_attempt
roll.append(third_attempt)
total += score
scores.append(score)
player.append(roll)
print 'Pins: ' + str(player)
print 'Points: ' + str(scores)
print 'Score for round: ' + str(score)
print 'Total score: ' + str(total)
return player, scores, total
def was_strike(roll):
return roll[0] == 'X'
def was_spare(roll):
return roll[1] == '/'
def is_strike(roll_1):
return roll_1 == 10
def is_spare(roll_1, roll_2):
return (roll_1 + roll_2) == 10
def first_roll():
return random.randint(0, 10)
while True:
user_input = raw_input("Would you like to play a game?\n")
if str(user_input) == 'Yes':
player_1 = []
player_2 = []
player_1_total = 0
player_2_total = 0
player_1_scores = []
player_2_scores = []
NUM_FRAMES = 10
for frame in xrange(1, NUM_FRAMES + 1):
print 'FRAME ' + str(frame) + '\n'
print 'Player 1: '
player_1, player_1_scores, player_1_total = take_turn(player_1, player_1_total, player_1_scores, frame)
print '\nPlayer 2: '
player_2, player_2_scores, player_2_total = take_turn(player_2, player_2_total, player_2_scores, frame)
print '\n'
elif str(user_input) == 'No':
exit()
else:
print "Type Yes or No\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment