Python: Add type annotations

This commit is contained in:
Martin Thoma
2022-04-02 09:30:56 +02:00
parent 624c55711c
commit a561322962
15 changed files with 42 additions and 40 deletions

View File

@@ -85,7 +85,7 @@ def get_shot_input() -> Tuple[int, int, int]:
print("Please enter whole numbers only") print("Please enter whole numbers only")
def play_game(search_area, num_charges): def play_game(search_area, num_charges) -> None:
print("\nYou are the captain of the destroyer USS Computer.") print("\nYou are the captain of the destroyer USS Computer.")
print("An enemy sub has been causing you trouble. Your") print("An enemy sub has been causing you trouble. Your")
print(f"mission is to destroy it. You have {num_charges} shots.") print(f"mission is to destroy it. You have {num_charges} shots.")

View File

@@ -2,6 +2,7 @@
import random # for generating random numbers import random # for generating random numbers
import sys # for system function, like exit() import sys # for system function, like exit()
from typing import List
# global variables for storing player's status # global variables for storing player's status
player_funds: float = 0 # no money player_funds: float = 0 # no money
@@ -62,7 +63,7 @@ def get_fort_choice() -> int:
return result return result
def show_fort_comment(which_fort): def show_fort_comment(which_fort) -> None:
"""Print the description for the fort""" """Print the description for the fort"""
print() print()
if which_fort == FORT_MONTREAL: if which_fort == FORT_MONTREAL:
@@ -103,10 +104,10 @@ def get_yes_or_no() -> str:
return result return result
def get_furs_purchase(): def get_furs_purchase() -> List[int]:
"""Prompt the player for how many of each fur type they want. """Prompt the player for how many of each fur type they want.
Accept numeric inputs, re-prompting on incorrect input values""" Accept numeric inputs, re-prompting on incorrect input values"""
results = [] results: List[int] = []
print("YOUR " + str(MAX_FURS) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING") print("YOUR " + str(MAX_FURS) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING")
print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.") print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.")
@@ -123,7 +124,7 @@ def get_furs_purchase():
return results return results
def main(): def main() -> None:
print(" " * 31 + "FUR TRADER") print(" " * 31 + "FUR TRADER")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print(" " * 15 + "(Ported to Python Oct 2012 krt@krt.com.au)") print(" " * 15 + "(Ported to Python Oct 2012 krt@krt.com.au)")
@@ -137,7 +138,7 @@ def main():
if game_state == "starting": if game_state == "starting":
show_introduction() show_introduction()
player_funds = 600 # Initial player start money player_funds: float = 600 # Initial player start money
player_furs = [0, 0, 0, 0] # Player fur inventory player_furs = [0, 0, 0, 0] # Player fur inventory
print("DO YOU WISH TO TRADE FURS?") print("DO YOU WISH TO TRADE FURS?")

View File

@@ -26,13 +26,14 @@ From: Basic Computer Games (1978)
from math import log from math import log
from random import random from random import random
from typing import Tuple
def insert_whitespaces() -> None: def insert_whitespaces() -> None:
print("\n\n\n\n\n") print("\n\n\n\n\n")
def limit_set(): def limit_set() -> Tuple[int, int]:
print(" Guess") print(" Guess")
print("Creative Computing Morristown, New Jersey") print("Creative Computing Morristown, New Jersey")
print("\n\n\n") print("\n\n\n")

View File

@@ -71,7 +71,7 @@ def gunner() -> None:
return return
def main(): def main() -> None:
print(" " * 33 + "GUNNER") print(" " * 33 + "GUNNER")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n\n") print("\n\n\n")

View File

@@ -22,7 +22,7 @@ def get_yes_or_no() -> Tuple[bool, Optional[bool], str]:
return False, None, msg return False, None, msg
def ask_enjoy_question(user_name): def ask_enjoy_question(user_name: str) -> None:
print(f"HI THERE, {user_name}, ARE YOU ENJOYING YOURSELF HERE?") print(f"HI THERE, {user_name}, ARE YOU ENJOYING YOURSELF HERE?")
while True: while True:
@@ -41,7 +41,7 @@ def ask_enjoy_question(user_name):
print("PLEASE ANSWER 'YES' OR 'NO'. DO YOU LIKE IT HERE?") print("PLEASE ANSWER 'YES' OR 'NO'. DO YOU LIKE IT HERE?")
def prompt_for_problems(user_name): def prompt_for_problems(user_name: str) -> str:
print() print()
print(f"SAY, {user_name}, I CAN SOLVE ALL KINDS OF PROBLEMS EXCEPT") print(f"SAY, {user_name}, I CAN SOLVE ALL KINDS OF PROBLEMS EXCEPT")
print("THOSE DEALING WITH GREECE. WHAT KIND OF PROBLEMS DO") print("THOSE DEALING WITH GREECE. WHAT KIND OF PROBLEMS DO")

View File

@@ -5,7 +5,7 @@ MAX_ATTEMPTS = 6
QUESTION_PROMPT = "? " QUESTION_PROMPT = "? "
def main(): def main() -> None:
print("HI LO") print("HI LO")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n") print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print("THIS IS THE GAME OF HI LO.\n") print("THIS IS THE GAME OF HI LO.\n")

View File

@@ -1,7 +1,7 @@
import math import math
import random import random
import time import time
from typing import List from typing import List, Tuple
def basic_print(*zones, **kwargs) -> None: def basic_print(*zones, **kwargs) -> None:
@@ -81,7 +81,7 @@ def setup_players() -> List[str]:
return player_names return player_names
def setup_horses(): def setup_horses() -> List[float]:
"""Generates random odds for each horse. Returns a list of """Generates random odds for each horse. Returns a list of
odds, indexed by the order of the global HORSE_NAMES.""" odds, indexed by the order of the global HORSE_NAMES."""
@@ -102,14 +102,14 @@ def print_horse_odds(odds) -> None:
basic_print("") basic_print("")
def get_bets(player_names): def get_bets(player_names: List[str]) -> List[Tuple[int, float]]:
"""For each player, get the number of the horse to bet on, """For each player, get the number of the horse to bet on,
as well as the amount of money to bet""" as well as the amount of money to bet"""
basic_print("--------------------------------------------------") basic_print("--------------------------------------------------")
basic_print("PLACE YOUR BETS...HORSE # THEN AMOUNT") basic_print("PLACE YOUR BETS...HORSE # THEN AMOUNT")
bets = [] bets: List[Tuple[int, float]] = []
for name in player_names: for name in player_names:
horse = basic_input(name, int) horse = basic_input(name, int)
amount = None amount = None
@@ -125,7 +125,7 @@ def get_bets(player_names):
return bets return bets
def get_distance(odd): def get_distance(odd: float) -> int:
"""Advances a horse during one step of the racing simulation. """Advances a horse during one step of the racing simulation.
The amount travelled is random, but scaled by the odds of the horse""" The amount travelled is random, but scaled by the odds of the horse"""
@@ -181,7 +181,7 @@ def print_race_state(total_distance, race_pos) -> None:
basic_print("XXXXFINISHXXXX") basic_print("XXXXFINISHXXXX")
def simulate_race(odds): def simulate_race(odds) -> List[int]:
num_horses = len(HORSE_NAMES) num_horses = len(HORSE_NAMES)
# in spirit of the original implementation, using two arrays to # in spirit of the original implementation, using two arrays to

View File

@@ -20,7 +20,7 @@ g = 10
EXPECTED_ACCURACY_PERCENT = 15 EXPECTED_ACCURACY_PERCENT = 15
def do_quiz(): def do_quiz() -> None:
print() print()
print() print()
num_questions_correct = 0 num_questions_correct = 0

View File

@@ -23,7 +23,7 @@ def print_instructions() -> None:
print("AS TO HOW CLOSE YOU'RE GETTING TO MY LETTER.") print("AS TO HOW CLOSE YOU'RE GETTING TO MY LETTER.")
def play_game(): def play_game() -> None:
target_value = random.randint(ord("A"), ord("Z")) target_value = random.randint(ord("A"), ord("Z"))
num_guesses = 0 num_guesses = 0
print() print()

View File

@@ -6,6 +6,7 @@ An implementation of John Conway's popular cellular automaton
Ported by Dave LeCompte Ported by Dave LeCompte
""" """
from typing import Dict
PAGE_WIDTH = 64 PAGE_WIDTH = 64
@@ -26,11 +27,11 @@ def print_header(title) -> None:
print() print()
def get_pattern(): def get_pattern() -> Dict[int, str]:
print("ENTER YOUR PATTERN:") print("ENTER YOUR PATTERN:")
c = 0 c = 0
pattern = {} pattern: Dict[int, str] = {}
while True: while True:
line = input() line = input()
if line == "DONE": if line == "DONE":
@@ -98,8 +99,8 @@ def main() -> None:
print() print()
for x in range(min_x, max_x + 1): for x in range(min_x, max_x + 1):
print print()
line = [" "] * MAX_WIDTH line_list = [" "] * MAX_WIDTH
for y in range(min_y, max_y + 1): for y in range(min_y, max_y + 1):
if a[x][y] == 2: if a[x][y] == 2:
a[x][y] = 0 a[x][y] = 0
@@ -109,15 +110,14 @@ def main() -> None:
elif a[x][y] != 1: elif a[x][y] != 1:
continue continue
# line 261 line_list[y] = "*"
line[y] = "*"
next_min_x = min(x, next_min_x) next_min_x = min(x, next_min_x)
next_max_x = max(x, next_max_x) next_max_x = max(x, next_max_x)
next_min_y = min(y, next_min_y) next_min_y = min(y, next_min_y)
next_max_y = max(y, next_max_y) next_max_y = max(y, next_max_y)
print("".join(line)) print("".join(line_list))
# line 295 # line 295
for _ in range(max_x + 1, MAX_HEIGHT): for _ in range(max_x + 1, MAX_HEIGHT):

View File

@@ -19,7 +19,7 @@ class Question:
self.incorrect_message = incorrect_message self.incorrect_message = incorrect_message
self.correct_message = correct_message self.correct_message = correct_message
def ask(self): def ask(self) -> bool:
print(self.question) print(self.question)
options = [f"{i+1}){self.answer_list[i]}" for i in range(len(self.answer_list))] options = [f"{i+1}){self.answer_list[i]}" for i in range(len(self.answer_list))]

View File

@@ -204,7 +204,7 @@ def print_board(guesses) -> None:
# "We did try a version that kept an actual list of all possible combinations # "We did try a version that kept an actual list of all possible combinations
# (as a string array), which was significantly faster than this versionn but # (as a string array), which was significantly faster than this versionn but
# which ate tremendous amounts of memory." # which ate tremendous amounts of memory."
def get_possibility(possibility): def get_possibility(possibility) -> List[int]:
# print(possibility) # print(possibility)
if possibility[0] > -1: # 3530 if possibility[0] > -1: # 3530
current_position = 0 # Python arrays are zero-indexed current_position = 0 # Python arrays are zero-indexed

View File

@@ -15,7 +15,7 @@ Ported by Dave LeCompte
import time import time
def get_yes_or_no(): def get_yes_or_no() -> bool:
while True: while True:
response = input().upper() response = input().upper()
if response == "YES": if response == "YES":
@@ -25,7 +25,7 @@ def get_yes_or_no():
print(f"EH? I DON'T UNDERSTAND '{response}' TRY 'YES' OR 'NO'.") print(f"EH? I DON'T UNDERSTAND '{response}' TRY 'YES' OR 'NO'.")
def play_game(): def play_game() -> None:
print("PLEASE THINK OF A NUMBER BETWEEN 1 AND 100.") print("PLEASE THINK OF A NUMBER BETWEEN 1 AND 100.")
print("YOUR NUMBER DIVIDED BY 3 HAS A REMAINDER OF") print("YOUR NUMBER DIVIDED BY 3 HAS A REMAINDER OF")
a = int(input()) a = int(input())

View File

@@ -1,12 +1,12 @@
import random import random
from typing import Tuple
# Class of the Game
class NIM: class NIM:
def __init__(self): def __init__(self) -> None:
self.piles = {1: 7, 2: 5, 3: 3, 4: 1} self.piles = {1: 7, 2: 5, 3: 3, 4: 1}
def remove_pegs(self, command): def remove_pegs(self, command) -> None:
try: try:
pile, num = command.split(",") pile, num = command.split(",")
@@ -29,7 +29,7 @@ class NIM:
else: else:
print("\nInvalid value of either Peg or Pile\n") print("\nInvalid value of either Peg or Pile\n")
def get_ai_move(self): def get_ai_move(self) -> Tuple[int, int]:
possible_pile = [] possible_pile = []
for k, v in self.piles.items(): for k, v in self.piles.items():
if v != 0: if v != 0:
@@ -48,7 +48,7 @@ class NIM:
for pile, peg in self.piles.items(): for pile, peg in self.piles.items():
print("Pile {} : {}".format(pile, "O " * peg)) print("Pile {} : {}".format(pile, "O " * peg))
def help(self): def help(self) -> None:
print("-" * 10) print("-" * 10)
print('\nThe Game is player with a number of Piles of Objects("O" == one peg)') print('\nThe Game is player with a number of Piles of Objects("O" == one peg)')
print("\nThe Piles are arranged as given below(Tradional NIM)\n") print("\nThe Piles are arranged as given below(Tradional NIM)\n")
@@ -62,7 +62,7 @@ class NIM:
print("\nThe winner is defined as the one that picks the last remaning object") print("\nThe winner is defined as the one that picks the last remaning object")
print("-" * 10) print("-" * 10)
def check_for_win(self): def check_for_win(self) -> bool:
sum = 0 sum = 0
for v in self.piles.values(): for v in self.piles.values():
sum += v sum += v
@@ -96,13 +96,13 @@ def main() -> None:
break break
# Computers Move # Computers Move
command = game.get_ai_move() ai_command = game.get_ai_move()
print( print(
"\nA.I MOVE - A.I Removed {} pegs from Pile {}".format( "\nA.I MOVE - A.I Removed {} pegs from Pile {}".format(
command[1], command[0] ai_command[1], ai_command[0]
) )
) )
game.remove_pegs(str(command[0]) + "," + str(command[1])) game.remove_pegs(str(ai_command[0]) + "," + str(ai_command[1]))
end = game.check_for_win() end = game.check_for_win()
if end: if end:
print("\nComputer Wins the Game, Better Luck Next Time\n") print("\nComputer Wins the Game, Better Luck Next Time\n")

View File

@@ -19,7 +19,7 @@ def print_instructions() -> None:
print() print()
def fnr(): def fnr() -> int:
return random.randint(1, 5) return random.randint(1, 5)