Merge pull request #654 from MartinThoma/py-testability

Python: Make code testable
This commit is contained in:
Jeff Atwood
2022-03-19 13:21:17 -05:00
committed by GitHub
28 changed files with 1118 additions and 1028 deletions

3
.coveragerc Normal file
View File

@@ -0,0 +1,3 @@
[run]
omit =
*test*

View File

@@ -22,7 +22,7 @@ jobs:
pip install -r 00_Utilities/python/ci-requirements.txt
- name: Test with pytest
run: |
pytest 01_Acey_Ducey/python 02_Amazing/python 39_Golf/python
pytest -m "not slow"
- name: Test with mypy
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

View File

@@ -58,93 +58,97 @@ def get_card_name(number: int) -> str:
def display_bankroll(bank_roll: int) -> None:
"""Print current bankroll"""
if BANK_ROLL > 0:
if bank_roll > 0:
print("You now have %s dollars\n" % bank_roll)
# Display initial title and instructions
print("\n Acey Ducey Card Game")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
print("Acey-Ducey is played in the following manner")
print("The dealer (computer) deals two cards face up")
print("You have an option to bet or not bet depending")
print("on whether or not you feel the card will have")
print("a value between the first two.")
print("If you do not want to bet, input a 0")
def main():
# Display initial title and instructions
print("\n Acey Ducey Card Game")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
print("Acey-Ducey is played in the following manner")
print("The dealer (computer) deals two cards face up")
print("You have an option to bet or not bet depending")
print("on whether or not you feel the card will have")
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
KEEP_PLAYING = True
while KEEP_PLAYING:
# Initialize bankroll at start of each game
BANK_ROLL = DEFAULT_BANKROLL
display_bankroll(BANK_ROLL)
# Initialize bankroll at start of each game
BANK_ROLL = DEFAULT_BANKROLL
display_bankroll(BANK_ROLL)
# Loop for a single round. Repeat until out of money.
while BANK_ROLL > 0:
# Loop for a single round. Repeat until out of money.
while BANK_ROLL > 0:
# Deal out dealer cards
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
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")
# 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)
# 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:
# Deal player card
BET_IS_VALID = True
player = deal_card_num()
print(get_card_name(player))
# Did we win?
if dealer1 < player < dealer2:
print("You win!!!")
BANK_ROLL += curr_bet
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:
print("Sorry, you lose")
BANK_ROLL -= curr_bet
# Deal player card
BET_IS_VALID = True
player = deal_card_num()
print(get_card_name(player))
# Update player on new bankroll level
display_bankroll(BANK_ROLL)
# Did we win?
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")
player_response = input("Try again (yes or no) ")
if player_response.lower() == "yes":
print()
else:
KEEP_PLAYING = False
# End of loop for a single round
# 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

@@ -0,0 +1,5 @@
from animal import initial_message
def test_initial_message():
initial_message()

View File

@@ -0,0 +1,5 @@
from awari import print_with_tab
def test_print_with_tab():
print_with_tab(3, "Hello")

View File

@@ -33,11 +33,12 @@
import random
from typing import List
MAX_GUESSES = 20
def print_rules():
def print_rules() -> None:
print("\nI am thinking of a three-digit number. Try to guess")
print("my number and I will give you clues as follows:")
print(" PICO - One digit correct but in the wrong position")
@@ -45,17 +46,17 @@ def print_rules():
print(" BAGELS - No digits correct")
def pick_number():
def pick_number() -> List[str]:
# Note that this returns a list of individual digits
# as separate strings, not a single integer or string
numbers = list(range(10))
random.shuffle(numbers)
num = numbers[0:3]
num = [str(i) for i in num]
return num
num_str = [str(i) for i in num]
return num_str
def get_valid_guess():
def get_valid_guess(guesses: int) -> str:
valid = False
while not valid:
guess = input(f"Guess # {guesses} ? ")
@@ -78,8 +79,7 @@ def get_valid_guess():
return guess
def build_result_string(num, guess):
def build_result_string(num: List[str], guess: str):
result = ""
# Correct digits in wrong place
@@ -108,60 +108,63 @@ def build_result_string(num, guess):
######################################################################
# Intro text
print("\n Bagels")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
def main():
# Intro text
print("\n Bagels")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
# Anything other than N* will show the rules
response = input("Would you like the rules (Yes or No)? ")
if len(response) > 0:
if response.upper()[0] != "N":
# Anything other than N* will show the rules
response = input("Would you like the rules (Yes or No)? ")
if len(response) > 0:
if response.upper()[0] != "N":
print_rules()
else:
print_rules()
else:
print_rules()
games_won = 0
still_running = True
while still_running:
games_won = 0
still_running = True
while still_running:
# New round
num = pick_number()
num_str = "".join(num)
guesses = 1
# New round
num = pick_number()
num_str = "".join(num)
guesses = 1
print("\nO.K. I have a number in mind.")
guessing = True
while guessing:
print("\nO.K. I have a number in mind.")
guessing = True
while guessing:
guess = get_valid_guess()
guess = get_valid_guess(guesses)
if guess == num_str:
print("You got it!!!\n")
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}")
if guess == num_str:
print("You got it!!!\n")
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
valid_response = False
while not valid_response:
response = input("Play again (Yes or No)? ")
if len(response) > 0:
valid_response = True
if response.upper()[0] != "Y":
still_running = False
valid_response = False
while not valid_response:
response = input("Play again (Yes or No)? ")
if len(response) > 0:
valid_response = True
if response.upper()[0] != "Y":
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:
print(f"\nA {games_won} point Bagels buff!!")
print("Hope you had fun. Bye.\n")
if __name__ == "__main__":
main()
######################################################################
#

View File

@@ -0,0 +1,5 @@
from bagels import build_result_string
def test_build_result_string():
build_result_string(["a", "b", "c"], "abc")

View File

@@ -110,9 +110,5 @@ def print_banner():
# print("\n" * 75) # Feed some more paper from the printer
def main():
print_banner()
if __name__ == "__main__":
main()
print_banner()

View File

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

View File

@@ -49,254 +49,259 @@ def print_legs(n_legs):
print()
print_n_whitespaces(34)
print("BUG")
print_n_whitespaces(15)
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(3)
def main():
print_n_whitespaces(34)
print("BUG")
print_n_whitespaces(15)
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(3)
print("THE GAME BUG")
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("THE GAME BUG")
print("I HOPE YOU ENJOY THIS GAME.")
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? ")
Z = input("DO YOU WANT INSTRUCTIONS? ")
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)
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
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
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:
break
# 1310
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")
def main():
# 1310
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_n_whitespaces(32)
print("BULLSEYE")
print_n_whitespaces(15)
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(3)
print("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET")
print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS")
print("TO GET 200 POINTS.")
print()
print("THROW", end="")
print_n_whitespaces(20)
print("DESCRIPTION", end="")
print_n_whitespaces(45)
print("PROBABLE SCORE")
print(" 1", end="")
print_n_whitespaces(20)
print("FAST OVERARM", end="")
print_n_whitespaces(45)
print("BULLSEYE OR COMPLETE MISS")
print(" 2", end="")
print_n_whitespaces(20)
print("CONTROLLED OVERARM", end="")
print_n_whitespaces(45)
print("10, 20 OR 30 POINTS")
print(" 3", end="")
print_n_whitespaces(20)
print("UNDERARM", end="")
print_n_whitespaces(45)
print("ANYTHING")
print()
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
def main():
print_n_whitespaces(32)
print("BULLSEYE")
print_n_whitespaces(15)
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(3)
print("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET")
print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS")
print("TO GET 200 POINTS.")
print()
print("THROW", end="")
print_n_whitespaces(20)
print("DESCRIPTION", end="")
print_n_whitespaces(45)
print("PROBABLE SCORE")
print(" 1", end="")
print_n_whitespaces(20)
print("FAST OVERARM", end="")
print_n_whitespaces(45)
print("BULLSEYE OR COMPLETE MISS")
print(" 2", end="")
print_n_whitespaces(20)
print("CONTROLLED OVERARM", end="")
print_n_whitespaces(45)
print("10, 20 OR 30 POINTS")
print(" 3", end="")
print_n_whitespaces(20)
print("UNDERARM", end="")
print_n_whitespaces(45)
print("ANYTHING")
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.")
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(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
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
print("\n Buzzword Generator")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
print("This program prints highly acceptable phrases in")
print("'educator-speak' that you can work into reports")
print("and speeches. Whenever a question mark is printed,")
print("type a 'Y' for another phrase or 'N' to quit.")
print("\n\nHere's the first phrase:")
# Display intro text
print("\n Buzzword Generator")
print("Creative Computing Morristown, New Jersey")
print("\n\n")
print("This program prints highly acceptable phrases in")
print("'educator-speak' that you can work into reports")
print("and speeches. Whenever a question mark is printed,")
print("type a 'Y' for another phrase or 'N' to quit.")
print("\n\nHere's the first phrase:")
still_running = True
while still_running:
phrase = ""
for section in WORDS:
if len(phrase) > 0:
phrase += " "
phrase += section[random.randint(0, len(section) - 1)]
still_running = True
while still_running:
phrase = ""
for section in WORDS:
if len(phrase) > 0:
phrase += " "
phrase += section[random.randint(0, len(section) - 1)]
print(phrase)
print("")
print(phrase)
print("")
response = input("? ")
try:
if response.upper()[0] != "Y":
response = input("? ")
try:
if response.upper()[0] != "Y":
still_running = False
except Exception:
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)
print(" " * 33 + "Craps")
print(" " * 15 + "Creative Computing Morristown, New Jersey")
print()
print()
print()
def main():
print(" " * 33 + "Craps")
print(" " * 15 + "Creative Computing Morristown, New Jersey")
print()
print()
print()
winnings = 0
print("2,3,12 are losers; 4,5,6,8,9,10 are points; 7,11 are natural winners.")
winnings = 0
print("2,3,12 are losers; 4,5,6,8,9,10 are points; 7,11 are natural winners.")
play_again = True
while play_again:
wager = int(input("Input the amount of your wager: "))
play_again = True
while play_again:
wager = int(input("Input the amount of your wager: "))
print("I will now throw the dice")
roll_1 = throw_dice()
print("I will now throw the dice")
roll_1 = throw_dice()
if roll_1 in [7, 11]:
print(f"{roll_1} - natural.... a winner!!!!")
print(f"{roll_1} pays even money, you win {wager} dollars")
winnings += wager
elif roll_1 == 2:
print(f"{roll_1} - snake eyes.... you lose.")
print(f"You lose {wager} dollars")
winnings -= wager
elif roll_1 in [3, 12]:
print(f"{roll_1} - craps.... you lose.")
print(f"You lose {wager} dollars")
winnings -= wager
else:
print(f"{roll_1} is the point. I will roll again")
roll_2 = 0
while roll_2 not in [roll_1, 7]:
roll_2 = throw_dice()
if roll_2 == 7:
print(f"{roll_2} - craps. You lose.")
print(f"You lose $ {wager}")
winnings -= wager
elif roll_2 == roll_1:
print(f"{roll_1} - a winner.........congrats!!!!!!!!")
print(
f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars"
)
winnings += 2 * wager
else:
print(f"{roll_2} - no point. I will roll again")
if roll_1 in [7, 11]:
print(f"{roll_1} - natural.... a winner!!!!")
print(f"{roll_1} pays even money, you win {wager} dollars")
winnings += wager
elif roll_1 == 2:
print(f"{roll_1} - snake eyes.... you lose.")
print(f"You lose {wager} dollars")
winnings -= wager
elif roll_1 in [3, 12]:
print(f"{roll_1} - craps.... you lose.")
print(f"You lose {wager} dollars")
winnings -= wager
else:
print(f"{roll_1} is the point. I will roll again")
roll_2 = 0
while roll_2 not in [roll_1, 7]:
roll_2 = throw_dice()
if roll_2 == 7:
print(f"{roll_2} - craps. You lose.")
print(f"You lose $ {wager}")
winnings -= wager
elif roll_2 == roll_1:
print(f"{roll_1} - a winner.........congrats!!!!!!!!")
print(
f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars"
)
winnings += 2 * wager
else:
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:
print(f"You are now under ${-winnings}")
print("Too bad, you are in the hole. Come again.")
elif winnings > 0:
print(f"You are now ahead ${winnings}")
print("Congratulations---you came out a winner. Come again.")
else:
print("You are now even at 0")
play_again = m == "5"
print("Congratulations---you came out even, not bad for an amateur")
if winnings < 0:
print("Too bad, you are in the hole. Come again.")
elif winnings > 0:
print("Congratulations---you came out a winner. Come again.")
else:
print("Congratulations---you came out even, not bad for an amateur")
if __name__ == "__main__":
main()

View File

@@ -28,50 +28,54 @@
import random
# We'll track counts of roll outcomes in a 13-element list.
# The first two indices (0 & 1) are ignored, leaving just
# the indices that match the roll values (2 through 12).
freq = [0] * 13
def main():
# We'll track counts of roll outcomes in a 13-element list.
# 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
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
if __name__ == "__main__":
main()
########################################################
#

View File

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

View File

@@ -71,42 +71,48 @@ DATA = [
# is the line length used by every row
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
message = input("Your message, please? ")
if message == "":
message = "LOVE"
def main():
# 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)
# Repeat the message until we get at least one line's worth
while len(message) < ROW_LEN:
message += message
# Get message from user
message = input("Your message, please? ")
if message == "":
message = "LOVE"
# 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)
# Repeat the message until we get at least one line's worth
while len(message) < ROW_LEN:
message += message
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!")
main()
if __name__ == "__main__":
main()

View File

@@ -39,39 +39,43 @@ def parse_input():
return i
initial_message()
while True:
dead = False
n = 0
print("Type '1' to Spin chamber and pull trigger")
print("Type '2' to Give up")
print("Go")
while not dead:
i = parse_input()
def main():
initial_message()
while True:
dead = False
n = 0
print("Type '1' to Spin chamber and pull trigger")
print("Type '2' to Give up")
print("Go")
while not dead:
i = parse_input()
if i == 2:
break
if i == 2:
break
if random() > 0.8333333333333334:
dead = True
if random() > 0.8333333333333334:
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:
print("- CLICK -\n")
n += 1
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 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

View File

@@ -57,8 +57,6 @@ computer_board = []
player_ship_coords = []
computer_ship_coords = []
# keep track of the turn
current_turn = 0
####################################
#
@@ -287,14 +285,12 @@ def generate_board():
return board, ship_coords
# execute_shot
#
# given a board and x, y coordinates,
# execute a shot. returns True if the shot
# is valid, False if not
def execute_shot(turn, board, x, y):
global current_turn
def execute_shot(turn, board, x, y, current_turn):
"""
given a board and x, y coordinates,
execute a shot. returns True if the shot
is valid, False if not
"""
square = board[x - 1][y - 1]
ship_hit = -1
if square is not None and square >= 0 and square < len(SHIPS):
@@ -422,7 +418,7 @@ first_turn = PLAYER
second_turn = COMPUTER
def execute_turn(turn):
def execute_turn(turn, current_turn):
global num_computer_shots
global num_player_shots
@@ -464,7 +460,7 @@ def execute_turn(turn):
hits = []
for shot in shots:
hit = execute_shot(turn, board, shot[0], shot[1])
hit = execute_shot(turn, board, shot[0], shot[1], current_turn)
if hit >= 0:
hits.append(hit)
if turn == COMPUTER and print_computer_shots:
@@ -489,36 +485,39 @@ def execute_turn(turn):
#
######################################
######################
#
# main game flow
#
######################
# initialize the player and computer
# boards
initialize_game()
def main():
# keep track of the turn
current_turn = 0
# execute turns until someone wins or we run
# out of squares to shoot
# initialize the player and computer
# boards
initialize_game()
game_over = False
while not game_over:
# execute turns until someone wins or we run
# out of squares to shoot
# increment the turn
current_turn = current_turn + 1
game_over = False
while not game_over:
print("\n")
print("TURN", current_turn)
# increment the turn
current_turn = current_turn + 1
# print("computer")
# print_board(computer_board)
# print("player")
# print_board(player_board)
print("\n")
print("TURN", current_turn)
if execute_turn(first_turn) == 0:
game_over = True
continue
if execute_turn(second_turn) == 0:
game_over = True
continue
# print("computer")
# print_board(computer_board)
# print("player")
# print_board(player_board)
if execute_turn(first_turn, current_turn) == 0:
game_over = True
continue
if execute_turn(second_turn, current_turn) == 0:
game_over = True
continue
if __name__ == "__main__":
main()

View File

@@ -24,47 +24,50 @@
import math
import time
# Constants
STRINGS = ("Creative", "Computing") # Text to display
MAX_LINES = 160
STEP_SIZE = 0.25 # Number of radians to increase at each
# line. Controls speed of horizontal
# printing movement.
CENTER = 26 # Controls left edge of "middle" string
DELAY = 0.05 # Amount of seconds to wait between lines
def main():
# Constants
STRINGS = ("Creative", "Computing") # Text to display
MAX_LINES = 160
STEP_SIZE = 0.25 # Number of radians to increase at each
# line. Controls speed of horizontal
# 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
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)
if __name__ == "__main__":
main()
########################################################
#

View File

@@ -1,40 +1,10 @@
from random import random
print("Slalom".rjust(39))
print("Creative Computing Morristown, New Jersey\n\n\n".rjust(57))
medals = {
"gold": 0,
"silver": 0,
"bronze": 0,
}
max_speeds = [
14,
18,
26,
29,
18,
25,
28,
32,
29,
20,
29,
29,
25,
21,
26,
29,
20,
21,
20,
18,
26,
25,
33,
31,
22,
]
def ask(question):
@@ -47,7 +17,7 @@ def ask_int(question):
return int(reply) if reply.isnumeric() else -1
def pre_run():
def pre_run(gates, max_speeds):
print('\nType "INS" for instructions')
print('Type "MAX" for approximate maximum speeds')
print('Type "RUN" for the beginning of the race')
@@ -80,7 +50,7 @@ def pre_run():
cmd = ask(f'"{cmd}" is an illegal command--Retry')
def run():
def run(gates, lvl, max_speeds):
global medals
print("The starter counts down...5...4...3...2...1...Go!")
time = 0
@@ -160,39 +130,75 @@ def run():
medals["bronze"] += 1
while True:
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
def main():
print("Slalom".rjust(39))
print("Creative Computing Morristown, New Jersey\n\n\n".rjust(57))
pre_run()
max_speeds = [
14,
18,
26,
29,
18,
25,
28,
32,
29,
20,
29,
29,
25,
21,
26,
29,
20,
21,
20,
18,
26,
25,
33,
31,
22,
]
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:
answer = ask("Do you want to play again?")
if answer == "YES" or answer == "NO":
break
gates = ask_int("How many gates does this course have (1 to 25)")
if gates < 1:
print("Try again,")
else:
print('Please type "YES" or "NO"')
if answer == "NO":
break
if gates > 25:
print("25 is the limit.")
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']}")
pre_run(gates, max_speeds)
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(gates, lvl, max_speeds)
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.")
profits = 0
keep_betting = True
def main():
profits = 0
keep_betting = True
initial_message()
while keep_betting:
m = input_betting()
w = spin_wheels()
profits = adjust_profits(w, m, profits)
initial_message()
while keep_betting:
m = input_betting()
w = spin_wheels()
profits = adjust_profits(w, m, profits)
print(f"Your standings are ${profits}")
answer = input("Again?")
print(f"Your standings are ${profits}")
answer = input("Again?")
try:
if not answer[0].lower() == "y":
try:
if not answer[0].lower() == "y":
keep_betting = False
except IndexError:
keep_betting = False
except IndexError:
keep_betting = False
final_message(profits)
final_message(profits)
if __name__ == "__main__":
main()
######################################################################
#
# Porting notes

View File

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

View File

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

View File

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

View File

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

View File

@@ -44,23 +44,6 @@ class Tower:
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:
def __init__(self):
# use fewer sizes to make debugging easier
@@ -144,27 +127,48 @@ class Game:
from_tower.add(disk)
game = Game()
while True:
game.print()
def main():
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()
)
while True:
yesno = input("TRY AGAIN (YES OR NO)\n")
if yesno.upper() == "YES":
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)
"""
)
game = Game()
while True:
game.print()
game.take_turn()
if game.winner():
print(
"CONGRATULATIONS!!\nYOU HAVE PERFORMED THE TASK IN %s MOVES.\n"
% game.moves()
)
while True:
yesno = input("TRY AGAIN (YES OR NO)\n")
if yesno.upper() == "YES":
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()