Python: Make code testable

Avoid executing code on module level as this prevents importing the
module for testing. Especially infinite loops are evil.
This commit is contained in:
Martin Thoma
2022-03-19 09:54:52 +01:00
parent f40a1fc465
commit 8495e59a8f
23 changed files with 1049 additions and 973 deletions

View File

@@ -22,7 +22,7 @@ jobs:
pip install -r 00_Utilities/python/ci-requirements.txt pip install -r 00_Utilities/python/ci-requirements.txt
- name: Test with pytest - name: Test with pytest
run: | run: |
pytest 01_Acey_Ducey/python 02_Amazing/python 39_Golf/python pytest -m "not slow"
- name: Test with mypy - name: Test with mypy
run: | run: |
mypy . --exclude 79_Slalom --exclude 27_Civil_War --exclude 38_Fur_Trader --exclude 81_Splat --exclude 09_Battle --exclude 40_Gomoko --exclude 36_Flip_Flop --exclude 43_Hammurabi --exclude 04_Awari --exclude 78_Sine_Wave --exclude 77_Salvo --exclude 34_Digits --exclude 17_Bullfight --exclude 16_Bug mypy . --exclude 79_Slalom --exclude 27_Civil_War --exclude 38_Fur_Trader --exclude 81_Splat --exclude 09_Battle --exclude 40_Gomoko --exclude 36_Flip_Flop --exclude 43_Hammurabi --exclude 04_Awari --exclude 78_Sine_Wave --exclude 77_Salvo --exclude 34_Digits --exclude 17_Bullfight --exclude 16_Bug

View File

@@ -62,89 +62,93 @@ def display_bankroll(bank_roll: int) -> None:
print("You now have %s dollars\n" % bank_roll) print("You now have %s dollars\n" % bank_roll)
# Display initial title and instructions def main():
print("\n Acey Ducey Card Game") # Display initial title and instructions
print("Creative Computing Morristown, New Jersey") print("\n Acey Ducey Card Game")
print("\n\n") print("Creative Computing Morristown, New Jersey")
print("Acey-Ducey is played in the following manner") print("\n\n")
print("The dealer (computer) deals two cards face up") print("Acey-Ducey is played in the following manner")
print("You have an option to bet or not bet depending") print("The dealer (computer) deals two cards face up")
print("on whether or not you feel the card will have") print("You have an option to bet or not bet depending")
print("a value between the first two.") print("on whether or not you feel the card will have")
print("If you do not want to bet, input a 0") print("a value between the first two.")
print("If you do not want to bet, input a 0")
# Loop for series of multiple games
KEEP_PLAYING = True
while KEEP_PLAYING:
# Loop for series of multiple games # Initialize bankroll at start of each game
KEEP_PLAYING = True BANK_ROLL = DEFAULT_BANKROLL
while KEEP_PLAYING: display_bankroll(BANK_ROLL)
# Initialize bankroll at start of each game # Loop for a single round. Repeat until out of money.
BANK_ROLL = DEFAULT_BANKROLL while BANK_ROLL > 0:
display_bankroll(BANK_ROLL)
# Loop for a single round. Repeat until out of money. # Deal out dealer cards
while BANK_ROLL > 0: print("Here are your next two cards")
dealer1 = deal_card_num()
# If the cards match, we redeal 2nd card until they don't
dealer2 = dealer1
while dealer1 == dealer2:
dealer2 = deal_card_num()
# Organize the cards in order if they're not already
if dealer1 >= dealer2:
(dealer1, dealer2) = (dealer2, dealer1) # Ya gotta love Python!
# Show dealer cards to the player
# (use card name rather than internal number)
print(get_card_name(dealer1))
print(get_card_name(dealer2) + "\n")
# Deal out dealer cards # Get and handle player bet choice
print("Here are your next two cards") BET_IS_VALID = False
dealer1 = deal_card_num() while not BET_IS_VALID:
# If the cards match, we redeal 2nd card until they don't curr_bet_str = input("What is your bet? ")
dealer2 = dealer1 try:
while dealer1 == dealer2: curr_bet = int(curr_bet_str)
dealer2 = deal_card_num() except ValueError:
# Organize the cards in order if they're not already # Bad input? Just loop back up and ask again...
if dealer1 >= dealer2: pass
(dealer1, dealer2) = (dealer2, dealer1) # Ya gotta love Python!
# Show dealer cards to the player
# (use card name rather than internal number)
print(get_card_name(dealer1))
print(get_card_name(dealer2) + "\n")
# Get and handle player bet choice
BET_IS_VALID = False
while not BET_IS_VALID:
curr_bet_str = input("What is your bet? ")
try:
curr_bet = int(curr_bet_str)
except ValueError:
# Bad input? Just loop back up and ask again...
pass
else:
if curr_bet == 0:
BET_IS_VALID = True
print("Chicken!!\n")
elif curr_bet > BANK_ROLL:
print("Sorry, my friend but you bet too much")
print("You have only %s dollars to bet\n" % BANK_ROLL)
else: else:
# Deal player card if curr_bet == 0:
BET_IS_VALID = True BET_IS_VALID = True
player = deal_card_num() print("Chicken!!\n")
print(get_card_name(player)) elif curr_bet > BANK_ROLL:
print("Sorry, my friend but you bet too much")
# Did we win? print("You have only %s dollars to bet\n" % BANK_ROLL)
if dealer1 < player < dealer2:
print("You win!!!")
BANK_ROLL += curr_bet
else: else:
print("Sorry, you lose") # Deal player card
BANK_ROLL -= curr_bet BET_IS_VALID = True
player = deal_card_num()
print(get_card_name(player))
# Update player on new bankroll level # Did we win?
display_bankroll(BANK_ROLL) if dealer1 < player < dealer2:
print("You win!!!")
BANK_ROLL += curr_bet
else:
print("Sorry, you lose")
BANK_ROLL -= curr_bet
# End of loop for a single round # Update player on new bankroll level
display_bankroll(BANK_ROLL)
print("\n\nSorry, friend but you blew your wad") # End of loop for a single round
player_response = input("Try again (yes or no) ")
if player_response.lower() == "yes":
print()
else:
KEEP_PLAYING = False
# End of multiple game loop print("\n\nSorry, friend but you blew your wad")
player_response = input("Try again (yes or no) ")
if player_response.lower() == "yes":
print()
else:
KEEP_PLAYING = False
print("OK Hope you had fun\n") # End of multiple game loop
print("OK Hope you had fun\n")
if __name__ == "__main__":
main()
######################################################## ########################################################

View File

@@ -108,60 +108,63 @@ def build_result_string(num, guess):
###################################################################### ######################################################################
# Intro text def main():
print("\n Bagels") # Intro text
print("Creative Computing Morristown, New Jersey") print("\n Bagels")
print("\n\n") print("Creative Computing Morristown, New Jersey")
print("\n\n")
# Anything other than N* will show the rules # Anything other than N* will show the rules
response = input("Would you like the rules (Yes or No)? ") response = input("Would you like the rules (Yes or No)? ")
if len(response) > 0: if len(response) > 0:
if response.upper()[0] != "N": if response.upper()[0] != "N":
print_rules()
else:
print_rules() print_rules()
else:
print_rules()
games_won = 0 games_won = 0
still_running = True still_running = True
while still_running: while still_running:
# New round # New round
num = pick_number() num = pick_number()
num_str = "".join(num) num_str = "".join(num)
guesses = 1 guesses = 1
print("\nO.K. I have a number in mind.") print("\nO.K. I have a number in mind.")
guessing = True guessing = True
while guessing: while guessing:
guess = get_valid_guess() guess = get_valid_guess()
if guess == num_str: if guess == num_str:
print("You got it!!!\n") print("You got it!!!\n")
games_won += 1 games_won += 1
guessing = False
else:
print(build_result_string(num, guess))
guesses += 1
if guesses > MAX_GUESSES:
print("Oh well")
print(f"That's {MAX_GUESSES} guesses. My number was {num_str}")
guessing = False guessing = False
else:
print(build_result_string(num, guess))
guesses += 1
if guesses > MAX_GUESSES:
print("Oh well")
print(f"That's {MAX_GUESSES} guesses. My number was {num_str}")
guessing = False
valid_response = False valid_response = False
while not valid_response: while not valid_response:
response = input("Play again (Yes or No)? ") response = input("Play again (Yes or No)? ")
if len(response) > 0: if len(response) > 0:
valid_response = True valid_response = True
if response.upper()[0] != "Y": if response.upper()[0] != "Y":
still_running = False still_running = False
if games_won > 0:
print(f"\nA {games_won} point Bagels buff!!")
print("Hope you had fun. Bye.\n")
if games_won > 0: if __name__ == "__main__":
print(f"\nA {games_won} point Bagels buff!!") main()
print("Hope you had fun. Bye.\n")
###################################################################### ######################################################################
# #

View File

@@ -353,4 +353,5 @@ class Basketball:
self.opponent_jumpshot() self.opponent_jumpshot()
new_game = Basketball() if __name__ == "__main__":
Basketball()

View File

@@ -49,254 +49,259 @@ def print_legs(n_legs):
print() print()
print_n_whitespaces(34) def main():
print("BUG") print_n_whitespaces(34)
print_n_whitespaces(15) print("BUG")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_n_whitespaces(15)
print_n_newlines(3) print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(3)
print("THE GAME BUG") print("THE GAME BUG")
print("I HOPE YOU ENJOY THIS GAME.") print("I HOPE YOU ENJOY THIS GAME.")
print()
Z = input("DO YOU WANT INSTRUCTIONS? ")
if Z != "NO":
print("THE OBJECT OF BUG IS TO FINISH YOUR BUG BEFORE I FINISH")
print("MINE. EACH NUMBER STANDS FOR A PART OF THE BUG BODY.")
print("I WILL ROLL THE DIE FOR YOU, TELL YOU WHAT I ROLLED FOR YOU")
print("WHAT THE NUMBER STANDS FOR, AND IF YOU CAN GET THE PART.")
print("IF YOU CAN GET THE PART I WILL GIVE IT TO YOU.")
print("THE SAME WILL HAPPEN ON MY TURN.")
print("IF THERE IS A CHANGE IN EITHER BUG I WILL GIVE YOU THE")
print("OPTION OF SEEING THE PICTURES OF THE BUGS.")
print("THE NUMBERS STAND FOR PARTS AS FOLLOWS:")
table = [
["NUMBER", "PART", "NUMBER OF PART NEEDED"],
["1", "BODY", "1"],
["2", "NECK", "1"],
["3", "HEAD", "1"],
["4", "FEELERS", "2"],
["5", "TAIL", "1"],
["6", "LEGS", "6"],
]
for row in table:
print(f"{row[0]:<16}{row[1]:<16}{row[2]:<20}")
print_n_newlines(2)
A = 0
B = 0
H = 0
L = 0
N = 0
P = 0
Q = 0
R = 0 # NECK
S = 0 # FEELERS
T = 0
U = 0
V = 0
Y = 0
while Y <= 0:
Z = random.randint(1, 6)
print() print()
C = 1 Z = input("DO YOU WANT INSTRUCTIONS? ")
print("YOU ROLLED A", Z)
if Z == 1:
print("1=BODY")
if B == 1:
print("YOU DO NOT NEED A BODY.")
# goto 970
else:
print("YOU NOW HAVE A BODY.")
B = 1
C = 0
# goto 970
elif Z == 2:
print("2=NECK")
if N == 1:
print("YOU DO NOT NEED A NECK.")
# goto 970
elif B == 0:
print("YOU DO NOT HAVE A BODY.")
# goto 970
else:
print("YOU NOW HAVE A NECK.")
N = 1
C = 0
# goto 970
elif Z == 3:
print("3=HEAD")
if N == 0:
print("YOU DO NOT HAVE A NECK.")
# goto 970
elif H == 1:
print("YOU HAVE A HEAD.")
# goto 970
else:
print("YOU NEEDED A HEAD.")
H = 1
C = 0
# goto 970
elif Z == 4:
print("4=FEELERS")
if H == 0:
print("YOU DO NOT HAVE A HEAD.")
# goto 970
elif A == 2:
print("YOU HAVE TWO FEELERS ALREADY.")
# goto 970
else:
print("I NOW GIVE YOU A FEELER.")
A = A + 1
C = 0
# goto 970
elif Z == 5:
print("5=TAIL")
if B == 0:
print("YOU DO NOT HAVE A BODY.")
# goto 970
elif T == 1:
print("YOU ALREADY HAVE A TAIL.")
# goto 970
else:
print("I NOW GIVE YOU A TAIL.")
T = T + 1
C = 0
# goto 970
elif Z == 6:
print("6=LEG")
if L == 6:
print("YOU HAVE 6 FEET ALREADY.")
# goto 970
elif B == 0:
print("YOU DO NOT HAVE A BODY.")
# goto 970
else:
L = L + 1
C = 0
print(f"YOU NOW HAVE {L} LEGS")
# goto 970
# 970
X = random.randint(1, 6)
print()
time.sleep(2)
print("I ROLLED A", X)
if X == 1:
print("1=BODY")
if P == 1:
print("I DO NOT NEED A BODY.")
# goto 1630
else:
print("I NOW HAVE A BODY.")
C = 0
P = 1
# goto 1630
elif X == 2:
print("2=NECK")
if Q == 1:
print("I DO NOT NEED A NECK.")
# goto 1630
elif P == 0:
print("I DO NOT HAVE A BODY.")
# goto 1630
else:
print("I NOW HAVE A NECK.")
Q = 1
C = 0
# goto 1630
elif X == 3:
print("3=HEAD")
if Q == 0:
print("I DO NOT HAVE A NECK.")
# goto 1630
elif R == 1:
print("I HAVE A HEAD.")
# goto 1630
else:
print("I NEEDED A HEAD.")
R = 1
C = 0
# goto 1630
elif X == 4:
print("4=FEELERS")
if R == 0:
print("I DO NOT HAVE A HEAD.")
# goto 1630
elif S == 2:
print("I HAVE TWO FEELERS ALREADY.")
# goto 1630
else:
print("I GET A FEELER.")
S = S + 1
C = 0
# goto 1630
elif X == 5:
print("5=TAIL")
if P == 0:
print("I DO NOT HAVE A BODY.")
# goto 1630
elif U == 1:
print("I ALREADY HAVE A TAIL.")
# goto 1630
else:
print("I NOW HAVE A TAIL.")
U = 1
C = 0
# goto 1630
elif X == 6:
print("6=LEG")
if V == 6:
print("I HAVE 6 FEET.")
# goto 1630
elif P == 0:
print("I DO NOT HAVE A BODY.")
# goto 1630
else:
V = V + 1
C = 0
print(f"I NOW HAVE {V} LEGS")
# goto 1630
# 1630
if (A == 2) and (T == 1) and (L == 6):
print("YOUR BUG IS FINISHED.")
Y = Y + 1
if (S == 2) and (P == 1) and (V == 6):
print("MY BUG IS FINISHED.")
Y = Y + 2
if C == 1:
continue
Z = input("DO YOU WANT THE PICTURES? ")
if Z != "NO": if Z != "NO":
print("*****YOUR BUG*****") print("THE OBJECT OF BUG IS TO FINISH YOUR BUG BEFORE I FINISH")
print("MINE. EACH NUMBER STANDS FOR A PART OF THE BUG BODY.")
print("I WILL ROLL THE DIE FOR YOU, TELL YOU WHAT I ROLLED FOR YOU")
print("WHAT THE NUMBER STANDS FOR, AND IF YOU CAN GET THE PART.")
print("IF YOU CAN GET THE PART I WILL GIVE IT TO YOU.")
print("THE SAME WILL HAPPEN ON MY TURN.")
print("IF THERE IS A CHANGE IN EITHER BUG I WILL GIVE YOU THE")
print("OPTION OF SEEING THE PICTURES OF THE BUGS.")
print("THE NUMBERS STAND FOR PARTS AS FOLLOWS:")
table = [
["NUMBER", "PART", "NUMBER OF PART NEEDED"],
["1", "BODY", "1"],
["2", "NECK", "1"],
["3", "HEAD", "1"],
["4", "FEELERS", "2"],
["5", "TAIL", "1"],
["6", "LEGS", "6"],
]
for row in table:
print(f"{row[0]:<16}{row[1]:<16}{row[2]:<20}")
print_n_newlines(2) print_n_newlines(2)
if A != 0:
print_feelers(A, is_player=True)
if H != 0:
print_head()
if N != 0:
print_neck()
if B != 0:
print_body(True) if T == 1 else print_body(False)
if L != 0:
print_legs(L)
print_n_newlines(4)
print("*****MY BUG*****")
print_n_newlines(3)
if S != 0:
print_feelers(S, is_player=False)
if R == 1:
print_head()
if Q != 0:
print_neck()
if P != 0:
print_body(True) if U == 1 else print_body(False)
if V != 0:
print_legs(V)
if Y != 0: A = 0
break B = 0
H = 0
L = 0
N = 0
P = 0
Q = 0
R = 0 # NECK
S = 0 # FEELERS
T = 0
U = 0
V = 0
Y = 0
print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!") while Y <= 0:
Z = random.randint(1, 6)
print()
C = 1
print("YOU ROLLED A", Z)
if Z == 1:
print("1=BODY")
if B == 1:
print("YOU DO NOT NEED A BODY.")
# goto 970
else:
print("YOU NOW HAVE A BODY.")
B = 1
C = 0
# goto 970
elif Z == 2:
print("2=NECK")
if N == 1:
print("YOU DO NOT NEED A NECK.")
# goto 970
elif B == 0:
print("YOU DO NOT HAVE A BODY.")
# goto 970
else:
print("YOU NOW HAVE A NECK.")
N = 1
C = 0
# goto 970
elif Z == 3:
print("3=HEAD")
if N == 0:
print("YOU DO NOT HAVE A NECK.")
# goto 970
elif H == 1:
print("YOU HAVE A HEAD.")
# goto 970
else:
print("YOU NEEDED A HEAD.")
H = 1
C = 0
# goto 970
elif Z == 4:
print("4=FEELERS")
if H == 0:
print("YOU DO NOT HAVE A HEAD.")
# goto 970
elif A == 2:
print("YOU HAVE TWO FEELERS ALREADY.")
# goto 970
else:
print("I NOW GIVE YOU A FEELER.")
A = A + 1
C = 0
# goto 970
elif Z == 5:
print("5=TAIL")
if B == 0:
print("YOU DO NOT HAVE A BODY.")
# goto 970
elif T == 1:
print("YOU ALREADY HAVE A TAIL.")
# goto 970
else:
print("I NOW GIVE YOU A TAIL.")
T = T + 1
C = 0
# goto 970
elif Z == 6:
print("6=LEG")
if L == 6:
print("YOU HAVE 6 FEET ALREADY.")
# goto 970
elif B == 0:
print("YOU DO NOT HAVE A BODY.")
# goto 970
else:
L = L + 1
C = 0
print(f"YOU NOW HAVE {L} LEGS")
# goto 970
# 970
X = random.randint(1, 6)
print()
time.sleep(2)
print("I ROLLED A", X)
if X == 1:
print("1=BODY")
if P == 1:
print("I DO NOT NEED A BODY.")
# goto 1630
else:
print("I NOW HAVE A BODY.")
C = 0
P = 1
# goto 1630
elif X == 2:
print("2=NECK")
if Q == 1:
print("I DO NOT NEED A NECK.")
# goto 1630
elif P == 0:
print("I DO NOT HAVE A BODY.")
# goto 1630
else:
print("I NOW HAVE A NECK.")
Q = 1
C = 0
# goto 1630
elif X == 3:
print("3=HEAD")
if Q == 0:
print("I DO NOT HAVE A NECK.")
# goto 1630
elif R == 1:
print("I HAVE A HEAD.")
# goto 1630
else:
print("I NEEDED A HEAD.")
R = 1
C = 0
# goto 1630
elif X == 4:
print("4=FEELERS")
if R == 0:
print("I DO NOT HAVE A HEAD.")
# goto 1630
elif S == 2:
print("I HAVE TWO FEELERS ALREADY.")
# goto 1630
else:
print("I GET A FEELER.")
S = S + 1
C = 0
# goto 1630
elif X == 5:
print("5=TAIL")
if P == 0:
print("I DO NOT HAVE A BODY.")
# goto 1630
elif U == 1:
print("I ALREADY HAVE A TAIL.")
# goto 1630
else:
print("I NOW HAVE A TAIL.")
U = 1
C = 0
# goto 1630
elif X == 6:
print("6=LEG")
if V == 6:
print("I HAVE 6 FEET.")
# goto 1630
elif P == 0:
print("I DO NOT HAVE A BODY.")
# goto 1630
else:
V = V + 1
C = 0
print(f"I NOW HAVE {V} LEGS")
# goto 1630
# 1630
if (A == 2) and (T == 1) and (L == 6):
print("YOUR BUG IS FINISHED.")
Y = Y + 1
if (S == 2) and (P == 1) and (V == 6):
print("MY BUG IS FINISHED.")
Y = Y + 2
if C == 1:
continue
Z = input("DO YOU WANT THE PICTURES? ")
if Z != "NO":
print("*****YOUR BUG*****")
print_n_newlines(2)
if A != 0:
print_feelers(A, is_player=True)
if H != 0:
print_head()
if N != 0:
print_neck()
if B != 0:
print_body(True) if T == 1 else print_body(False)
if L != 0:
print_legs(L)
print_n_newlines(4)
print("*****MY BUG*****")
print_n_newlines(3)
if S != 0:
print_feelers(S, is_player=False)
if R == 1:
print_head()
if Q != 0:
print_neck()
if P != 0:
print_body(True) if U == 1 else print_body(False)
if V != 0:
print_legs(V)
if Y != 0:
break
print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!")
if __name__ == "__main__":
main()

View File

@@ -214,28 +214,35 @@ while True:
if death: if death:
break break
# 1310
print_n_newlines(3)
if D[4] == 0: def main():
print("THE CROWD BOOS FOR TEN MINUTES. IF YOU EVER DARE TO SHOW") # 1310
print("YOUR FACE IN A RING AGAIN, THEY SWEAR THEY WILL KILL YOU--")
print("UNLESS THE BULL DOES FIRST.")
else:
if D[4] == 2:
print("THE CROWD CHEERS WILDLY!")
elif D[5] == 2:
print("THE CROWD CHEERS!")
print()
print("THE CROWD AWARDS YOU")
if FNC() < 2.4:
print("NOTHING AT ALL.")
elif FNC() < 4.9:
print("ONE EAR OF THE BULL.")
elif FNC() < 7.4:
print("BOTH EARS OF THE BULL!")
print("OLE!")
else:
print("OLE! YOU ARE 'MUY HOMBRE'!! OLE! OLE!")
print()
print("ADIOS")
print_n_newlines(3) print_n_newlines(3)
if D[4] == 0:
print("THE CROWD BOOS FOR TEN MINUTES. IF YOU EVER DARE TO SHOW")
print("YOUR FACE IN A RING AGAIN, THEY SWEAR THEY WILL KILL YOU--")
print("UNLESS THE BULL DOES FIRST.")
else:
if D[4] == 2:
print("THE CROWD CHEERS WILDLY!")
elif D[5] == 2:
print("THE CROWD CHEERS!")
print()
print("THE CROWD AWARDS YOU")
if FNC() < 2.4:
print("NOTHING AT ALL.")
elif FNC() < 4.9:
print("ONE EAR OF THE BULL.")
elif FNC() < 7.4:
print("BOTH EARS OF THE BULL!")
print("OLE!")
else:
print("OLE! YOU ARE 'MUY HOMBRE'!! OLE! OLE!")
print()
print("ADIOS")
print_n_newlines(3)
if __name__ == "__main__":
main()

View File

@@ -10,108 +10,113 @@ def print_n_newlines(n: int):
print() print()
print_n_whitespaces(32) def main():
print("BULLSEYE") print_n_whitespaces(32)
print_n_whitespaces(15) print("BULLSEYE")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_n_whitespaces(15)
print_n_newlines(3) print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET") print_n_newlines(3)
print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS") print("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET")
print("TO GET 200 POINTS.") print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS")
print() print("TO GET 200 POINTS.")
print("THROW", end="") print()
print_n_whitespaces(20) print("THROW", end="")
print("DESCRIPTION", end="") print_n_whitespaces(20)
print_n_whitespaces(45) print("DESCRIPTION", end="")
print("PROBABLE SCORE") print_n_whitespaces(45)
print(" 1", end="") print("PROBABLE SCORE")
print_n_whitespaces(20) print(" 1", end="")
print("FAST OVERARM", end="") print_n_whitespaces(20)
print_n_whitespaces(45) print("FAST OVERARM", end="")
print("BULLSEYE OR COMPLETE MISS") print_n_whitespaces(45)
print(" 2", end="") print("BULLSEYE OR COMPLETE MISS")
print_n_whitespaces(20) print(" 2", end="")
print("CONTROLLED OVERARM", end="") print_n_whitespaces(20)
print_n_whitespaces(45) print("CONTROLLED OVERARM", end="")
print("10, 20 OR 30 POINTS") print_n_whitespaces(45)
print(" 3", end="") print("10, 20 OR 30 POINTS")
print_n_whitespaces(20) print(" 3", end="")
print("UNDERARM", end="") print_n_whitespaces(20)
print_n_whitespaces(45) print("UNDERARM", end="")
print("ANYTHING") print_n_whitespaces(45)
print() print("ANYTHING")
nb_winners = 0
round = 0
winners = {}
for i in range(1, 11):
winners[i] = 0
total_score = {}
for i in range(1, 21):
total_score[i] = 0
nb_players = int(input("HOW MANY PLAYERS? "))
player_names = {}
for i in range(1, nb_players + 1):
player_name = input("NAME OF PLAYER #")
player_names[i] = player_name
while nb_winners == 0:
round = round + 1
print() print()
print(f"ROUND {round}---------")
for i in range(1, nb_players + 1):
print()
while True:
throw = int(input(f"{player_names[i]}'S THROW? "))
if throw not in [1, 2, 3]:
print("INPUT 1, 2, OR 3!")
else:
break
if throw == 1:
P1 = 0.65
P2 = 0.55
P3 = 0.5
P4 = 0.5
elif throw == 2:
P1 = 0.99
P2 = 0.77
P3 = 0.43
P4 = 0.01
elif throw == 3:
P1 = 0.95
P2 = 0.75
P3 = 0.45
P4 = 0.05
throwing_luck = random.random()
if throwing_luck >= P1:
print("BULLSEYE!! 40 POINTS!")
points = 40
elif throwing_luck >= P2:
print("30-POINT ZONE!")
points = 30
elif throwing_luck >= P3:
print("20-POINT ZONE")
points = 20
elif throwing_luck >= P4:
print("WHEW! 10 POINTS.")
points = 10
else:
print("MISSED THE TARGET! TOO BAD.")
points = 0
total_score[i] = total_score[i] + points
print(f"TOTAL SCORE = {total_score[i]}")
for player_index in range(1, nb_players + 1):
if total_score[player_index] > 200:
nb_winners = nb_winners + 1
winners[nb_winners] = player_index
print() nb_winners = 0
print("WE HAVE A WINNER!!") round = 0
print()
for i in range(1, nb_winners + 1): winners = {}
print(f"{player_names[winners[i]]} SCORED {total_score[winners[i]]} POINTS.") for i in range(1, 11):
print() winners[i] = 0
print("THANKS FOR THE GAME.")
total_score = {}
for i in range(1, 21):
total_score[i] = 0
nb_players = int(input("HOW MANY PLAYERS? "))
player_names = {}
for i in range(1, nb_players + 1):
player_name = input("NAME OF PLAYER #")
player_names[i] = player_name
while nb_winners == 0:
round = round + 1
print()
print(f"ROUND {round}---------")
for i in range(1, nb_players + 1):
print()
while True:
throw = int(input(f"{player_names[i]}'S THROW? "))
if throw not in [1, 2, 3]:
print("INPUT 1, 2, OR 3!")
else:
break
if throw == 1:
P1 = 0.65
P2 = 0.55
P3 = 0.5
P4 = 0.5
elif throw == 2:
P1 = 0.99
P2 = 0.77
P3 = 0.43
P4 = 0.01
elif throw == 3:
P1 = 0.95
P2 = 0.75
P3 = 0.45
P4 = 0.05
throwing_luck = random.random()
if throwing_luck >= P1:
print("BULLSEYE!! 40 POINTS!")
points = 40
elif throwing_luck >= P2:
print("30-POINT ZONE!")
points = 30
elif throwing_luck >= P3:
print("20-POINT ZONE")
points = 20
elif throwing_luck >= P4:
print("WHEW! 10 POINTS.")
points = 10
else:
print("MISSED THE TARGET! TOO BAD.")
points = 0
total_score[i] = total_score[i] + points
print(f"TOTAL SCORE = {total_score[i]}")
for player_index in range(1, nb_players + 1):
if total_score[player_index] > 200:
nb_winners = nb_winners + 1
winners[nb_winners] = player_index
print()
print("WE HAVE A WINNER!!")
print()
for i in range(1, nb_winners + 1):
print(f"{player_names[winners[i]]} SCORED {total_score[winners[i]]} POINTS.")
print()
print("THANKS FOR THE GAME.")
if __name__ == "__main__":
main()

View File

@@ -22,86 +22,89 @@
import random import random
WORDS = [
[
"Ability",
"Basal",
"Behavioral",
"Child-centered",
"Differentiated",
"Discovery",
"Flexible",
"Heterogeneous",
"Homogenous",
"Manipulative",
"Modular",
"Tavistock",
"Individualized",
],
[
"learning",
"evaluative",
"objective",
"cognitive",
"enrichment",
"scheduling",
"humanistic",
"integrated",
"non-graded",
"training",
"vertical age",
"motivational",
"creative",
],
[
"grouping",
"modification",
"accountability",
"process",
"core curriculum",
"algorithm",
"performance",
"reinforcement",
"open classroom",
"resource",
"structure",
"facility",
"environment",
],
]
def main():
WORDS = [
[
"Ability",
"Basal",
"Behavioral",
"Child-centered",
"Differentiated",
"Discovery",
"Flexible",
"Heterogeneous",
"Homogenous",
"Manipulative",
"Modular",
"Tavistock",
"Individualized",
],
[
"learning",
"evaluative",
"objective",
"cognitive",
"enrichment",
"scheduling",
"humanistic",
"integrated",
"non-graded",
"training",
"vertical age",
"motivational",
"creative",
],
[
"grouping",
"modification",
"accountability",
"process",
"core curriculum",
"algorithm",
"performance",
"reinforcement",
"open classroom",
"resource",
"structure",
"facility",
"environment",
],
]
# Display intro text # Display intro text
print("\n Buzzword Generator") print("\n Buzzword Generator")
print("Creative Computing Morristown, New Jersey") print("Creative Computing Morristown, New Jersey")
print("\n\n") print("\n\n")
print("This program prints highly acceptable phrases in") print("This program prints highly acceptable phrases in")
print("'educator-speak' that you can work into reports") print("'educator-speak' that you can work into reports")
print("and speeches. Whenever a question mark is printed,") print("and speeches. Whenever a question mark is printed,")
print("type a 'Y' for another phrase or 'N' to quit.") print("type a 'Y' for another phrase or 'N' to quit.")
print("\n\nHere's the first phrase:") print("\n\nHere's the first phrase:")
still_running = True still_running = True
while still_running: while still_running:
phrase = "" phrase = ""
for section in WORDS: for section in WORDS:
if len(phrase) > 0: if len(phrase) > 0:
phrase += " " phrase += " "
phrase += section[random.randint(0, len(section) - 1)] phrase += section[random.randint(0, len(section) - 1)]
print(phrase) print(phrase)
print("") print("")
response = input("? ") response = input("? ")
try: try:
if response.upper()[0] != "Y": if response.upper()[0] != "Y":
still_running = False
except Exception:
still_running = False still_running = False
except Exception:
still_running = False print("Come back when you need help with another report!\n")
print("Come back when you need help with another report!\n") if __name__ == "__main__":
main()
###################################################################### ######################################################################
# #

View File

@@ -18,64 +18,69 @@ def throw_dice():
return randint(1, 6) + randint(1, 6) return randint(1, 6) + randint(1, 6)
print(" " * 33 + "Craps") def main():
print(" " * 15 + "Creative Computing Morristown, New Jersey") print(" " * 33 + "Craps")
print() print(" " * 15 + "Creative Computing Morristown, New Jersey")
print() print()
print() print()
print()
winnings = 0 winnings = 0
print("2,3,12 are losers; 4,5,6,8,9,10 are points; 7,11 are natural winners.") print("2,3,12 are losers; 4,5,6,8,9,10 are points; 7,11 are natural winners.")
play_again = True play_again = True
while play_again: while play_again:
wager = int(input("Input the amount of your wager: ")) wager = int(input("Input the amount of your wager: "))
print("I will now throw the dice") print("I will now throw the dice")
roll_1 = throw_dice() roll_1 = throw_dice()
if roll_1 in [7, 11]: if roll_1 in [7, 11]:
print(f"{roll_1} - natural.... a winner!!!!") print(f"{roll_1} - natural.... a winner!!!!")
print(f"{roll_1} pays even money, you win {wager} dollars") print(f"{roll_1} pays even money, you win {wager} dollars")
winnings += wager winnings += wager
elif roll_1 == 2: elif roll_1 == 2:
print(f"{roll_1} - snake eyes.... you lose.") print(f"{roll_1} - snake eyes.... you lose.")
print(f"You lose {wager} dollars") print(f"You lose {wager} dollars")
winnings -= wager winnings -= wager
elif roll_1 in [3, 12]: elif roll_1 in [3, 12]:
print(f"{roll_1} - craps.... you lose.") print(f"{roll_1} - craps.... you lose.")
print(f"You lose {wager} dollars") print(f"You lose {wager} dollars")
winnings -= wager winnings -= wager
else: else:
print(f"{roll_1} is the point. I will roll again") print(f"{roll_1} is the point. I will roll again")
roll_2 = 0 roll_2 = 0
while roll_2 not in [roll_1, 7]: while roll_2 not in [roll_1, 7]:
roll_2 = throw_dice() roll_2 = throw_dice()
if roll_2 == 7: if roll_2 == 7:
print(f"{roll_2} - craps. You lose.") print(f"{roll_2} - craps. You lose.")
print(f"You lose $ {wager}") print(f"You lose $ {wager}")
winnings -= wager winnings -= wager
elif roll_2 == roll_1: elif roll_2 == roll_1:
print(f"{roll_1} - a winner.........congrats!!!!!!!!") print(f"{roll_1} - a winner.........congrats!!!!!!!!")
print( print(
f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars" f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars"
) )
winnings += 2 * wager winnings += 2 * wager
else: else:
print(f"{roll_2} - no point. I will roll again") print(f"{roll_2} - no point. I will roll again")
m = input(" If you want to play again print 5 if not print 2: ")
if winnings < 0:
print(f"You are now under ${-winnings}")
elif winnings > 0:
print(f"You are now ahead ${winnings}")
else:
print("You are now even at 0")
play_again = m == "5"
m = input(" If you want to play again print 5 if not print 2: ")
if winnings < 0: if winnings < 0:
print(f"You are now under ${-winnings}") print("Too bad, you are in the hole. Come again.")
elif winnings > 0: elif winnings > 0:
print(f"You are now ahead ${winnings}") print("Congratulations---you came out a winner. Come again.")
else: else:
print("You are now even at 0") print("Congratulations---you came out even, not bad for an amateur")
play_again = m == "5"
if winnings < 0:
print("Too bad, you are in the hole. Come again.") if __name__ == "__main__":
elif winnings > 0: main()
print("Congratulations---you came out a winner. Come again.")
else:
print("Congratulations---you came out even, not bad for an amateur")

View File

@@ -28,50 +28,54 @@
import random import random
# We'll track counts of roll outcomes in a 13-element list.
# The first two indices (0 & 1) are ignored, leaving just def main():
# the indices that match the roll values (2 through 12). # We'll track counts of roll outcomes in a 13-element list.
freq = [0] * 13 # The first two indices (0 & 1) are ignored, leaving just
# the indices that match the roll values (2 through 12).
freq = [0] * 13
# Display intro text
print("\n Dice")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
# "Danny Freidus"
print("This program simulates the rolling of a")
print("pair of dice.")
print("You enter the number of times you want the computer to")
print("'roll' the dice. Watch out, very large numbers take")
print("a long time. In particular, numbers over 5000.")
still_playing = True
while still_playing:
print("")
n = int(input("How many rolls? "))
# Roll the dice n times
for _ in range(n):
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll_total = die1 + die2
freq[roll_total] += 1
# Display final results
print("\nTotal Spots Number of Times")
for i in range(2, 13):
print(" %-14d%d" % (i, freq[i]))
# Keep playing?
print("")
response = input("Try again? ")
if len(response) > 0 and response.upper()[0] == "Y":
# Clear out the frequency list
freq = [0] * 13
else:
# Exit the game loop
still_playing = False
# Display intro text if __name__ == "__main__":
print("\n Dice") main()
print("Creative Computing Morristown, New Jersey")
print("\n\n")
# "Danny Freidus"
print("This program simulates the rolling of a")
print("pair of dice.")
print("You enter the number of times you want the computer to")
print("'roll' the dice. Watch out, very large numbers take")
print("a long time. In particular, numbers over 5000.")
still_playing = True
while still_playing:
print("")
n = int(input("How many rolls? "))
# Roll the dice n times
for _ in range(n):
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
roll_total = die1 + die2
freq[roll_total] += 1
# Display final results
print("\nTotal Spots Number of Times")
for i in range(2, 13):
print(" %-14d%d" % (i, freq[i]))
# Keep playing?
print("")
response = input("Try again? ")
if len(response) > 0 and response.upper()[0] == "Y":
# Clear out the frequency list
freq = [0] * 13
else:
# Exit the game loop
still_playing = False
######################################################## ########################################################
# #

View File

@@ -55,42 +55,47 @@ def limit_set():
return limit, limit_goal return limit, limit_goal
limit, limit_goal = limit_set() def main():
while True: limit, limit_goal = limit_set()
guess_count = 1 while True:
still_guessing = True guess_count = 1
won = False still_guessing = True
my_guess = int(limit * random() + 1) won = False
my_guess = int(limit * random() + 1)
print(f"I'm thinking of a number between 1 and {limit}") print(f"I'm thinking of a number between 1 and {limit}")
print("Now you try to guess what it is.") print("Now you try to guess what it is.")
while still_guessing: while still_guessing:
n = int(input()) n = int(input())
if n < 0: if n < 0:
break break
insert_whitespaces() insert_whitespaces()
if n < my_guess: if n < my_guess:
print("Too low. Try a bigger answer") print("Too low. Try a bigger answer")
guess_count += 1 guess_count += 1
elif n > my_guess: elif n > my_guess:
print("Too high. Try a smaller answer") print("Too high. Try a smaller answer")
guess_count += 1 guess_count += 1
else:
print(f"That's it! You got it in {guess_count} tries")
won = True
still_guessing = False
if won:
if guess_count < limit_goal:
print("Very good.")
elif guess_count == limit_goal:
print("Good.")
else:
print(f"You should have been able to get it in only {limit_goal}")
insert_whitespaces()
else: else:
print(f"That's it! You got it in {guess_count} tries") insert_whitespaces()
won = True limit, limit_goal = limit_set()
still_guessing = False
if won:
if guess_count < limit_goal: if __name__ == "__main__":
print("Very good.") main()
elif guess_count == limit_goal:
print("Good.")
else:
print(f"You should have been able to get it in only {limit_goal}")
insert_whitespaces()
else:
insert_whitespaces()
limit, limit_goal = limit_set()

View File

@@ -71,42 +71,48 @@ DATA = [
# is the line length used by every row # is the line length used by every row
ROW_LEN = sum(DATA[0]) ROW_LEN = sum(DATA[0])
# Display intro text
print("\n Love")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
print("A tribute to the great American artist, Robert Indiana.")
print("His great work will be reproduced with a message of")
print("your choice up to 60 characters. If you can't think of")
print("a message, simple type the word 'love'\n") # (sic)
# Get message from user def main():
message = input("Your message, please? ") # Display intro text
if message == "": print("\n Love")
message = "LOVE" print("Creative Computing Morristown, New Jersey")
print("\n\n")
print("A tribute to the great American artist, Robert Indiana.")
print("His great work will be reproduced with a message of")
print("your choice up to 60 characters. If you can't think of")
print("a message, simple type the word 'love'\n") # (sic)
# Repeat the message until we get at least one line's worth # Get message from user
while len(message) < ROW_LEN: message = input("Your message, please? ")
message += message if message == "":
message = "LOVE"
# Display image # Repeat the message until we get at least one line's worth
print("\n" * 9) while len(message) < ROW_LEN:
for row in DATA: message += message
print_message = True
position = 0
line_text = ""
for length in row:
if print_message:
text = message[position : (position + length)]
print_message = False
else:
text = " " * length
print_message = True
line_text += text
position += length
print(line_text)
print("") # Display image
print("\n" * 9)
for row in DATA:
print_message = True
position = 0
line_text = ""
for length in row:
if print_message:
text = message[position : (position + length)]
print_message = False
else:
text = " " * length
print_message = True
line_text += text
position += length
print(line_text)
print("")
if __name__ == "__main__":
main()
###################################################################### ######################################################################

View File

@@ -59,4 +59,5 @@ def main():
print("HAVE A NICE DAY!") print("HAVE A NICE DAY!")
main() if __name__ == "__main__":
main()

View File

@@ -39,39 +39,43 @@ def parse_input():
return i return i
initial_message() def main():
while True: initial_message()
dead = False while True:
n = 0 dead = False
print("Type '1' to Spin chamber and pull trigger") n = 0
print("Type '2' to Give up") print("Type '1' to Spin chamber and pull trigger")
print("Go") print("Type '2' to Give up")
while not dead: print("Go")
i = parse_input() while not dead:
i = parse_input()
if i == 2: if i == 2:
break break
if random() > 0.8333333333333334: if random() > 0.8333333333333334:
dead = True dead = True
else:
print("- CLICK -\n")
n += 1
if n > NUMBER_OF_ROUNDS:
break
if dead:
print("BANG!!!!! You're Dead!")
print("Condolences will be sent to your relatives.\n\n\n")
print("...Next victim...")
else: else:
print("- CLICK -\n") if n > NUMBER_OF_ROUNDS:
n += 1 print("You win!!!!!")
print("Let someone else blow his brain out.\n")
else:
print(" Chicken!!!!!\n\n\n")
print("...Next victim....")
if n > NUMBER_OF_ROUNDS:
break
if dead:
print("BANG!!!!! You're Dead!")
print("Condolences will be sent to your relatives.\n\n\n")
print("...Next victim...")
else:
if n > NUMBER_OF_ROUNDS:
print("You win!!!!!")
print("Let someone else blow his brain out.\n")
else:
print(" Chicken!!!!!\n\n\n")
print("...Next victim....")
if __name__ == "__main__":
main()
######################################################## ########################################################
# Porting Notes # Porting Notes

View File

@@ -489,36 +489,36 @@ def execute_turn(turn):
# #
###################################### ######################################
######################
#
# main game flow
#
######################
# initialize the player and computer def main():
# boards # initialize the player and computer
initialize_game() # boards
initialize_game()
# execute turns until someone wins or we run # execute turns until someone wins or we run
# out of squares to shoot # out of squares to shoot
game_over = False game_over = False
while not game_over: while not game_over:
# increment the turn # increment the turn
current_turn = current_turn + 1 current_turn = current_turn + 1
print("\n") print("\n")
print("TURN", current_turn) print("TURN", current_turn)
# print("computer") # print("computer")
# print_board(computer_board) # print_board(computer_board)
# print("player") # print("player")
# print_board(player_board) # print_board(player_board)
if execute_turn(first_turn) == 0: if execute_turn(first_turn) == 0:
game_over = True game_over = True
continue continue
if execute_turn(second_turn) == 0: if execute_turn(second_turn) == 0:
game_over = True game_over = True
continue continue
if __name__ == "__main__":
main()

View File

@@ -24,47 +24,50 @@
import math import math
import time import time
# Constants
STRINGS = ("Creative", "Computing") # Text to display def main():
MAX_LINES = 160 # Constants
STEP_SIZE = 0.25 # Number of radians to increase at each STRINGS = ("Creative", "Computing") # Text to display
# line. Controls speed of horizontal MAX_LINES = 160
# printing movement. STEP_SIZE = 0.25 # Number of radians to increase at each
CENTER = 26 # Controls left edge of "middle" string # line. Controls speed of horizontal
DELAY = 0.05 # Amount of seconds to wait between lines # printing movement.
CENTER = 26 # Controls left edge of "middle" string
DELAY = 0.05 # Amount of seconds to wait between lines
# Display "intro" text
print("\n Sine Wave")
print(" Creative Computing Morristown, New Jersey")
print("\n\n\n\n")
# "REMarkable program by David Ahl"
string_index = 0
radians = 0
width = CENTER - 1
# "Start long loop"
for _line_num in range(MAX_LINES):
# Get string to display on this line
curr_string = STRINGS[string_index]
# Calculate how far over to print the text
sine = math.sin(radians)
padding = int(CENTER + width * sine)
print(curr_string.rjust(padding + len(curr_string)))
# Increase radians and increment our tuple index
radians += STEP_SIZE
string_index += 1
if string_index >= len(STRINGS):
string_index = 0
# Make sure the text doesn't fly by too fast...
time.sleep(DELAY)
# Display "intro" text if __name__ == "__main__":
print("\n Sine Wave") main()
print(" Creative Computing Morristown, New Jersey")
print("\n\n\n\n")
# "REMarkable program by David Ahl"
string_index = 0
radians = 0
width = CENTER - 1
# "Start long loop"
for _line_num in range(MAX_LINES):
# Get string to display on this line
curr_string = STRINGS[string_index]
# Calculate how far over to print the text
sine = math.sin(radians)
padding = int(CENTER + width * sine)
print(curr_string.rjust(padding + len(curr_string)))
# Increase radians and increment our tuple index
radians += STEP_SIZE
string_index += 1
if string_index >= len(STRINGS):
string_index = 0
# Make sure the text doesn't fly by too fast...
time.sleep(DELAY)
######################################################## ########################################################
# #

View File

@@ -160,39 +160,44 @@ def run():
medals["bronze"] += 1 medals["bronze"] += 1
while True: def main():
gates = ask_int("How many gates does this course have (1 to 25)")
if gates < 1:
print("Try again,")
else:
if gates > 25:
print("25 is the limit.")
break
pre_run()
while True:
lvl = ask_int("Rate yourself as a skier, (1=Worst, 3=Best)")
if lvl < 1 or lvl > 3:
print("The bounds are 1-3.")
else:
break
while True:
run()
while True: while True:
answer = ask("Do you want to play again?") gates = ask_int("How many gates does this course have (1 to 25)")
if answer == "YES" or answer == "NO": if gates < 1:
break print("Try again,")
else: else:
print('Please type "YES" or "NO"') if gates > 25:
if answer == "NO": print("25 is the limit.")
break break
print("Thanks for the race") pre_run()
if medals["gold"] > 0:
print(f"Gold medals: {medals['gold']}") while True:
if medals["silver"] > 0: lvl = ask_int("Rate yourself as a skier, (1=Worst, 3=Best)")
print(f"Silver medals: {medals['silver']}") if lvl < 1 or lvl > 3:
if medals["bronze"] > 0: print("The bounds are 1-3.")
print(f"Bronze medals: {medals['bronze']}") else:
break
while True:
run()
while True:
answer = ask("Do you want to play again?")
if answer == "YES" or answer == "NO":
break
else:
print('Please type "YES" or "NO"')
if answer == "NO":
break
print("Thanks for the race")
if medals["gold"] > 0:
print(f"Gold medals: {medals['gold']}")
if medals["silver"] > 0:
print(f"Silver medals: {medals['silver']}")
if medals["bronze"] > 0:
print(f"Bronze medals: {medals['bronze']}")
if __name__ == "__main__":
main()

View File

@@ -126,27 +126,31 @@ def final_message(profits):
print("Collect your winings from the H&M cashier.") print("Collect your winings from the H&M cashier.")
profits = 0 def main():
keep_betting = True profits = 0
keep_betting = True
initial_message() initial_message()
while keep_betting: while keep_betting:
m = input_betting() m = input_betting()
w = spin_wheels() w = spin_wheels()
profits = adjust_profits(w, m, profits) profits = adjust_profits(w, m, profits)
print(f"Your standings are ${profits}") print(f"Your standings are ${profits}")
answer = input("Again?") answer = input("Again?")
try: try:
if not answer[0].lower() == "y": if not answer[0].lower() == "y":
keep_betting = False
except IndexError:
keep_betting = False keep_betting = False
except IndexError:
keep_betting = False
final_message(profits) final_message(profits)
if __name__ == "__main__":
main()
###################################################################### ######################################################################
# #
# Porting notes # Porting notes

View File

@@ -293,27 +293,28 @@ def print_header():
) )
# def main():
# Main program. print_header()
#
print_header() successful_jumps = []
while True:
successful_jumps = [] chute_altitude = jump()
while True: if chute_altitude > 0:
chute_altitude = jump() # We want the statistics on previous jumps (i.e. not including the
if chute_altitude > 0: # current jump.)
# We want the statistics on previous jumps (i.e. not including the n_previous_jumps, n_better = jump_stats(successful_jumps, chute_altitude)
# current jump.) successful_jumps.append(chute_altitude)
n_previous_jumps, n_better = jump_stats(successful_jumps, chute_altitude) print_results(n_previous_jumps, n_better)
successful_jumps.append(chute_altitude) else:
print_results(n_previous_jumps, n_better) # Splat!
else: print("I'LL GIVE YOU ANOTHER CHANCE.")
# Splat! z = yes_no_input("DO YOU WANT TO PLAY AGAIN")
print("I'LL GIVE YOU ANOTHER CHANCE.")
z = yes_no_input("DO YOU WANT TO PLAY AGAIN")
if not z:
z = yes_no_input("PLEASE")
if not z: if not z:
print("SSSSSSSSSS.") z = yes_no_input("PLEASE")
break if not z:
print("SSSSSSSSSS.")
break
if __name__ == "__main__":
main()

View File

@@ -57,53 +57,57 @@ def get_guess():
return guess return guess
# Display intro text def main():
print("\n Stars") # Display intro text
print("Creative Computing Morristown, New Jersey") print("\n Stars")
print("\n\n") print("Creative Computing Morristown, New Jersey")
# "*** Stars - People's Computer Center, MenloPark, CA" print("\n\n")
# "*** Stars - People's Computer Center, MenloPark, CA"
response = input("Do you want instructions? ") response = input("Do you want instructions? ")
if response.upper()[0] == "Y": if response.upper()[0] == "Y":
print_instructions() print_instructions()
still_playing = True still_playing = True
while still_playing: while still_playing:
# "*** Computer thinks of a number" # "*** Computer thinks of a number"
secret_number = random.randint(1, MAX_NUM) secret_number = random.randint(1, MAX_NUM)
print("\n\nOK, I am thinking of a number, start guessing.") print("\n\nOK, I am thinking of a number, start guessing.")
# Init/start guess loop # Init/start guess loop
guess_number = 0 guess_number = 0
player_has_won = False player_has_won = False
while (guess_number < MAX_GUESSES) and not player_has_won: while (guess_number < MAX_GUESSES) and not player_has_won:
print("") print("")
guess = get_guess() guess = get_guess()
guess_number += 1 guess_number += 1
if guess == secret_number: if guess == secret_number:
# "*** We have a winner" # "*** We have a winner"
player_has_won = True player_has_won = True
print("**************************************************!!!") print("**************************************************!!!")
print(f"You got it in {guess_number} guesses!!!") print(f"You got it in {guess_number} guesses!!!")
else: else:
print_stars(secret_number, guess) print_stars(secret_number, guess)
# End of guess loop # End of guess loop
# "*** Did not guess in [MAX_GUESS] guesses" # "*** Did not guess in [MAX_GUESS] guesses"
if not player_has_won: if not player_has_won:
print(f"\nSorry, that's {guess_number} guesses, number was {secret_number}") print(f"\nSorry, that's {guess_number} guesses, number was {secret_number}")
# Keep playing? # Keep playing?
response = input("\nPlay again? ") response = input("\nPlay again? ")
if response.upper()[0] != "Y": if response.upper()[0] != "Y":
still_playing = False still_playing = False
if __name__ == "__main__":
main()
###################################################################### ######################################################################
# #
# Porting Notes # Porting Notes

View File

@@ -11,18 +11,23 @@ def equation(x: float) -> float:
return 30 * exp(-x * x / 100) return 30 * exp(-x * x / 100)
print(" " * 32 + "3D PLOT") def main():
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n\n") print(" " * 32 + "3D PLOT")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n\n")
for x in range(-300, 315, 15): for x in range(-300, 315, 15):
x1 = x / 10 x1 = x / 10
max_column = 0 max_column = 0
y1 = 5 * floor(sqrt(900 - x1 * x1) / 5) y1 = 5 * floor(sqrt(900 - x1 * x1) / 5)
y_plot = [" "] * 80 y_plot = [" "] * 80
for y in range(y1, -(y1 + 5), -5): for y in range(y1, -(y1 + 5), -5):
column = floor(25 + equation(sqrt(x1 * x1 + y * y)) - 0.7 * y) column = floor(25 + equation(sqrt(x1 * x1 + y * y)) - 0.7 * y)
if column > max_column: if column > max_column:
max_column = column max_column = column
y_plot[column] = "*" y_plot[column] = "*"
print("".join(y_plot)) print("".join(y_plot))
if __name__ == "__main__":
main()

View File

@@ -3,7 +3,7 @@ import unittest
import tower import tower
class MyTestCase(unittest.TestCase): class TowerTestCase(unittest.TestCase):
def test_something(self): def test_something(self):
t = tower.Tower() t = tower.Tower()
self.assertTrue(t.empty()) self.assertTrue(t.empty())
@@ -44,9 +44,6 @@ class MyTestCase(unittest.TestCase):
t.add(d5) t.add(d5)
t.add(d3) t.add(d3)
f = t.vertical_format(6, 3)
self.assertEqual(f, [" ", "[ 3 ] ", "[ 5 ] "])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@@ -44,23 +44,6 @@ class Tower:
print(r) print(r)
print(
"""
IN THIS PROGRAM, WE SHALL REFER TO DISKS BY NUMERICAL CODE.
3 WILL REPRESENT THE SMALLEST DISK, 5 THE NEXT SIZE,
7 THE NEXT, AND SO ON, UP TO 15. IF YOU DO THE PUZZLE WITH
2 DISKS, THEIR CODE NAMES WOULD BE 13 AND 15. WITH 3 DISKS
THE CODE NAMES WOULD BE 11, 13 AND 15, ETC. THE NEEDLES
ARE NUMBERED FROM LEFT TO RIGHT, 1 TO 3. WE WILL
START WITH THE DISKS ON NEEDLE 1, AND ATTEMPT TO MOVE THEM
TO NEEDLE 3.
GOOD LUCK!
"""
)
class Game: class Game:
def __init__(self): def __init__(self):
# use fewer sizes to make debugging easier # use fewer sizes to make debugging easier
@@ -144,27 +127,48 @@ class Game:
from_tower.add(disk) from_tower.add(disk)
game = Game() def main():
while True: print(
game.print() """
IN THIS PROGRAM, WE SHALL REFER TO DISKS BY NUMERICAL CODE.
3 WILL REPRESENT THE SMALLEST DISK, 5 THE NEXT SIZE,
7 THE NEXT, AND SO ON, UP TO 15. IF YOU DO THE PUZZLE WITH
2 DISKS, THEIR CODE NAMES WOULD BE 13 AND 15. WITH 3 DISKS
THE CODE NAMES WOULD BE 11, 13 AND 15, ETC. THE NEEDLES
ARE NUMBERED FROM LEFT TO RIGHT, 1 TO 3. WE WILL
START WITH THE DISKS ON NEEDLE 1, AND ATTEMPT TO MOVE THEM
TO NEEDLE 3.
game.take_turn() GOOD LUCK!
if game.winner(): """
print( )
"CONGRATULATIONS!!\nYOU HAVE PERFORMED THE TASK IN %s MOVES.\n"
% game.moves() game = Game()
) while True:
while True: game.print()
yesno = input("TRY AGAIN (YES OR NO)\n")
if yesno.upper() == "YES": game.take_turn()
game = Game()
break if game.winner():
elif yesno.upper() == "NO": print(
print("THANKS FOR THE GAME!\n") "CONGRATULATIONS!!\nYOU HAVE PERFORMED THE TASK IN %s MOVES.\n"
sys.exit(0) % game.moves()
else: )
print("'YES' OR 'NO' PLEASE\n") while True:
elif game.moves() > 128: yesno = input("TRY AGAIN (YES OR NO)\n")
print("SORRY, BUT I HAVE ORDERS TO STOP IF YOU MAKE MORE THAN 128 MOVES.") if yesno.upper() == "YES":
sys.exit(0) game = Game()
break
elif yesno.upper() == "NO":
print("THANKS FOR THE GAME!\n")
sys.exit(0)
else:
print("'YES' OR 'NO' PLEASE\n")
elif game.moves() > 128:
print("SORRY, BUT I HAVE ORDERS TO STOP IF YOU MAKE MORE THAN 128 MOVES.")
sys.exit(0)
if __name__ == "__main__":
main()