From 83b3dc402cd23c7040ea944168da04f4eb33fa06 Mon Sep 17 00:00:00 2001 From: Martin Thoma Date: Sat, 19 Mar 2022 22:10:26 +0100 Subject: [PATCH] Python: Add type annotations --- 00_Utilities/python/ci-requirements.in | 1 + 01_Acey_Ducey/python/aceyducey.py | 2 +- 02_Amazing/python/test_amazing.py | 6 +- 03_Animal/python/test_animal.py | 2 +- 04_Awari/python/awari.py | 37 +-- 05_Bagels/python/bagels.py | 7 +- 05_Bagels/python/test_bagels.py | 2 +- 06_Banner/python/banner.py | 7 +- 06_Banner/python/test_banner.py | 19 ++ 07_Basketball/python/basketball.py | 93 +++--- 08_Batnum/python/batnum.py | 129 ++++---- 09_Battle/python/battle.py | 8 +- 09_Battle/python/battle_oo.py | 10 +- 11_Bombardment/python/bombardment.py | 23 +- 13_Bounce/python/bounce.py | 19 +- 14_Bowling/python/bowling.py | 10 +- 16_Bug/python/Bug.py | 10 +- 16_Bug/python/bug-overengineered.py | 5 +- 17_Bullfight/python/Bullfight.py | 301 +++++++++--------- 18_Bullseye/python/Bullseye.py | 6 +- 19_Bunny/python/bunny.py | 6 +- 20_Buzzword/python/buzzword.py | 2 +- 21_Calendar/python/calendar.py | 6 +- 22_Change/python/change.py | 2 +- 23_Checkers/python/checkers.py | 2 +- 24_Chemist/python/chemist.py | 2 +- 26_Chomp/python/chomp.py | 2 +- 28_Combat/python/combat.py | 10 +- 29_Craps/python/craps.py | 4 +- 30_Cube/python/cube.py | 2 +- 32_Diamond/python/diamond.py | 2 +- 33_Dice/python/dice.py | 2 +- 34_Digits/python/Digits.py | 12 +- 35_Even_Wins/python/evenwins.py | 2 +- 38_Fur_Trader/python/furtrader.py | 2 +- 40_Gomoko/python/Gomoko.py | 14 +- 41_Guess/python/guess.py | 2 +- 43_Hammurabi/python/hamurabi.py | 4 +- 44_Hangman/python/hangman.py | 2 +- 45_Hello/python/hello.py | 2 +- 46_Hexapawn/python/hexapawn.py | 2 +- 48_High_IQ/python/High_IQ.py | 2 +- 50_Horserace/python/horserace.py | 4 +- 52_Kinema/python/kinema.py | 2 +- 54_Letter/python/letter.py | 2 +- 55_Life/python/life.py | 2 +- 57_Literature_Quiz/python/litquiz.py | 2 +- 58_Love/python/love.py | 2 +- 59_Lunar_LEM_Rocket/python/lunar.py | 2 +- 61_Math_Dice/python/mathdice.py | 2 +- 63_Name/python/name.py | 2 +- 64_Nicomachus/python/nicomachus.py | 2 +- 65_Nim/python/Traditional_NIM.py | 2 +- 66_Number/python/number.py | 4 +- 67_One_Check/python/onecheck.py | 2 +- 68_Orbit/python/orbit.py | 2 +- 69_Pizza/python/pizza.py | 2 +- 70_Poetry/python/poetry.py | 2 +- 74_Rock_Scissors_Paper/python/rockscissors.py | 2 +- 75_Roulette/python/roulette.py | 83 ++--- 76_Russian_Roulette/python/russianroulette.py | 10 +- 77_Salvo/python/salvo.py | 3 +- 78_Sine_Wave/python/sinewave.py | 4 +- 79_Slalom/python/slalom.py | 2 +- 80_Slots/python/slots.py | 4 +- 81_Splat/python/splat.py | 5 +- 82_Stars/python/stars.py | 2 +- 84_Super_Star_Trek/python/superstartrek.py | 12 +- 84_Super_Star_Trek/python/superstartrekins.py | 2 +- 85_Synonym/python/synonym.py | 4 +- 86_Target/python/target.py | 2 +- 87_3-D_Plot/python/3dplot.py | 2 +- 90_Tower/python/tower.py | 2 +- 91_Train/python/train.py | 2 +- 92_Trap/python/trap.py | 2 +- 93_23_Matches/python/23matches.py | 2 +- 94_War/python/war.py | 2 +- 95_Weekday/python/weekday.py | 2 +- 96_Word/python/word.py | 2 +- 79 files changed, 509 insertions(+), 461 deletions(-) create mode 100644 06_Banner/python/test_banner.py diff --git a/00_Utilities/python/ci-requirements.in b/00_Utilities/python/ci-requirements.in index ae5fa2e0..218d0de9 100644 --- a/00_Utilities/python/ci-requirements.in +++ b/00_Utilities/python/ci-requirements.in @@ -2,4 +2,5 @@ pytest flake8 flake8-bugbear flake8-comprehensions +flake8_implicit_str_concat mypy diff --git a/01_Acey_Ducey/python/aceyducey.py b/01_Acey_Ducey/python/aceyducey.py index 1d4a13e8..1db2ee76 100644 --- a/01_Acey_Ducey/python/aceyducey.py +++ b/01_Acey_Ducey/python/aceyducey.py @@ -62,7 +62,7 @@ def display_bankroll(bank_roll: int) -> None: print("You now have %s dollars\n" % bank_roll) -def main(): +def main() -> None: # Display initial title and instructions print("\n Acey Ducey Card Game") print("Creative Computing Morristown, New Jersey") diff --git a/02_Amazing/python/test_amazing.py b/02_Amazing/python/test_amazing.py index 774404cc..87ff2d90 100644 --- a/02_Amazing/python/test_amazing.py +++ b/02_Amazing/python/test_amazing.py @@ -2,8 +2,8 @@ import pytest from amazing import build_maze, welcome_header -def test_welcome_header(capsys): - assert welcome_header() is None +def test_welcome_header(capsys) -> None: + welcome_header() out, err = capsys.readouterr() assert out == ( " AMAZING PROGRAM\n" @@ -22,6 +22,6 @@ def test_welcome_header(capsys): (2, 1), ], ) -def test_build_maze(width, length): +def test_build_maze(width: int, length: int) -> None: with pytest.raises(AssertionError): build_maze(width, length) diff --git a/03_Animal/python/test_animal.py b/03_Animal/python/test_animal.py index 5ea57ef4..74c73143 100644 --- a/03_Animal/python/test_animal.py +++ b/03_Animal/python/test_animal.py @@ -1,5 +1,5 @@ from animal import initial_message -def test_initial_message(): +def test_initial_message() -> None: initial_message() diff --git a/04_Awari/python/awari.py b/04_Awari/python/awari.py index 42754c05..d05cb0ec 100644 --- a/04_Awari/python/awari.py +++ b/04_Awari/python/awari.py @@ -70,17 +70,18 @@ Ported by Dave LeCompte # - store history to a file on disk (or in the cloud!) to allow the AI # to learn over more than a single session +from typing import Dict, List, Tuple -game_number = 0 -move_count = 0 -losing_book = [] +game_number: int = 0 +move_count: int = 0 +losing_book: List[int] = [] n = 0 MAX_HISTORY = 9 LOSING_BOOK_SIZE = 50 -def print_with_tab(space_count, msg): +def print_with_tab(space_count: int, msg: str) -> None: if space_count > 0: spaces = " " * space_count else: @@ -88,7 +89,7 @@ def print_with_tab(space_count, msg): print(spaces + msg) -def draw_pit(line, board, pit_index): +def draw_pit(line: str, board, pit_index) -> str: val = board[pit_index] line = line + " " if val < 10: @@ -97,7 +98,7 @@ def draw_pit(line, board, pit_index): return line -def draw_board(board): +def draw_board(board) -> None: print() # Draw the top (computer) pits @@ -121,7 +122,7 @@ def draw_board(board): print() -def play_game(board): +def play_game(board: List[int]) -> None: # Place the beginning stones for i in range(0, 13): board[i] = 3 @@ -164,7 +165,7 @@ def play_game(board): game_over(board) -def computer_move(msg, board): +def computer_move(msg: str, board) -> Tuple[int, bool, int, str]: # This function does a two-ply lookahead evaluation; one computer # move plus one human move. # @@ -239,7 +240,7 @@ def computer_move(msg, board): # penalize that move. for prev_game_number in range(game_number): if losing_book[game_number] * 6 + move_digit == int( - losing_book[prev_game_number] / 6 ^ (7 - move_count) + 0.1 + losing_book[prev_game_number] / 6 ^ (7 - move_count) + 0.1 # type: ignore ): computer_move_quality -= 2 @@ -264,7 +265,7 @@ def computer_move(msg, board): return move_number, is_still_going, home, msg -def game_over(board): +def game_over(board) -> None: print() print("GAME OVER") @@ -282,13 +283,13 @@ def game_over(board): print(f"YOU WIN BY {pit_difference} POINTS") -def do_capture(m, home, board): +def do_capture(m, home, board) -> None: board[home] += board[12 - m] + 1 board[m] = 0 board[12 - m] = 0 -def do_move(m, home, board): +def do_move(m, home, board) -> int: move_stones = board[m] board[m] = 0 @@ -302,15 +303,15 @@ def do_move(m, home, board): return m -def player_has_stones(board): +def player_has_stones(board) -> bool: return any(board[i] > 0 for i in range(6)) -def computer_has_stones(board): +def computer_has_stones(board: Dict[int, int]) -> bool: return any(board[i] > 0 for i in range(7, 13)) -def execute_move(move, home, board): +def execute_move(move, home: int, board) -> Tuple[int, bool, int]: move_digit = move last_location = do_move(move, home, board) @@ -337,12 +338,12 @@ def execute_move(move, home, board): return last_location, is_still_going, home -def player_move_again(board): +def player_move_again(board) -> Tuple[int, bool, int]: print("AGAIN") return player_move(board) -def player_move(board): +def player_move(board) -> Tuple[int, bool, int]: while True: print("SELECT MOVE 1-6") m = int(input()) - 1 @@ -360,7 +361,7 @@ def player_move(board): return ending_spot, is_still_going, home -def main(): +def main() -> None: print_with_tab(34, "AWARI") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/05_Bagels/python/bagels.py b/05_Bagels/python/bagels.py index 5510a519..13014389 100644 --- a/05_Bagels/python/bagels.py +++ b/05_Bagels/python/bagels.py @@ -79,7 +79,7 @@ def get_valid_guess(guesses: int) -> str: return guess -def build_result_string(num: List[str], guess: str): +def build_result_string(num: List[str], guess: str) -> str: result = "" # Correct digits in wrong place @@ -105,10 +105,7 @@ def build_result_string(num: List[str], guess: str): return result -###################################################################### - - -def main(): +def main() -> None: # Intro text print("\n Bagels") print("Creative Computing Morristown, New Jersey") diff --git a/05_Bagels/python/test_bagels.py b/05_Bagels/python/test_bagels.py index 520778e4..fc68236b 100644 --- a/05_Bagels/python/test_bagels.py +++ b/05_Bagels/python/test_bagels.py @@ -1,5 +1,5 @@ from bagels import build_result_string -def test_build_result_string(): +def test_build_result_string() -> None: build_result_string(["a", "b", "c"], "abc") diff --git a/06_Banner/python/banner.py b/06_Banner/python/banner.py index d83ac7dc..868d98f0 100644 --- a/06_Banner/python/banner.py +++ b/06_Banner/python/banner.py @@ -50,7 +50,7 @@ letters = { } -def print_banner(): +def print_banner() -> None: f = [0] * 7 j = [0] * 9 @@ -77,8 +77,9 @@ def print_banner(): g1 = 1 mStr = input("Character (type 'ALL' if you want character being printed) ").upper() aStr = input("Statement ") - # This means to prepare printer, just press Enter - input("Set page ") + + input("Set page ") # This means to prepare printer, just press Enter + for lStr in aStr: s = letters[lStr].copy() xStr = mStr diff --git a/06_Banner/python/test_banner.py b/06_Banner/python/test_banner.py new file mode 100644 index 00000000..0f297395 --- /dev/null +++ b/06_Banner/python/test_banner.py @@ -0,0 +1,19 @@ +import io + +from banner import print_banner + + +def test_print_banner(monkeypatch) -> None: + horizontal = "1" + vertical = "1" + centered = "1" + char = "*" + statement = "O" # only capital letters + set_page = "2" + monkeypatch.setattr( + "sys.stdin", + io.StringIO( + f"{horizontal}\n{vertical}\n{centered}\n{char}\n{statement}\n{set_page}" + ), + ) + print_banner() diff --git a/07_Basketball/python/basketball.py b/07_Basketball/python/basketball.py index d94414e0..a29f4f09 100644 --- a/07_Basketball/python/basketball.py +++ b/07_Basketball/python/basketball.py @@ -1,4 +1,5 @@ import random +from typing import Optional # The basketball class is a computer game that allows you to play as # Dartmouth College's captain and playmaker @@ -7,14 +8,13 @@ import random class Basketball: - def __init__(self): + def __init__(self) -> None: self.time = 0 self.score = [0, 0] # first value is opponents score, second is home - self.defense = None self.defense_choices = [6, 6.5, 7, 7.5] - self.shot = None + self.shot: Optional[int] = None self.shot_choices = [0, 1, 2, 3, 4] - self.z1 = None + self.z1: Optional[float] = None # Explains the keyboard inputs print("\t\t\t Basketball") @@ -32,21 +32,7 @@ class Basketball: print("To change defense, just type 0 as your next shot.") print("Your starting defense will be? ", end="") - # takes input for a defense - try: - self.defense = float(input()) - - except ValueError: - self.defense = None - - # if the input wasn't a valid defense, takes input again - while self.defense not in self.defense_choices: - print("Your new defensive allignment is? ", end="") - try: - self.defense = float(input()) - - except ValueError: - continue + self.defense = get_defense(self.defense_choices) # takes input for opponent's name print("\nChoose your opponent? ", end="") @@ -56,29 +42,30 @@ class Basketball: # adds points to the score # team can take 0 or 1, for opponent or Dartmouth, respectively - def add_points(self, team, points): + def add_points(self, team, points) -> None: self.score[team] += points self.print_score() - def ball_passed_back(self): + def ball_passed_back(self) -> None: print("Ball passed back to you. ", end="") self.dartmouth_ball() # change defense, called when the user enters 0 for their shot - def change_defense(self): - self.defense = None + def change_defense(self) -> None: + defense = None - while self.defense not in self.defense_choices: + while defense not in self.defense_choices: print("Your new defensive allignment is? ") try: - self.defense = float(input()) - + defense = float(input()) except ValueError: continue + assert isinstance(defense, float) + self.defense = defense self.dartmouth_ball() # simulates two foul shots for a player and adds the points - def foul_shots(self, team): + def foul_shots(self, team) -> None: print("Shooter fouled. Two shots.") if random.random() > 0.49: if random.random() > 0.75: @@ -93,17 +80,17 @@ class Basketball: self.print_score() # called when t = 50, starts a new period - def halftime(self): + def halftime(self) -> None: print("\n ***** End of first half *****\n") self.print_score() self.start_of_period() # prints the current score - def print_score(self): + def print_score(self) -> None: print("Score: " + str(self.score[1]) + " to " + str(self.score[0]) + "\n") # simulates a center jump for posession at the beginning of a period - def start_of_period(self): + def start_of_period(self) -> None: print("Center jump") if random.random() > 0.6: print("Dartmouth controls the tap.\n") @@ -113,11 +100,11 @@ class Basketball: self.opponent_ball() # called when t = 92 - def two_minute_warning(self): + def two_minute_warning(self) -> None: print(" *** Two minutes left in the game ***") # called when the user enters 1 or 2 for their shot - def dartmouth_jump_shot(self): + def dartmouth_jump_shot(self) -> None: self.time += 1 if self.time == 50: self.halftime() @@ -171,7 +158,7 @@ class Basketball: # called when the user enters 0, 3, or 4 # lay up, set shot, or defense change - def dartmouth_non_jump_shot(self): + def dartmouth_non_jump_shot(self) -> None: self.time += 1 if self.time == 50: self.halftime() @@ -216,20 +203,22 @@ class Basketball: self.opponent_ball() # plays out a Dartmouth posession, starting with your choice of shot - def dartmouth_ball(self): + def dartmouth_ball(self) -> None: print("Your shot? ", end="") - self.shot = None + shot = None try: - self.shot = int(input()) + shot = int(input()) except ValueError: - self.shot = None + shot = None - while self.shot not in self.shot_choices: + while shot not in self.shot_choices: print("Incorrect answer. Retype it. Your shot? ", end="") try: - self.shot = int(input()) + shot = int(input()) except Exception: continue + assert isinstance(shot, int) + self.shot = shot if self.time < 100 or random.random() < 0.5: if self.shot == 1 or self.shot == 2: @@ -263,7 +252,7 @@ class Basketball: self.start_of_period() # simulates the opponents jumpshot - def opponent_jumpshot(self): + def opponent_jumpshot(self) -> None: print("Jump Shot.") if 8 / self.defense * random.random() > 0.35: if 8 / self.defense * random.random() > 0.75: @@ -304,8 +293,8 @@ class Basketball: self.dartmouth_ball() # simulates opponents lay up or set shot - def opponent_non_jumpshot(self): - if self.z1 > 3: + def opponent_non_jumpshot(self) -> None: + if self.z1 > 3: # type: ignore print("Set shot.") else: print("Lay up") @@ -342,7 +331,7 @@ class Basketball: # simulates an opponents possesion # #randomly picks jump shot or lay up / set shot. - def opponent_ball(self): + def opponent_ball(self) -> None: self.time += 1 if self.time == 50: self.halftime() @@ -353,5 +342,23 @@ class Basketball: self.opponent_jumpshot() +def get_defense(defense_choices) -> float: + # takes input for a defense + try: + defense = float(input()) + except ValueError: + defense = None + + # if the input wasn't a valid defense, takes input again + while defense not in defense_choices: + print("Your new defensive allignment is? ", end="") + try: + defense = float(input()) + except ValueError: + continue + assert isinstance(defense, float) + return defense + + if __name__ == "__main__": Basketball() diff --git a/08_Batnum/python/batnum.py b/08_Batnum/python/batnum.py index d7314578..91480d23 100644 --- a/08_Batnum/python/batnum.py +++ b/08_Batnum/python/batnum.py @@ -1,4 +1,5 @@ from enum import Enum +from typing import Tuple, Union class WinOptions(Enum): @@ -13,7 +14,7 @@ class StartOptions(Enum): PlayerFirst = 2 -def PrintIntro(): +def print_intro() -> None: """Prints out the introduction and rules for the game.""" print("BATNUM".rjust(33, " ")) print("CREATIVE COMPUTING MORRISSTOWN, NEW JERSEY".rjust(15, " ")) @@ -33,7 +34,7 @@ def PrintIntro(): return -def GetParams(): +def get_params() -> Tuple[int, int, int, int, int]: """This requests the necessary parameters to play the game. Returns a set with the five game parameters: @@ -45,26 +46,30 @@ def GetParams(): winOption - 1 if the goal is to take the last object or 2 if the goal is to not take the last object """ - pileSize = 0 - winOption = WinOptions.Undefined - minSelect = 0 - maxSelect = 0 - startOption = StartOptions.Undefined + pile_size = 0 + win_option: Union[WinOptions, int] = WinOptions.Undefined + min_select = 0 + max_select = 0 + start_option: Union[StartOptions, int] = StartOptions.Undefined - while pileSize < 1: - pileSize = int(input("ENTER PILE SIZE ")) - while winOption == WinOptions.Undefined: - winOption = int(input("ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: ")) - while minSelect < 1 or maxSelect < 1 or minSelect > maxSelect: - (minSelect, maxSelect) = ( + while pile_size < 1: + pile_size = int(input("ENTER PILE SIZE ")) + while win_option == WinOptions.Undefined: + win_option = int(input("ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: ")) + assert isinstance(win_option, int) + while min_select < 1 or max_select < 1 or min_select > max_select: + (min_select, max_select) = ( int(x) for x in input("ENTER MIN AND MAX ").split(" ") ) - while startOption == StartOptions.Undefined: - startOption = int(input("ENTER START OPTION - 1 COMPUTER FIRST, 2 YOU FIRST ")) - return (pileSize, minSelect, maxSelect, startOption, winOption) + while start_option == StartOptions.Undefined: + start_option = int(input("ENTER START OPTION - 1 COMPUTER FIRST, 2 YOU FIRST ")) + assert isinstance(start_option, int) + return (pile_size, min_select, max_select, start_option, win_option) -def PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption): +def player_move( + pile_size, min_select, max_select, start_option, win_option +) -> Tuple[bool, int]: """This handles the player's turn - asking the player how many objects to take and doing some basic validation around that input. Then it checks for any win conditions. @@ -75,36 +80,38 @@ def PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption): playerMove = int(input("YOUR MOVE ")) if playerMove == 0: print("I TOLD YOU NOT TO USE ZERO! COMPUTER WINS BY FORFEIT.") - return (True, pileSize) - if playerMove > maxSelect or playerMove < minSelect: + return (True, pile_size) + if playerMove > max_select or playerMove < min_select: print("ILLEGAL MOVE, REENTER IT") continue - pileSize = pileSize - playerMove + pile_size = pile_size - playerMove playerDone = True - if pileSize <= 0: - if winOption == WinOptions.AvoidLast: + if pile_size <= 0: + if win_option == WinOptions.AvoidLast: print("TOUGH LUCK, YOU LOSE.") else: print("CONGRATULATIONS, YOU WIN.") - return (True, pileSize) - return (False, pileSize) + return (True, pile_size) + return (False, pile_size) -def ComputerPick(pileSize, minSelect, maxSelect, startOption, winOption): +def computer_pick(pile_size, min_select, max_select, start_option, win_option) -> int: """This handles the logic to determine how many objects the computer will select on its turn. """ - q = pileSize - 1 if winOption == WinOptions.AvoidLast else pileSize - c = minSelect + maxSelect - computerPick = q - (c * int(q / c)) - if computerPick < minSelect: - computerPick = minSelect - if computerPick > maxSelect: - computerPick = maxSelect - return computerPick + q = pile_size - 1 if win_option == WinOptions.AvoidLast else pile_size + c = min_select + max_select + computer_pick = q - (c * int(q / c)) + if computer_pick < min_select: + computer_pick = min_select + if computer_pick > max_select: + computer_pick = max_select + return computer_pick -def ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption): +def computer_move( + pile_size, min_select, max_select, start_option, win_option +) -> Tuple[bool, int]: """This handles the computer's turn - first checking for the various win/lose conditions and then calculating how many objects the computer will take. @@ -114,47 +121,45 @@ def ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption): # In this case, we win by taking the last object and # the remaining pile is less than max select # so the computer can grab them all and win - if winOption == WinOptions.TakeLast and pileSize <= maxSelect: - print(f"COMPUTER TAKES {pileSize} AND WINS.") - return (True, pileSize) + if win_option == WinOptions.TakeLast and pile_size <= max_select: + print(f"COMPUTER TAKES {pile_size} AND WINS.") + return (True, pile_size) # In this case, we lose by taking the last object and # the remaining pile is less than minsize and the computer # has to take all of them. - if winOption == WinOptions.AvoidLast and pileSize <= minSelect: - print(f"COMPUTER TAKES {minSelect} AND LOSES.") - return (True, pileSize) + if win_option == WinOptions.AvoidLast and pile_size <= min_select: + print(f"COMPUTER TAKES {min_select} AND LOSES.") + return (True, pile_size) # Otherwise, we determine how many the computer selects - currSel = ComputerPick(pileSize, minSelect, maxSelect, startOption, winOption) - pileSize = pileSize - currSel - print(f"COMPUTER TAKES {currSel} AND LEAVES {pileSize}") - return (False, pileSize) + currSel = computer_pick(pile_size, min_select, max_select, start_option, win_option) + pile_size = pile_size - currSel + print(f"COMPUTER TAKES {currSel} AND LEAVES {pile_size}") + return (False, pile_size) -def PlayGame(pileSize, minSelect, maxSelect, startOption, winOption): +def play_game(pile_size, min_select, max_select, start_option, win_option) -> None: """This is the main game loop - repeating each turn until one of the win/lose conditions is met. """ - gameOver = False + game_over = False # playersTurn is a boolean keeping track of whether it's the # player's or computer's turn - playersTurn = startOption == StartOptions.PlayerFirst + players_turn = start_option == StartOptions.PlayerFirst - while not gameOver: - if playersTurn: - (gameOver, pileSize) = PlayerMove( - pileSize, minSelect, maxSelect, startOption, winOption + while not game_over: + if players_turn: + (game_over, pile_size) = player_move( + pile_size, min_select, max_select, start_option, win_option ) - playersTurn = False - if gameOver: + players_turn = False + if game_over: return - if not playersTurn: - (gameOver, pileSize) = ComputerMove( - pileSize, minSelect, maxSelect, startOption, winOption + if not players_turn: + (game_over, pile_size) = computer_move( + pile_size, min_select, max_select, start_option, win_option ) - playersTurn = True - - return + players_turn = True if __name__ == "__main__": @@ -168,7 +173,7 @@ if __name__ == "__main__": startOption = 0 while True: - PrintIntro() - (pileSize, minSelect, maxSelect, startOption, winOption) = GetParams() + print_intro() + (pileSize, minSelect, maxSelect, startOption, winOption) = get_params() # Just keep playing the game until the user kills it with ctrl-C - PlayGame(pileSize, minSelect, maxSelect, startOption, winOption) + play_game(pileSize, minSelect, maxSelect, startOption, winOption) diff --git a/09_Battle/python/battle.py b/09_Battle/python/battle.py index 0aa6127c..993b9f45 100644 --- a/09_Battle/python/battle.py +++ b/09_Battle/python/battle.py @@ -82,12 +82,12 @@ def get_next_target(sea: SeaType) -> PointType: while True: try: guess = input("? ") - point = guess.split(",") + point_str_list = guess.split(",") - if len(point) != 2: + if len(point_str_list) != 2: raise ValueError() - point = (int(point[0]), int(point[1])) + point = (int(point_str_list[0]), int(point_str_list[1])) if not is_within_sea(point, sea): raise ValueError() @@ -99,7 +99,7 @@ def get_next_target(sea: SeaType) -> PointType: ) -def setup_ships(sea: SeaType): +def setup_ships(sea: SeaType) -> None: place_ship(sea, DESTROYER_LENGTH, 1) place_ship(sea, DESTROYER_LENGTH, 2) place_ship(sea, CRUISER_LENGTH, 3) diff --git a/09_Battle/python/battle_oo.py b/09_Battle/python/battle_oo.py index 468e9dbe..2227a22a 100644 --- a/09_Battle/python/battle_oo.py +++ b/09_Battle/python/battle_oo.py @@ -36,7 +36,7 @@ class Vector: class Sea: WIDTH = 6 - def __init__(self): + def __init__(self) -> None: self._graph = tuple([0 for _ in range(self.WIDTH)] for _ in range(self.WIDTH)) def _validate_item_indices(self, point: Point) -> None: @@ -67,7 +67,7 @@ class Sea: return True # Redefines how python will render this object when asked as a str - def __str__(self): + def __str__(self) -> str: # Display it encoded return "\n".join( [ @@ -145,7 +145,7 @@ class Battle: break - def loop(self): + def loop(self) -> None: while True: target = self._next_target() target_value = self.sea[target] @@ -174,7 +174,7 @@ class Battle: print(f"YOUR CURRENT SPLASH/HIT RATIO IS {self.splash_hit_ratio}") - def _display_sunk_report(self): + def _display_sunk_report(self) -> None: print( "SO FAR, THE BAD GUYS HAVE LOST", f"{self.sea.count_sunk(1, 2)} DESTROYER(S),", @@ -182,7 +182,7 @@ class Battle: f"AND {self.sea.count_sunk(5, 6)} AIRCRAFT CARRIER(S).", ) - def _display_game_end(self): + def _display_game_end(self) -> None: print( "YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET " f"WITH A FINAL SPLASH/HIT RATIO OF {self.splash_hit_ratio}" diff --git a/11_Bombardment/python/bombardment.py b/11_Bombardment/python/bombardment.py index 3f946bb4..5cb64a16 100755 --- a/11_Bombardment/python/bombardment.py +++ b/11_Bombardment/python/bombardment.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 import random from functools import partial +from typing import Callable, List, Set -def display_intro(): +def display_intro() -> None: print("" * 33 + "BOMBARDMENT") print("" * 15 + " CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("\n\n") @@ -23,7 +24,7 @@ def display_intro(): print("\n" * 4) -def display_field(): +def display_field() -> None: for row in range(5): initial = row * 5 + 1 print("\t".join([str(initial + column) for column in range(5)])) @@ -31,22 +32,22 @@ def display_field(): print("\n" * 9) -def positions_list(): +def positions_list() -> List[int]: return list(range(1, 26, 1)) -def generate_enemy_positions(): +def generate_enemy_positions() -> Set[int]: """Randomly choose 4 'positions' out of a range of 1 to 25""" positions = positions_list() random.shuffle(positions) return set(positions[:4]) -def is_valid_position(pos): +def is_valid_position(pos) -> bool: return pos in positions_list() -def prompt_for_player_positions(): +def prompt_for_player_positions() -> Set[int]: while True: raw_positions = input("WHAT ARE YOUR FOUR POSITIONS? ") @@ -63,7 +64,7 @@ def prompt_for_player_positions(): return positions -def prompt_player_for_target(): +def prompt_player_for_target() -> int: while True: target = int(input("WHERE DO YOU WISH TO FIRE YOUR MISSLE? ")) @@ -74,7 +75,7 @@ def prompt_player_for_target(): return target -def attack(target, positions, hit_message, miss_message, progress_messages): +def attack(target, positions, hit_message, miss_message, progress_messages) -> bool: """Performs attack procedure returning True if we are to continue.""" if target in positions: @@ -87,7 +88,7 @@ def attack(target, positions, hit_message, miss_message, progress_messages): return len(positions) > 0 -def init_enemy(): +def init_enemy() -> Callable[[], int]: """Returns a closure analogous to prompt_player_for_target. Will choose from a unique sequence of positions to avoid picking the same position twice.""" @@ -96,7 +97,7 @@ def init_enemy(): random.shuffle(position_sequence) position = iter(position_sequence) - def choose(): + def choose() -> int: return next(position) return choose @@ -119,7 +120,7 @@ ENEMY_PROGRESS_MESSAGES = ( ) -def play(): +def play() -> None: display_intro() display_field() diff --git a/13_Bounce/python/bounce.py b/13_Bounce/python/bounce.py index 477c4261..fc11c204 100644 --- a/13_Bounce/python/bounce.py +++ b/13_Bounce/python/bounce.py @@ -6,16 +6,17 @@ A physics simulation Ported by Dave LeCompte """ +from typing import Tuple PAGE_WIDTH = 64 -def print_centered(msg): +def print_centered(msg: str) -> None: spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) print(spaces + msg) -def print_header(title): +def print_header(title: str) -> None: print_centered(title) print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() @@ -23,7 +24,7 @@ def print_header(title): print() -def print_instructions(): +def print_instructions() -> None: print("THIS SIMULATION LETS YOU SPECIFY THE INITIAL VELOCITY") print("OF A BALL THROWN STRAIGHT UP, AND THE COEFFICIENT OF") print("ELASTICITY OF THE BALL. PLEASE USE A DECIMAL FRACTION") @@ -34,7 +35,7 @@ def print_instructions(): print() -def get_initial_conditions(): +def get_initial_conditions() -> Tuple[float, float, float]: delta_t = float(input("TIME INCREMENT (SEC)? ")) print() v0 = float(input("VELOCITY (FPS)? ")) @@ -45,12 +46,12 @@ def get_initial_conditions(): return delta_t, v0, coeff_rest -def print_at_tab(line, tab, s): +def print_at_tab(line: str, tab: int, s: str) -> str: line += (" " * (tab - len(line))) + s return line -def run_simulation(delta_t, v0, coeff_rest): +def run_simulation(delta_t, v0, coeff_rest) -> None: bounce_time = [0] * 20 # time of each bounce print("FEET") @@ -61,14 +62,14 @@ def run_simulation(delta_t, v0, coeff_rest): bounce_time[i] = v0 * coeff_rest ** (i - 1) / 16 # Draw the trajectory of the bouncing ball, one slice of height at a time - h = int(-16 * (v0 / 32) ** 2 + v0**2 / 32 + 0.5) + h: float = int(-16 * (v0 / 32) ** 2 + v0**2 / 32 + 0.5) while h >= 0: line = "" if int(h) == h: line += str(int(h)) total_time = 0 for i in range(1, sim_dur + 1): - tm = 0 + tm: float = 0 while tm <= bounce_time[i]: total_time += delta_t if ( @@ -95,7 +96,7 @@ def run_simulation(delta_t, v0, coeff_rest): print() -def main(): +def main() -> None: print_header("BOUNCE") print_instructions() diff --git a/14_Bowling/python/bowling.py b/14_Bowling/python/bowling.py index b2fdd500..d4e66ab4 100644 --- a/14_Bowling/python/bowling.py +++ b/14_Bowling/python/bowling.py @@ -1,14 +1,14 @@ import random -def simulateRoll(pins): +def simulate_roll(pins) -> None: for _ in range(20): x = random.randint(0, 14) if x < len(pins): pins[x] = 1 -def calculate_score(rolls): +def calculate_score(rolls) -> int: score = 0 frame = 1 b = 1 @@ -41,7 +41,7 @@ class Player: prev_score = 0 pins = [0] * 10 # reset the pins for ball in range(2): - simulateRoll(pins) + simulate_roll(pins) score = sum(pins) self.show(pins) pin_count = score - prev_score @@ -69,7 +69,7 @@ class Player: for _ball in range(extra): if score == 10: pins = [0] * 10 - simulateRoll(pins) + simulate_roll(pins) score = sum(pins) self.rolls.append(score) @@ -92,7 +92,7 @@ def centreText(text, width): return (" " * ((width - t) // 2)) + text -def main(): +def main() -> None: print(centreText("Bowl", 80)) print(centreText("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", 80)) print() diff --git a/16_Bug/python/Bug.py b/16_Bug/python/Bug.py index f144be04..e2acb1b2 100644 --- a/16_Bug/python/Bug.py +++ b/16_Bug/python/Bug.py @@ -49,7 +49,7 @@ def print_legs(n_legs): print() -def main(): +def main() -> None: print_n_whitespaces(34) print("BUG") print_n_whitespaces(15) @@ -59,8 +59,8 @@ def main(): print("THE GAME BUG") print("I HOPE YOU ENJOY THIS GAME.") print() - Z = input("DO YOU WANT INSTRUCTIONS? ") - if Z != "NO": + want_instructions = input("DO YOU WANT INSTRUCTIONS? ") + if want_instructions != "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") @@ -269,8 +269,8 @@ def main(): Y = Y + 2 if C == 1: continue - Z = input("DO YOU WANT THE PICTURES? ") - if Z != "NO": + want_pictures = input("DO YOU WANT THE PICTURES? ") + if want_pictures != "NO": print("*****YOUR BUG*****") print_n_newlines(2) if A != 0: diff --git a/16_Bug/python/bug-overengineered.py b/16_Bug/python/bug-overengineered.py index 73a1a347..723034af 100644 --- a/16_Bug/python/bug-overengineered.py +++ b/16_Bug/python/bug-overengineered.py @@ -9,11 +9,12 @@ Ported by Peter Sharp from collections import namedtuple from random import randint +from typing import Any, Dict PAGE_WIDTH = 64 -def main(states, data): +def main(states, data) -> None: """ Starts the game loop using given states and data @@ -327,7 +328,7 @@ if __name__ == "__main__": ) # all the data used by the game - data = { + data: Dict[str, Any] = { "state": "start", "partNo": None, "players": {"YOU": [0] * len(part_types), "I": [0] * len(part_types)}, diff --git a/17_Bullfight/python/Bullfight.py b/17_Bullfight/python/Bullfight.py index 06f35e8e..b25d35f0 100644 --- a/17_Bullfight/python/Bullfight.py +++ b/17_Bullfight/python/Bullfight.py @@ -1,17 +1,18 @@ import math import random +from typing import Dict, Union -def print_n_whitespaces(n: int): +def print_n_whitespaces(n: int) -> None: print(" " * n, end="") -def print_n_newlines(n: int): +def print_n_newlines(n: int) -> None: for _ in range(n): print() -def subroutine_1610(): +def subroutine_1610(A, AS, BS, LS) -> float: B = 3 / A * random.random() if B < 0.37: C = 0.5 @@ -43,23 +44,22 @@ def subroutine_1610(): return C -def FNC(): +def FNC(L: float, D: Dict[int, float], A: int) -> float: Q = ( 4.5 + L / 6 - (D[1] + D[2]) * 2.5 + 4 * D[4] + 2 * D[5] - (D[3] ** 2) / 120 - A ) * random.random() return Q -print_n_whitespaces(34) -print("BULL") -print_n_whitespaces(15) -print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") +def print_header() -> None: + print_n_whitespaces(34) + print("BULL") + print_n_whitespaces(15) + print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") + print_n_newlines(2) -print_n_newlines(2) -L = 1 -Z = input("DO YOU WANT INSTRUCTIONS? ") -if Z != "NO": +def print_instructions() -> None: print("HELLO, ALL YOU BLOODLOVERS AND AFICIONADOS.") print("HERE IS YOUR BIG CHANCE TO KILL A BULL.") print() @@ -79,144 +79,153 @@ if Z != "NO": print() print("THE BETTER THE JOB THE PICADORES AND TOREADORES DO,") print("THE BETTER YOUR CHANCES ARE.") -print_n_newlines(2) -D = {4: 1, 5: 1} -LS = ["", "SUPERB", "GOOD", "FAIR", "POOR", "AWFUL"] -A = random.randint(1, 5) -print(f"YOU HAVE DRAWN A {LS[A]} BULL.") -if A > 4: - print("YOU'RE LUCKY.") -elif A < 2: - print("GOOD LUCK. YOU'LL NEED IT.") + +def print_intro() -> None: + print_header() + Z = input("DO YOU WANT INSTRUCTIONS? ") + if Z != "NO": + print_instructions() + print_n_newlines(2) + + +def main() -> None: + print_intro() + L: float = 1 + D: Dict[int, float] = {4: 1, 5: 1} + LS = ["", "SUPERB", "GOOD", "FAIR", "POOR", "AWFUL"] + A = random.randint(1, 5) + print(f"YOU HAVE DRAWN A {LS[A]} BULL.") + if A > 4: + print("YOU'RE LUCKY.") + elif A < 2: + print("GOOD LUCK. YOU'LL NEED IT.") + print() print() -print() -AS = "PICADO" -BS = "RES" -C = subroutine_1610() -D[1] = C -AS = "TOREAD" -BS = "ORES" -subroutine_1610() -D[2] = C -print_n_newlines(2) -D[3] = 0 -while True: - D[3] = D[3] + 1 # 660 - print(f"PASS NUMBER {D[3]}") - if D[3] >= 3: - while True: # 1930 - AS = input("HERE COMES THE BULL. TRY FOR A KILL? ") - if AS not in ["YES", "NO"]: - print("INCORRECT ANSWER - - PLEASE TYPE 'YES' OR 'NO'.") - else: - break - Z1 = 1 if AS == "YES" else 2 - if Z1 != 1: - print("CAPE MOVE? ", end="") - else: - pass - # goto 1130 - else: - print("THE BULL IS CHARGING AT YOU! YOU ARE THE MATADOR--") - while True: # 1930 - AS = input("DO YOU WANT TO KILL THE BULL? ") - if AS not in ["YES", "NO"]: - print("INCORRECT ANSWER - - PLEASE TYPE 'YES' OR 'NO'.") - else: - break - Z1 = 1 if AS == "YES" else 2 - if Z1 != 1: - print("WHAT MOVE DO YOU MAKE WITH THE CAPE? ", end="") - else: - # goto 1130 - pass - gore = 0 - if Z1 != 1: # NO - while True: - E = float(input()) - if E != float(int(abs(E))): - print("DON'T PANIC, YOU IDIOT! PUT DOWN A CORRECT NUMBER") - elif E < 3: - break - if E == 0: - M = 3 - elif E == 1: - M = 2 - else: - M = 0.5 - L = L + M - F = (6 - A + M / 10) * random.random() / ((D[1] + D[2] + D[3] / 10) * 5) - if F < 0.51: - continue - gore = 1 - else: # YES - print() - print("IT IS THE MOMENT OF TRUTH.") - print() - H = int(input("HOW DO YOU TRY TO KILL THE BULL? ")) - if H not in [4, 5]: - print("YOU PANICKED. THE BULL GORED YOU.") - gore = 2 - # goto 970 - else: - K = (6 - A) * 10 * random.random() / ((D[1] + D[2]) * 5 * D[3]) - if H == 4: - if K > 0.8: - gore = 1 - else: - if K > 0.2: - gore = 1 - if gore == 0: - print("YOU KILLED THE BULL!") - D[5] = 2 - break - if gore > 0: - if gore == 1: - print("THE BULL HAS GORED YOU!") - death = False - while True: - _ = random.randint(1, 2) # 970 - if _ == 1: - print("YOU ARE DEAD.") - D[4] = 1.5 - # goto 1320 - death = True - break - else: - print("YOU ARE STILL ALIVE.") - print() - print("DO YOU RUN FROM THE RING? ", end="") - while True: # 1930 - AS = input() - if AS not in ["YES", "NO"]: - print("INCORRECT ANSWER - - PLEASE TYPE 'YES' OR 'NO'.") - else: - break - Z1 = 1 if AS == "YES" else 2 - if Z1 == 2: - print("YOU ARE BRAVE. STUPID, BUT BRAVE.") - _ = random.randint(1, 2) - if _ == 1: - D[4] = 2 - # goto 660, outter while loop - death = True - break - else: - print("YOU ARE GORED AGAIN!") - # goto 970 + AS = "PICADO" + BS = "RES" + C = subroutine_1610(A, AS, BS, LS) + D[1] = C + AS = "TOREAD" + BS = "ORES" + subroutine_1610(A, AS, BS, LS) + D[2] = C + print_n_newlines(2) + D[3] = 0 + while True: + D[3] = D[3] + 1 # 660 + print(f"PASS NUMBER {D[3]}") + if D[3] >= 3: + while True: # 1930 + AS = input("HERE COMES THE BULL. TRY FOR A KILL? ") + if AS not in ["YES", "NO"]: + print("INCORRECT ANSWER - - PLEASE TYPE 'YES' OR 'NO'.") else: - print("COWARD") - D[4] = 0 - # goto 1310, break outter while loop + break + Z1 = 1 if AS == "YES" else 2 + if Z1 != 1: + print("CAPE MOVE? ", end="") + else: + pass + # goto 1130 + else: + print("THE BULL IS CHARGING AT YOU! YOU ARE THE MATADOR--") + while True: # 1930 + AS = input("DO YOU WANT TO KILL THE BULL? ") + if AS not in ["YES", "NO"]: + print("INCORRECT ANSWER - - PLEASE TYPE 'YES' OR 'NO'.") + else: + break + Z1 = 1 if AS == "YES" else 2 + if Z1 != 1: + print("WHAT MOVE DO YOU MAKE WITH THE CAPE? ", end="") + else: + # goto 1130 + pass + gore = 0 + if Z1 != 1: # NO + while True: + E = float(input()) + if E != float(int(abs(E))): + print("DON'T PANIC, YOU IDIOT! PUT DOWN A CORRECT NUMBER") + elif E < 3: + break + if E == 0: + M: Union[int, float] = 3 + elif E == 1: + M = 2 + else: + M = 0.5 + L = L + M + F = (6 - A + M / 10) * random.random() / ((D[1] + D[2] + D[3] / 10) * 5) + if F < 0.51: + continue + gore = 1 + else: # YES + print() + print("IT IS THE MOMENT OF TRUTH.") + print() + H = int(input("HOW DO YOU TRY TO KILL THE BULL? ")) + if H not in [4, 5]: + print("YOU PANICKED. THE BULL GORED YOU.") + gore = 2 + # goto 970 + else: + K = (6 - A) * 10 * random.random() / ((D[1] + D[2]) * 5 * D[3]) + if H == 4: + if K > 0.8: + gore = 1 + else: + if K > 0.2: + gore = 1 + if gore == 0: + print("YOU KILLED THE BULL!") + D[5] = 2 + break + if gore > 0: + if gore == 1: + print("THE BULL HAS GORED YOU!") + death = False + while True: + _ = random.randint(1, 2) # 970 + if _ == 1: + print("YOU ARE DEAD.") + D[4] = 1.5 + # goto 1320 death = True break + else: + print("YOU ARE STILL ALIVE.") + print() + print("DO YOU RUN FROM THE RING? ", end="") + while True: # 1930 + AS = input() + if AS not in ["YES", "NO"]: + print("INCORRECT ANSWER - - PLEASE TYPE 'YES' OR 'NO'.") + else: + break + Z1 = 1 if AS == "YES" else 2 + if Z1 == 2: + print("YOU ARE BRAVE. STUPID, BUT BRAVE.") + _ = random.randint(1, 2) + if _ == 1: + D[4] = 2 + # goto 660, outter while loop + death = True + break + else: + print("YOU ARE GORED AGAIN!") + # goto 970 + else: + print("COWARD") + D[4] = 0 + # goto 1310, break outter while loop + death = True + break - if death: - break + if death: + break - -def main(): # 1310 print_n_newlines(3) if D[4] == 0: @@ -230,11 +239,11 @@ def main(): print("THE CROWD CHEERS!") print() print("THE CROWD AWARDS YOU") - if FNC() < 2.4: + if FNC(L, D, A) < 2.4: print("NOTHING AT ALL.") - elif FNC() < 4.9: + elif FNC(L, D, A) < 4.9: print("ONE EAR OF THE BULL.") - elif FNC() < 7.4: + elif FNC(L, D, A) < 7.4: print("BOTH EARS OF THE BULL!") print("OLE!") else: diff --git a/18_Bullseye/python/Bullseye.py b/18_Bullseye/python/Bullseye.py index d5e22959..e354ab4e 100644 --- a/18_Bullseye/python/Bullseye.py +++ b/18_Bullseye/python/Bullseye.py @@ -1,16 +1,16 @@ import random -def print_n_whitespaces(n: int): +def print_n_whitespaces(n: int) -> None: print(" " * n, end="") -def print_n_newlines(n: int): +def print_n_newlines(n: int) -> None: for _ in range(n): print() -def main(): +def main() -> None: print_n_whitespaces(32) print("BULLSEYE") print_n_whitespaces(15) diff --git a/19_Bunny/python/bunny.py b/19_Bunny/python/bunny.py index c7ce2bc2..e6e267cf 100755 --- a/19_Bunny/python/bunny.py +++ b/19_Bunny/python/bunny.py @@ -239,19 +239,19 @@ DATA = ( ) -def display_intro(): +def display_intro() -> None: print(tab(33) + "BUNNY") print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("\n\n") -def tab(column): +def tab(column) -> str: """Emulates the TAB command in BASIC. Returns a string with ASCII codes for setting the cursor to the specified column.""" return f"\r\33[{column}C" -def play(): +def play() -> None: display_intro() # Using an iterator will give us a similar interface to BASIC's READ diff --git a/20_Buzzword/python/buzzword.py b/20_Buzzword/python/buzzword.py index f4ff0baa..820b89df 100644 --- a/20_Buzzword/python/buzzword.py +++ b/20_Buzzword/python/buzzword.py @@ -23,7 +23,7 @@ import random -def main(): +def main() -> None: WORDS = [ [ "Ability", diff --git a/21_Calendar/python/calendar.py b/21_Calendar/python/calendar.py index 5332f201..29faff01 100644 --- a/21_Calendar/python/calendar.py +++ b/21_Calendar/python/calendar.py @@ -20,8 +20,10 @@ # ######################################################## +from typing import Tuple -def parse_input(): + +def parse_input() -> Tuple[int, bool]: """ function to parse input for weekday and leap year boolean """ @@ -137,7 +139,7 @@ def calendar(weekday, leap_year): print("\n") -def main(): +def main() -> None: print(" " * 32 + "CALENDAR") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("\n" * 11) diff --git a/22_Change/python/change.py b/22_Change/python/change.py index cb9e72e9..e7610b2e 100644 --- a/22_Change/python/change.py +++ b/22_Change/python/change.py @@ -100,7 +100,7 @@ def print_thanks(): print() -def main(): +def main() -> None: print_header("CHANGE") print_introduction() diff --git a/23_Checkers/python/checkers.py b/23_Checkers/python/checkers.py index 5b5616c2..94c2078b 100644 --- a/23_Checkers/python/checkers.py +++ b/23_Checkers/python/checkers.py @@ -387,7 +387,7 @@ def play_game(): board.play_human_move(start_x, start_y, dest_x, dest_y) -def main(): +def main() -> None: print_header("CHECKERS") print_instructions() diff --git a/24_Chemist/python/chemist.py b/24_Chemist/python/chemist.py index 73dfdc4e..ba546e71 100644 --- a/24_Chemist/python/chemist.py +++ b/24_Chemist/python/chemist.py @@ -58,7 +58,7 @@ def show_ending(): print(" YOUR CONTRIBUTIONS TO THE FIELD OF COMIC BOOK CHEMISTRY.") -def main(): +def main() -> None: print_with_tab(33, "CHEMIST") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/26_Chomp/python/chomp.py b/26_Chomp/python/chomp.py index 0188b269..e4d37981 100755 --- a/26_Chomp/python/chomp.py +++ b/26_Chomp/python/chomp.py @@ -103,7 +103,7 @@ def play_game(): break -def main(): +def main() -> None: print(" " * 33 + "CHOMP") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") print("THIS IS THE GAME OF CHOMP (SCIENTIFIC AMERICAN, JAN 1973)") diff --git a/28_Combat/python/combat.py b/28_Combat/python/combat.py index 87e12532..d6eed5eb 100644 --- a/28_Combat/python/combat.py +++ b/28_Combat/python/combat.py @@ -8,7 +8,7 @@ cpu_navy = 20000 cpu_air = 22000 -def show_intro(): +def show_intro() -> None: global MAX_UNITS print(" " * 32 + "COMBAT") @@ -18,7 +18,7 @@ def show_intro(): print("WE HAVE " + str(MAX_UNITS) + " SOLDIERS APIECE.") -def get_forces(): +def get_forces() -> None: global usr_army, usr_navy, usr_air while True: @@ -34,7 +34,7 @@ def get_forces(): break -def attack_first(): +def attack_first() -> None: global usr_army, usr_navy, usr_air global cpu_army, cpu_navy, cpu_air @@ -110,7 +110,7 @@ def attack_first(): cpu_army = int(2 * cpu_army / 3) -def attack_second(): +def attack_second() -> None: global usr_army, usr_navy, usr_air, cpu_army, cpu_navy, cpu_air global plane_crash_win num_units = 0 @@ -191,7 +191,7 @@ def attack_second(): print("RESPECTIVE COUNTRIES AND LIVE IN PEACE.") -def main(): +def main() -> None: show_intro() get_forces() attack_first() diff --git a/29_Craps/python/craps.py b/29_Craps/python/craps.py index 3e47d014..9d265e4e 100644 --- a/29_Craps/python/craps.py +++ b/29_Craps/python/craps.py @@ -14,11 +14,11 @@ appeared one day one a computer at DEC. from random import randint -def throw_dice(): +def throw_dice() -> int: return randint(1, 6) + randint(1, 6) -def main(): +def main() -> None: print(" " * 33 + "Craps") print(" " * 15 + "Creative Computing Morristown, New Jersey") print() diff --git a/30_Cube/python/cube.py b/30_Cube/python/cube.py index 479edd52..393a494e 100755 --- a/30_Cube/python/cube.py +++ b/30_Cube/python/cube.py @@ -87,7 +87,7 @@ def play_game() -> None: print("\nGoodbye.") -def print_instructions(): +def print_instructions() -> None: print("\nThis is a game in which you will be playing against the") print("random decisions of the computer. The field of play is a") print("cube of side 3. Any of the 27 locations can be designated") diff --git a/32_Diamond/python/diamond.py b/32_Diamond/python/diamond.py index 4d99dacc..bbcc85fe 100644 --- a/32_Diamond/python/diamond.py +++ b/32_Diamond/python/diamond.py @@ -37,7 +37,7 @@ def print_diamond(begin_width, end_width, step, width, count): n += step -def main(): +def main() -> None: print_with_tab(33, "DIAMOND") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/33_Dice/python/dice.py b/33_Dice/python/dice.py index 3aedc5ce..1529a739 100644 --- a/33_Dice/python/dice.py +++ b/33_Dice/python/dice.py @@ -29,7 +29,7 @@ import random -def main(): +def main() -> None: # 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). diff --git a/34_Digits/python/Digits.py b/34_Digits/python/Digits.py index 12aec85c..d632f0b4 100644 --- a/34_Digits/python/Digits.py +++ b/34_Digits/python/Digits.py @@ -1,14 +1,14 @@ import random -def print_intro(): +def print_intro() -> None: print(" DIGITS") print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("\n\n") print("THIS IS A GAME OF GUESSING.") -def read_instruction_choice(): +def read_instruction_choice() -> bool: print("FOR INSTRUCTIONS, TYPE '1', ELSE TYPE '0' ? ") try: choice = int(input()) @@ -17,7 +17,7 @@ def read_instruction_choice(): return False -def print_instructions(): +def print_instructions() -> None: print("\n") print("PLEASE TAKE A PIECE OF PAPER AND WRITE DOWN") print("THE DIGITS '0', '1', OR '2' THIRTY TIMES AT RANDOM.") @@ -70,7 +70,7 @@ def print_summary_report(running_correct: int): print("IT'S A TIE GAME.") -def main(): +def main() -> None: print_intro() if read_instruction_choice(): print_instructions() @@ -88,8 +88,8 @@ def main(): l[0][0] = 2 l[4][1] = 2 l[8][2] = 2 - z = 26 - z1 = 8 + z: float = 26 + z1: float = 8 z2 = 2 running_correct = 0 diff --git a/35_Even_Wins/python/evenwins.py b/35_Even_Wins/python/evenwins.py index 97032239..cd2a01dd 100644 --- a/35_Even_Wins/python/evenwins.py +++ b/35_Even_Wins/python/evenwins.py @@ -208,7 +208,7 @@ def play_game(): serious_error(f"play_game: unknown player {whose_turn}") -def main(): +def main() -> None: global whose_turn welcome_screen() diff --git a/38_Fur_Trader/python/furtrader.py b/38_Fur_Trader/python/furtrader.py index deeb3f67..b58328c7 100755 --- a/38_Fur_Trader/python/furtrader.py +++ b/38_Fur_Trader/python/furtrader.py @@ -4,7 +4,7 @@ import random # for generating random numbers import sys # for system function, like exit() # global variables for storing player's status -player_funds = 0 # no money +player_funds: float = 0 # no money player_furs = [0, 0, 0, 0] # no furs diff --git a/40_Gomoko/python/Gomoko.py b/40_Gomoko/python/Gomoko.py index 294e9300..3df79495 100644 --- a/40_Gomoko/python/Gomoko.py +++ b/40_Gomoko/python/Gomoko.py @@ -47,8 +47,7 @@ def print_banner(): def get_board_dimensions() -> int: n = 0 while True: - n = input("WHAT IS YOUR BOARD SIZE (MIN 7/ MAX 19)? ") - n = int(n) + n = int(input("WHAT IS YOUR BOARD SIZE (MIN 7/ MAX 19)? ")) if n < 7 or n > 19: print("I SAID, THE MINIMUM IS 7, THE MAXIMUM IS 19.") print() @@ -61,10 +60,10 @@ def get_move() -> Tuple[int, int]: while True: xy = input("YOUR PLAY (I,J)? ") print() - x, y = xy.split(",") + x_str, y_str = xy.split(",") try: - x = int(x) - y = int(y) + x = int(x_str) + y = int(y_str) except Exception: print("ILLEGAL MOVE. TRY AGAIN...") continue @@ -82,7 +81,7 @@ def initialize_board(n: int) -> List[List[int]]: return board -def main(): +def main() -> None: print_banner() while True: @@ -147,8 +146,7 @@ def main(): print_board(board, n) print() print("THANKS FOR THE GAME!!") - repeat = input("PLAY AGAIN (1 FOR YES, 0 FOR NO)? ") - repeat = int(repeat) + repeat = int(input("PLAY AGAIN (1 FOR YES, 0 FOR NO)? ")) if repeat == 0: break diff --git a/41_Guess/python/guess.py b/41_Guess/python/guess.py index b1cc8e97..7b15050c 100644 --- a/41_Guess/python/guess.py +++ b/41_Guess/python/guess.py @@ -55,7 +55,7 @@ def limit_set(): return limit, limit_goal -def main(): +def main() -> None: limit, limit_goal = limit_set() while True: guess_count = 1 diff --git a/43_Hammurabi/python/hamurabi.py b/43_Hammurabi/python/hamurabi.py index 6bf990df..5c476ca9 100644 --- a/43_Hammurabi/python/hamurabi.py +++ b/43_Hammurabi/python/hamurabi.py @@ -32,7 +32,7 @@ def b_input(promptstring): # emulate BASIC input. It rejects non-numeric values return int(x) -def main(): +def main() -> None: seed() title = "HAMURABI" title = title.rjust(32, " ") @@ -45,7 +45,7 @@ def main(): print("FOR A TEN-YEAR TERM OF OFFICE.\n") D1 = 0 - P1 = 0 + P1: float = 0 year = 0 population = 95 grain_stores = 2800 diff --git a/44_Hangman/python/hangman.py b/44_Hangman/python/hangman.py index c5521d1e..cbceb6a2 100755 --- a/44_Hangman/python/hangman.py +++ b/44_Hangman/python/hangman.py @@ -234,7 +234,7 @@ def play_game(guess_target): break -def main(): +def main() -> None: print(" " * 32 + "HANGMAN") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") diff --git a/45_Hello/python/hello.py b/45_Hello/python/hello.py index a69cc33d..4955d6b8 100644 --- a/45_Hello/python/hello.py +++ b/45_Hello/python/hello.py @@ -177,7 +177,7 @@ def happy_goodbye(user_name): print(f"NICE MEETING YOU, {user_name}, HAVE A NICE DAY.") -def main(): +def main() -> None: print_with_tab(33, "HELLO") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/46_Hexapawn/python/hexapawn.py b/46_Hexapawn/python/hexapawn.py index 69ee11b4..eb97c8a4 100644 --- a/46_Hexapawn/python/hexapawn.py +++ b/46_Hexapawn/python/hexapawn.py @@ -489,7 +489,7 @@ def play_game(): return -def main(): +def main() -> None: print_header("HEXAPAWN") if prompt_yes_no("INSTRUCTIONS (Y-N)?"): print_instructions() diff --git a/48_High_IQ/python/High_IQ.py b/48_High_IQ/python/High_IQ.py index 66d1879c..58ded067 100644 --- a/48_High_IQ/python/High_IQ.py +++ b/48_High_IQ/python/High_IQ.py @@ -168,7 +168,7 @@ def move(board): return False -def main(): +def main() -> None: print(" " * 33 + "H-I-Q") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_instructions() diff --git a/50_Horserace/python/horserace.py b/50_Horserace/python/horserace.py index 556beb21..4d54555c 100644 --- a/50_Horserace/python/horserace.py +++ b/50_Horserace/python/horserace.py @@ -245,7 +245,7 @@ def print_race_results(race_positions, odds, bets, player_names): basic_print(f"{name} WINS ${amount * odds[winning_horse_idx]}") -def main_loop(player_names, horse_odds): +def main_loop(player_names, horse_odds) -> None: """Main game loop""" while True: @@ -260,7 +260,7 @@ def main_loop(player_names, horse_odds): break -def main(): +def main() -> None: # introduction, player names and horse odds are only generated once introduction() player_names = setup_players() diff --git a/52_Kinema/python/kinema.py b/52_Kinema/python/kinema.py index 347fff2a..9fb81f87 100644 --- a/52_Kinema/python/kinema.py +++ b/52_Kinema/python/kinema.py @@ -74,7 +74,7 @@ def ask_player(question, answer): return score -def main(): +def main() -> None: print_with_tab(33, "KINEMA") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/54_Letter/python/letter.py b/54_Letter/python/letter.py index d80b368a..312e2247 100644 --- a/54_Letter/python/letter.py +++ b/54_Letter/python/letter.py @@ -66,7 +66,7 @@ def play_game(): continue -def main(): +def main() -> None: print_with_tab(33, "LETTER") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/55_Life/python/life.py b/55_Life/python/life.py index 5a8e5062..b11e1bdf 100644 --- a/55_Life/python/life.py +++ b/55_Life/python/life.py @@ -48,7 +48,7 @@ def get_pattern(): c += 1 -def main(): +def main() -> None: print_header("LIFE") pattern = get_pattern() diff --git a/57_Literature_Quiz/python/litquiz.py b/57_Literature_Quiz/python/litquiz.py index b5b9d1c5..94ad1ff3 100644 --- a/57_Literature_Quiz/python/litquiz.py +++ b/57_Literature_Quiz/python/litquiz.py @@ -84,7 +84,7 @@ def print_instructions(): print() -def main(): +def main() -> None: print_centered("LITERATURE QUIZ") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/58_Love/python/love.py b/58_Love/python/love.py index 739fb5dc..a15237ba 100644 --- a/58_Love/python/love.py +++ b/58_Love/python/love.py @@ -72,7 +72,7 @@ DATA = [ ROW_LEN = sum(DATA[0]) -def main(): +def main() -> None: # Display intro text print("\n Love") print("Creative Computing Morristown, New Jersey") diff --git a/59_Lunar_LEM_Rocket/python/lunar.py b/59_Lunar_LEM_Rocket/python/lunar.py index bbbaf69a..f9c5d285 100644 --- a/59_Lunar_LEM_Rocket/python/lunar.py +++ b/59_Lunar_LEM_Rocket/python/lunar.py @@ -346,7 +346,7 @@ def run_simulation(): capsule.update_state(sim_clock, delta_t, new_state) -def main(): +def main() -> None: print_header("LUNAR") print_instructions() while True: diff --git a/61_Math_Dice/python/mathdice.py b/61_Math_Dice/python/mathdice.py index e131a0e5..3f258545 100644 --- a/61_Math_Dice/python/mathdice.py +++ b/61_Math_Dice/python/mathdice.py @@ -46,7 +46,7 @@ def print_dice(n): print(" ----- ") -def main(): +def main() -> None: while True: d1 = randint(1, 6) diff --git a/63_Name/python/name.py b/63_Name/python/name.py index 589d97f2..298f50e4 100644 --- a/63_Name/python/name.py +++ b/63_Name/python/name.py @@ -22,7 +22,7 @@ def is_yes_ish(answer): return False -def main(): +def main() -> None: print_with_tab(34, "NAME") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/64_Nicomachus/python/nicomachus.py b/64_Nicomachus/python/nicomachus.py index bcc7a8a3..71972720 100644 --- a/64_Nicomachus/python/nicomachus.py +++ b/64_Nicomachus/python/nicomachus.py @@ -61,7 +61,7 @@ def play_game(): print("LET'S TRY ANOTHER") -def main(): +def main() -> None: print_with_tab(33, "NICOMA") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/65_Nim/python/Traditional_NIM.py b/65_Nim/python/Traditional_NIM.py index d1003f13..c59f4ecb 100644 --- a/65_Nim/python/Traditional_NIM.py +++ b/65_Nim/python/Traditional_NIM.py @@ -70,7 +70,7 @@ class NIM: return sum == 0 -def main(): +def main() -> None: # Game initialization game = NIM() diff --git a/66_Number/python/number.py b/66_Number/python/number.py index 7746ff6a..8e6f2287 100644 --- a/66_Number/python/number.py +++ b/66_Number/python/number.py @@ -32,7 +32,7 @@ def fnr(): return random.randint(1, 5) -def main(): +def main() -> None: print_with_tab(33, "NUMBER") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() @@ -41,7 +41,7 @@ def main(): print_instructions() - points = 100 + points: float = 100 while points <= 500: print("GUESS A NUMBER FROM 1 TO 5") diff --git a/67_One_Check/python/onecheck.py b/67_One_Check/python/onecheck.py index 3510da70..b866ebd9 100644 --- a/67_One_Check/python/onecheck.py +++ b/67_One_Check/python/onecheck.py @@ -7,7 +7,7 @@ def tab(x): return " " * x -def main(): +def main() -> None: # Initial instructions print(tab(30) + "ONE CHECK") diff --git a/68_Orbit/python/orbit.py b/68_Orbit/python/orbit.py index 252be2a6..727998f6 100644 --- a/68_Orbit/python/orbit.py +++ b/68_Orbit/python/orbit.py @@ -143,7 +143,7 @@ def play_game(): return False -def main(): +def main() -> None: print_centered("ORBIT") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/69_Pizza/python/pizza.py b/69_Pizza/python/pizza.py index 0f7d28e2..c8e9eb47 100644 --- a/69_Pizza/python/pizza.py +++ b/69_Pizza/python/pizza.py @@ -150,7 +150,7 @@ def play_game(num_turns, player_name): break -def main(): +def main() -> None: print_header("PIZZA") player_name = print_instructions() diff --git a/70_Poetry/python/poetry.py b/70_Poetry/python/poetry.py index f27a202e..961f78af 100644 --- a/70_Poetry/python/poetry.py +++ b/70_Poetry/python/poetry.py @@ -131,7 +131,7 @@ def pick_phrase(): phrase = j + 1 -def main(): +def main() -> None: print_centered("POETRY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/74_Rock_Scissors_Paper/python/rockscissors.py b/74_Rock_Scissors_Paper/python/rockscissors.py index cc56adf6..09d63d2d 100644 --- a/74_Rock_Scissors_Paper/python/rockscissors.py +++ b/74_Rock_Scissors_Paper/python/rockscissors.py @@ -67,7 +67,7 @@ def play_game(): print("\nThanks for playing!!\n") -def main(): +def main() -> None: print(" " * 21 + "GAME OF ROCK, SCISSORS, PAPER") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") diff --git a/75_Roulette/python/roulette.py b/75_Roulette/python/roulette.py index 204dcdd2..b20b00e6 100644 --- a/75_Roulette/python/roulette.py +++ b/75_Roulette/python/roulette.py @@ -1,11 +1,12 @@ import random from datetime import date +from typing import List, Tuple global RED_NUMBERS RED_NUMBERS = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36] -def print_instructions(): +def print_instructions() -> None: print( """ THIS IS THE BETTING LAYOUT @@ -59,69 +60,69 @@ THE MINIMUM BET IS $5, THE MAXIMUM IS $500. ) -def query_bets(): +def query_bets() -> Tuple[List[int], List[int]]: """Queries the user to input their bets""" - betCount = -1 - while betCount <= 0: + bet_count = -1 + while bet_count <= 0: try: - betCount = int(input("HOW MANY BETS? ")) + bet_count = int(input("HOW MANY BETS? ")) except Exception: ... - bet_IDs = [-1] * betCount - bet_Values = [0] * betCount + bet_ids = [-1] * bet_count + bet_values = [0] * bet_count - for i in range(betCount): - while bet_IDs[i] == -1: + for i in range(bet_count): + while bet_ids[i] == -1: try: inString = input("NUMBER " + str(i + 1) + "? ").split(",") - id, val = int(inString[0]), int(inString[1]) + id_, val = int(inString[0]), int(inString[1]) # check other bet_IDs for j in range(i): - if id != -1 and bet_IDs[j] == id: - id = -1 + if id_ != -1 and bet_ids[j] == id_: + id_ = -1 print("YOU ALREADY MADE THAT BET ONCE, DUM-DUM") break - if id > 0 and id <= 50 and val >= 5 and val <= 500: - bet_IDs[i] = id - bet_Values[i] = val + if id_ > 0 and id_ <= 50 and val >= 5 and val <= 500: + bet_ids[i] = id_ + bet_values[i] = val except Exception: - ... - return bet_IDs, bet_Values + pass + return bet_ids, bet_values -def bet_results(bet_IDs, bet_Values, result): +def bet_results(bet_ids: List[int], bet_values: List[int], result): """Computes the results, prints them, and returns the total net winnings""" total_winnings = 0 - def get_modifier(id, num): + def get_modifier(id_: int, num: int) -> int: if ( - (id == 37 and num <= 12) - or (id == 38 and num > 12 and num <= 24) - or (id == 39 and num > 24 and num < 37) - or (id == 40 and num < 37 and num % 3 == 1) - or (id == 41 and num < 37 and num % 3 == 2) - or (id == 42 and num < 37 and num % 3 == 0) + (id_ == 37 and num <= 12) + or (id_ == 38 and num > 12 and num <= 24) + or (id_ == 39 and num > 24 and num < 37) + or (id_ == 40 and num < 37 and num % 3 == 1) + or (id_ == 41 and num < 37 and num % 3 == 2) + or (id_ == 42 and num < 37 and num % 3 == 0) ): return 2 elif ( - (id == 43 and num <= 18) - or (id == 44 and num > 18 and num <= 36) - or (id == 45 and num % 2 == 0) - or (id == 46 and num % 2 == 1) - or (id == 47 and num in RED_NUMBERS) - or (id == 48 and num not in RED_NUMBERS) + (id_ == 43 and num <= 18) + or (id_ == 44 and num > 18 and num <= 36) + or (id_ == 45 and num % 2 == 0) + or (id_ == 46 and num % 2 == 1) + or (id_ == 47 and num in RED_NUMBERS) + or (id_ == 48 and num not in RED_NUMBERS) ): return 1 - elif id < 37 and id == num: + elif id_ < 37 and id_ == num: return 35 else: return -1 - for i in range(len(bet_IDs)): - winnings = bet_Values[i] * get_modifier(bet_IDs[i], result) + for i in range(len(bet_ids)): + winnings = bet_values[i] * get_modifier(bet_ids[i], result) total_winnings += winnings if winnings >= 0: @@ -132,7 +133,7 @@ def bet_results(bet_IDs, bet_Values, result): return winnings -def print_check(amount): +def print_check(amount: int) -> None: """Prints a check of a given amount""" name = input("TO WHOM SHALL I MAKE THE CHECK? ") @@ -149,7 +150,7 @@ def print_check(amount): print("-" * 72) -def main(): +def main() -> None: player_balance = 1000 host_balance = 100000 @@ -159,11 +160,11 @@ def main(): print() print() - if stringtobool(input("DO YOU WANT INSTRUCTIONS? ")): + if string_to_bool(input("DO YOU WANT INSTRUCTIONS? ")): print_instructions() while True: - bet_IDs, bet_Values = query_bets() + bet_ids, bet_values = query_bets() print("SPINNING") print() @@ -180,7 +181,7 @@ def main(): print(str(val) + " BLACK") print() - total_winnings = bet_results(bet_IDs, bet_Values, val) + total_winnings = bet_results(bet_ids, bet_values, val) player_balance += total_winnings host_balance -= total_winnings @@ -195,7 +196,7 @@ def main(): print("YOU BROKE THE HOUSE!") player_balance = 101000 break - if not stringtobool(input("PLAY AGAIN? ")): + if not string_to_bool(input("PLAY AGAIN? ")): break if player_balance <= 0: @@ -206,7 +207,7 @@ def main(): print("COME BACK SOON!") -def stringtobool(string): +def string_to_bool(string: str) -> bool: """Converts a string to a bool""" return string.lower() in ("yes", "y", "true", "t", "yes") diff --git a/76_Russian_Roulette/python/russianroulette.py b/76_Russian_Roulette/python/russianroulette.py index 84960761..43cfbfb9 100644 --- a/76_Russian_Roulette/python/russianroulette.py +++ b/76_Russian_Roulette/python/russianroulette.py @@ -28,18 +28,16 @@ def initial_message(): print("Here is a Revolver.") -def parse_input(): - correct_input = False - while not correct_input: +def parse_input() -> int: + while True: try: i = int(input("? ")) - correct_input = True + return i except ValueError: print("Number expected...") - return i -def main(): +def main() -> None: initial_message() while True: dead = False diff --git a/77_Salvo/python/salvo.py b/77_Salvo/python/salvo.py index 94078bea..3cfa36fd 100644 --- a/77_Salvo/python/salvo.py +++ b/77_Salvo/python/salvo.py @@ -54,7 +54,6 @@ computer_board = [] # array representing the coordinates # for each ship for player and computer # array is in the same order as SHIPS -player_ship_coords = [] computer_ship_coords = [] @@ -486,7 +485,7 @@ def execute_turn(turn, current_turn): ###################################### -def main(): +def main() -> None: # keep track of the turn current_turn = 0 diff --git a/78_Sine_Wave/python/sinewave.py b/78_Sine_Wave/python/sinewave.py index f5ade637..4f001b56 100644 --- a/78_Sine_Wave/python/sinewave.py +++ b/78_Sine_Wave/python/sinewave.py @@ -25,7 +25,7 @@ import math import time -def main(): +def main() -> None: # Constants STRINGS = ("Creative", "Computing") # Text to display MAX_LINES = 160 @@ -42,7 +42,7 @@ def main(): # "REMarkable program by David Ahl" string_index = 0 - radians = 0 + radians: float = 0 width = CENTER - 1 # "Start long loop" diff --git a/79_Slalom/python/slalom.py b/79_Slalom/python/slalom.py index 3176e986..1db5d5d8 100644 --- a/79_Slalom/python/slalom.py +++ b/79_Slalom/python/slalom.py @@ -130,7 +130,7 @@ def run(gates, lvl, max_speeds): medals["bronze"] += 1 -def main(): +def main() -> None: print("Slalom".rjust(39)) print("Creative Computing Morristown, New Jersey\n\n\n".rjust(57)) diff --git a/80_Slots/python/slots.py b/80_Slots/python/slots.py index 16495518..e54f3b4e 100644 --- a/80_Slots/python/slots.py +++ b/80_Slots/python/slots.py @@ -117,7 +117,7 @@ def adjust_profits(wheel, m, profits): return profits -def final_message(profits): +def final_message(profits) -> None: if profits < 0: print("Pay up! Please leave your money on the terminal") elif profits == 0: @@ -126,7 +126,7 @@ def final_message(profits): print("Collect your winings from the H&M cashier.") -def main(): +def main() -> None: profits = 0 keep_betting = True diff --git a/81_Splat/python/splat.py b/81_Splat/python/splat.py index 357f358e..fec98749 100644 --- a/81_Splat/python/splat.py +++ b/81_Splat/python/splat.py @@ -24,6 +24,7 @@ Ported in 2021 by Jonas Nockert / @lemonad """ from math import sqrt from random import choice, random, uniform +from typing import List PAGE_WIDTH = 72 @@ -293,10 +294,10 @@ def print_header(): ) -def main(): +def main() -> None: print_header() - successful_jumps = [] + successful_jumps: List[float] = [] while True: chute_altitude = jump() if chute_altitude > 0: diff --git a/82_Stars/python/stars.py b/82_Stars/python/stars.py index ab67d9d3..f0540155 100644 --- a/82_Stars/python/stars.py +++ b/82_Stars/python/stars.py @@ -57,7 +57,7 @@ def get_guess(): return guess -def main(): +def main() -> None: # Display intro text print("\n Stars") print("Creative Computing Morristown, New Jersey") diff --git a/84_Super_Star_Trek/python/superstartrek.py b/84_Super_Star_Trek/python/superstartrek.py index 578e1cda..fdaa3c3d 100644 --- a/84_Super_Star_Trek/python/superstartrek.py +++ b/84_Super_Star_Trek/python/superstartrek.py @@ -14,7 +14,13 @@ import random from math import sqrt -from typing import Any, List +from typing import Any, Callable, Dict, List + +# Global variables +restart = False +s = 0 +e = 0 +d: List[int] = [] # ------------------------------------------------------------------------- # Utility functions @@ -923,10 +929,10 @@ def end_game(won=False, quit=True, enterprise_killed=False): # ------------------------------------------------------------------------- -def main(): +def main() -> None: global restart - f = { + f: Dict[str, Callable[[], None]] = { "NAV": navigation, "SRS": short_range_scan, "LRS": long_range_scan, diff --git a/84_Super_Star_Trek/python/superstartrekins.py b/84_Super_Star_Trek/python/superstartrekins.py index 1dae1749..45954518 100644 --- a/84_Super_Star_Trek/python/superstartrekins.py +++ b/84_Super_Star_Trek/python/superstartrekins.py @@ -139,7 +139,7 @@ def print_instructions(): print(" GALACTIC REGIONS REFERRED TO IN THE GAME.") -def main(): +def main() -> None: print_header() if not get_yes_no("DO YOU NEED INSTRUCTIONS (Y/N)? "): return diff --git a/85_Synonym/python/synonym.py b/85_Synonym/python/synonym.py index 046758d6..628034d1 100644 --- a/85_Synonym/python/synonym.py +++ b/85_Synonym/python/synonym.py @@ -76,12 +76,12 @@ def ask_question(question_number): return -def finish(): +def finish() -> None: print() print("SYNONYM DRILL COMPLETED.") -def main(): +def main() -> None: print_header("SYNONYM") print_instructions() diff --git a/86_Target/python/target.py b/86_Target/python/target.py index af158999..b51bc5a5 100644 --- a/86_Target/python/target.py +++ b/86_Target/python/target.py @@ -160,7 +160,7 @@ def play_game(): next_target() -def main(): +def main() -> None: print_header("TARGET") print_instructions() diff --git a/87_3-D_Plot/python/3dplot.py b/87_3-D_Plot/python/3dplot.py index 8452f0a4..ea3f3ee9 100644 --- a/87_3-D_Plot/python/3dplot.py +++ b/87_3-D_Plot/python/3dplot.py @@ -11,7 +11,7 @@ def equation(x: float) -> float: return 30 * exp(-x * x / 100) -def main(): +def main() -> None: print(" " * 32 + "3D PLOT") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n\n") diff --git a/90_Tower/python/tower.py b/90_Tower/python/tower.py index fcca9e96..835555a2 100644 --- a/90_Tower/python/tower.py +++ b/90_Tower/python/tower.py @@ -127,7 +127,7 @@ class Game: from_tower.add(disk) -def main(): +def main() -> None: print( """ IN THIS PROGRAM, WE SHALL REFER TO DISKS BY NUMERICAL CODE. diff --git a/91_Train/python/train.py b/91_Train/python/train.py index bf4329d2..d7ac55d8 100644 --- a/91_Train/python/train.py +++ b/91_Train/python/train.py @@ -28,7 +28,7 @@ def play_game(): print("Good! Answer within", error_percent, "percent.") -def main(): +def main() -> None: print(" " * 33 + "TRAIN") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") print("Time - speed distance exercise") diff --git a/92_Trap/python/trap.py b/92_Trap/python/trap.py index f1f294f7..5f74a760 100644 --- a/92_Trap/python/trap.py +++ b/92_Trap/python/trap.py @@ -49,7 +49,7 @@ def play_game(): break -def main(): +def main() -> None: print(" " * 34 + "TRAP") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") if input("Instructions ").lower().startswith("y"): diff --git a/93_23_Matches/python/23matches.py b/93_23_Matches/python/23matches.py index 226b0f3a..5488f08b 100755 --- a/93_23_Matches/python/23matches.py +++ b/93_23_Matches/python/23matches.py @@ -60,7 +60,7 @@ def play_game(): prompt_human = "Your turn -- you may take 1, 2 or 3 matches.\nHow many do you wish to remove " -def main(): +def main() -> None: print(" " * 31 + "23 MATCHHES") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") print("This is a game called '23 Matches'.\n") diff --git a/94_War/python/war.py b/94_War/python/war.py index 78aa7a73..f8d34004 100755 --- a/94_War/python/war.py +++ b/94_War/python/war.py @@ -110,7 +110,7 @@ def play_game(): print("\nThanks for playing. It was fun.") -def main(): +def main() -> None: print(" " * 33 + "WAR") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") print("This is the card game of war. Each card is given by suit-#") diff --git a/95_Weekday/python/weekday.py b/95_Weekday/python/weekday.py index 133cb391..9f550430 100644 --- a/95_Weekday/python/weekday.py +++ b/95_Weekday/python/weekday.py @@ -146,7 +146,7 @@ def end(): print() -def main(): +def main() -> None: print_with_tab(32, "WEEKDAY") print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print() diff --git a/96_Word/python/word.py b/96_Word/python/word.py index 10d1fd20..fcb3fc11 100644 --- a/96_Word/python/word.py +++ b/96_Word/python/word.py @@ -69,7 +69,7 @@ def play_game(): print("\nIf you give up, type '?' for you next guess.") -def main(): +def main() -> None: print(" " * 33 + "WORD") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n")