Python: Add type annotations to all 'print' functions (#662)

* Add test to superstartrek and fixes several issues in superstartrek - I probably introduced them 🙈
* Mastermind type annotations
This commit is contained in:
Martin Thoma
2022-03-21 10:41:14 +01:00
committed by GitHub
parent c444da93c0
commit 1b1d50986b
50 changed files with 241 additions and 172 deletions

View File

@@ -4,7 +4,7 @@ import random
QUESTION_PROMPT = "? " QUESTION_PROMPT = "? "
def play(): def play() -> None:
print("BOXING") print("BOXING")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n") print("\n\n")

View File

@@ -2,16 +2,16 @@ import random
import time import time
def print_n_whitespaces(n: int): def print_n_whitespaces(n: int) -> None:
print(" " * n, end="") print(" " * n, end="")
def print_n_newlines(n: int): def print_n_newlines(n: int) -> None:
for _ in range(n): for _ in range(n):
print() print()
def print_feelers(n_feelers, is_player=True): def print_feelers(n_feelers, is_player: bool = True) -> None:
for _ in range(4): for _ in range(4):
print_n_whitespaces(10) print_n_whitespaces(10)
for _ in range(n_feelers): for _ in range(n_feelers):
@@ -19,7 +19,7 @@ def print_feelers(n_feelers, is_player=True):
print() print()
def print_head(): def print_head() -> None:
print(" HHHHHHH") print(" HHHHHHH")
print(" H H") print(" H H")
print(" H O O H") print(" H O O H")
@@ -28,12 +28,12 @@ def print_head():
print(" HHHHHHH") print(" HHHHHHH")
def print_neck(): def print_neck() -> None:
print(" N N") print(" N N")
print(" N N") print(" N N")
def print_body(has_tail=False): def print_body(has_tail: bool = False) -> None:
print(" BBBBBBBBBBBB") print(" BBBBBBBBBBBB")
print(" B B") print(" B B")
print(" B B") print(" B B")
@@ -41,7 +41,7 @@ def print_body(has_tail=False):
print(" BBBBBBBBBBBB") print(" BBBBBBBBBBBB")
def print_legs(n_legs): def print_legs(n_legs: int) -> None:
for _ in range(2): for _ in range(2):
print_n_whitespaces(5) print_n_whitespaces(5)
for _ in range(n_legs): for _ in range(n_legs):

View File

@@ -38,7 +38,7 @@ def main(states, data) -> None:
Bodypart = namedtuple("Bodypart", ["name", "count", "depends"]) Bodypart = namedtuple("Bodypart", ["name", "count", "depends"])
def print_start(_): def print_start(_) -> str:
""" """
Prints start message Prints start message
""" """
@@ -64,7 +64,7 @@ def control_start(cmd):
return action return action
def print_instructions(data): def print_instructions(data) -> str:
""" """
Prints game instructions Prints game instructions
""" """
@@ -171,7 +171,7 @@ def get_finished(data):
return finished return finished
def print_game(data): def print_game(data) -> str:
""" """
Displays the results of the game turn Displays the results of the game turn
""" """
@@ -222,7 +222,7 @@ def print_game(data):
return input("DO YOU WANT THE PICTURES? ") if len(data["logs"]) else "n" return input("DO YOU WANT THE PICTURES? ") if len(data["logs"]) else "n"
def print_pictures(data): def print_pictures(data) -> None:
""" """
Displays what the bugs look like for each player Displays what the bugs look like for each player
""" """
@@ -272,7 +272,7 @@ def control_game(cmd):
return action return action
def print_winner(data): def print_winner(data) -> None:
""" """
Displays the winning message Displays the winning message
""" """
@@ -288,7 +288,7 @@ def exit_game(_):
return "exit" return "exit"
def print_centered(msg, width=PAGE_WIDTH): def print_centered(msg, width=PAGE_WIDTH) -> None:
""" """
Prints given message centered to given width Prints given message centered to given width
""" """
@@ -296,7 +296,7 @@ def print_centered(msg, width=PAGE_WIDTH):
print(spaces + msg) print(spaces + msg)
def print_table(rows): def print_table(rows) -> None:
for row in rows: for row in rows:
print(*row, sep="\t") print(*row, sep="\t")

View File

@@ -9,12 +9,12 @@ Port by Dave LeCompte
PAGE_WIDTH = 64 PAGE_WIDTH = 64
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -22,7 +22,7 @@ def print_header(title):
print() print()
def print_introduction(): def print_introduction() -> None:
print("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE") print("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE")
print("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100.") print("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100.")
print() print()
@@ -35,7 +35,7 @@ def pennies_to_dollar_string(p):
return ds return ds
def compute_change(): def compute_change() -> None:
print("COST OF ITEM?") print("COST OF ITEM?")
cost = float(input()) cost = float(input())
print("AMOUNT OF PAYMENT?") print("AMOUNT OF PAYMENT?")
@@ -94,7 +94,7 @@ def compute_change():
print(f"{change_in_pennies} PENNY(S)") print(f"{change_in_pennies} PENNY(S)")
def print_thanks(): def print_thanks() -> None:
print("THANK YOU, COME AGAIN.") print("THANK YOU, COME AGAIN.")
print() print()
print() print()

View File

@@ -26,12 +26,12 @@ MoveRecord = collections.namedtuple(
) )
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -62,7 +62,7 @@ def is_legal_board_coordinate(x, y):
class Board: class Board:
def __init__(self): def __init__(self) -> None:
self.spaces = [[0 for y in range(8)] for x in range(8)] self.spaces = [[0 for y in range(8)] for x in range(8)]
for x in range(8): for x in range(8):
if (x % 2) == 0: if (x % 2) == 0:
@@ -74,7 +74,7 @@ class Board:
self.spaces[x][5] = COMPUTER_PIECE self.spaces[x][5] = COMPUTER_PIECE
self.spaces[x][1] = HUMAN_PIECE self.spaces[x][1] = HUMAN_PIECE
def __str__(self): def __str__(self) -> str:
pieces = { pieces = {
EMPTY_SPACE: ".", EMPTY_SPACE: ".",
HUMAN_PIECE: "O", HUMAN_PIECE: "O",
@@ -336,7 +336,7 @@ class Board:
return True return True
def print_instructions(): def print_instructions() -> None:
print("THIS IS THE GAME OF CHECKERS. THE COMPUTER IS X,") print("THIS IS THE GAME OF CHECKERS. THE COMPUTER IS X,")
print("AND YOU ARE O. THE COMPUTER WILL MOVE FIRST.") print("AND YOU ARE O. THE COMPUTER WILL MOVE FIRST.")
print("SQUARES ARE REFERRED TO BY A COORDINATE SYSTEM.") print("SQUARES ARE REFERRED TO BY A COORDINATE SYSTEM.")
@@ -351,17 +351,17 @@ def print_instructions():
print() print()
def print_human_won(): def print_human_won() -> None:
print() print()
print("YOU WIN.") print("YOU WIN.")
def print_computer_won(): def print_computer_won() -> None:
print() print()
print("I WIN.") print("I WIN.")
def play_game(): def play_game() -> None:
board = Board() board = Board()
while True: while True:

View File

@@ -11,7 +11,7 @@ import random
MAX_LIVES = 9 MAX_LIVES = 9
def print_with_tab(space_count, msg): def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0: if space_count > 0:
spaces = " " * space_count spaces = " " * space_count
else: else:

View File

@@ -1,4 +1,4 @@
def print_lightning_bolt(): def print_lightning_bolt() -> None:
print("*" * 36) print("*" * 36)
n = 24 n = 24
@@ -17,7 +17,7 @@ def print_lightning_bolt():
print("*" * 36) print("*" * 36)
def print_solution(n): def print_solution(n: int) -> None:
print(f"\n{n} plus 3 gives {n + 3}. This Divided by 5 equals {(n + 3) / 5}") print(f"\n{n} plus 3 gives {n + 3}. This Divided by 5 equals {(n + 3) / 5}")
print(f"This times 8 gives {((n + 3) / 5) * 8}. If we divide 5 and add 5.") print(f"This times 8 gives {((n + 3) / 5) * 8}. If we divide 5 and add 5.")

View File

@@ -7,7 +7,7 @@ Ported by Dave LeCompte
""" """
def print_with_tab(space_count, msg): def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0: if space_count > 0:
spaces = " " * space_count spaces = " " * space_count
else: else:
@@ -15,7 +15,7 @@ def print_with_tab(space_count, msg):
print(spaces + msg) print(spaces + msg)
def print_diamond(begin_width, end_width, step, width, count): def print_diamond(begin_width, end_width, step, width, count) -> None:
edgeString = "CC" edgeString = "CC"
fill = "!" fill = "!"

View File

@@ -56,7 +56,7 @@ def read_continue_choice():
return False return False
def print_summary_report(running_correct: int): def print_summary_report(running_correct: int) -> None:
print() print()
if running_correct > 10: if running_correct > 10:
print() print()

View File

@@ -92,7 +92,7 @@ def to_int(s):
return False, 0 return False, 0
def print_board(): def print_board() -> None:
global marbles_in_middle global marbles_in_middle
global human_marbles global human_marbles
global computer_marbles global computer_marbles

View File

@@ -36,8 +36,8 @@ def flip_bits(
""" """
while m == n: while m == n:
r = r_function(n) r = r_function(n)
n = r - int(math.floor(r)) n_tmp = r - int(math.floor(r))
n = int(10 * n) n = int(10 * n_tmp)
if row[n] == "X": if row[n] == "X":
row[n] = "O" row[n] = "O"
break break
@@ -46,7 +46,7 @@ def flip_bits(
return row, n return row, n
def print_instructions(): def print_instructions() -> None:
print(" " * 32 + "FLIPFLOP") print(" " * 32 + "FLIPFLOP")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n" * 2) print("\n" * 2)

View File

@@ -22,7 +22,7 @@ FORT_NEWYORK = 3
FORT_NAMES = ["HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"] FORT_NAMES = ["HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"]
def print_at_column(column: int, words: str): def print_at_column(column: int, words: str) -> None:
"""Print the words at the specified column""" """Print the words at the specified column"""
spaces = " " * column # make a fat string of spaces spaces = " " * column # make a fat string of spaces
print(spaces + words) print(spaces + words)

View File

@@ -16,7 +16,7 @@ from golf import (
) )
def test_odds(): def test_odds() -> None:
n = 1000 n = 1000
p = sum(odds(50) for i in range(n)) / n p = sum(odds(50) for i in range(n)) / n
assert abs(p - 0.5) < 0.1 assert abs(p - 0.5) < 0.1

View File

@@ -6,7 +6,7 @@ def print_n_whitespaces(n: int) -> None:
print(" " * n, end="") print(" " * n, end="")
def print_board(A: List[List[Any]], n): def print_board(A: List[List[Any]], n: int) -> None:
"""PRINT THE BOARD""" """PRINT THE BOARD"""
for i in range(n): for i in range(n):
print(" ", end="") print(" ", end="")
@@ -22,7 +22,7 @@ def check_move(_I, _J, _N) -> bool: # 910
return True return True
def print_banner(): def print_banner() -> None:
print_n_whitespaces(33) print_n_whitespaces(33)
print("GOMOKU") print("GOMOKU")
print_n_whitespaces(15) print_n_whitespaces(15)

View File

@@ -30,7 +30,7 @@ from math import log
from random import random from random import random
def insert_whitespaces(): def insert_whitespaces() -> None:
print("\n\n\n\n\n") print("\n\n\n\n\n")

View File

@@ -6,7 +6,7 @@ from math import sin
from random import random from random import random
def gunner(): def gunner() -> None:
gun_range = int(40000 * random() + 20000) gun_range = int(40000 * random() + 20000)
print("\nMAXIMUM RANGE OF YOUR GUN IS", gun_range, "YARDS.") print("\nMAXIMUM RANGE OF YOUR GUN IS", gun_range, "YARDS.")

View File

@@ -11,7 +11,7 @@ Ported by Dave LeCompte
import time import time
def print_with_tab(space_count, msg): def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0: if space_count > 0:
spaces = " " * space_count spaces = " " * space_count
else: else:

View File

@@ -61,12 +61,12 @@ wins = 0
losses = 0 losses = 0
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -74,7 +74,7 @@ def print_header(title):
print() print()
def print_instructions(): def print_instructions() -> None:
print( print(
""" """
THIS PROGRAM PLAYS THE GAME OF HEXAPAWN. THIS PROGRAM PLAYS THE GAME OF HEXAPAWN.
@@ -215,7 +215,7 @@ def init_board():
return [COMPUTER_PIECE] * 3 + [EMPTY_SPACE] * 3 + [HUMAN_PIECE] * 3 return [COMPUTER_PIECE] * 3 + [EMPTY_SPACE] * 3 + [HUMAN_PIECE] * 3
def print_board(board): def print_board(board) -> None:
piece_dict = {COMPUTER_PIECE: "X", EMPTY_SPACE: ".", HUMAN_PIECE: "O"} piece_dict = {COMPUTER_PIECE: "X", EMPTY_SPACE: ".", HUMAN_PIECE: "O"}
space = " " * 10 space = " " * 10
@@ -242,7 +242,7 @@ def get_coordinates():
print_illegal() print_illegal()
def print_illegal(): def print_illegal() -> None:
print("ILLEGAL MOVE.") print("ILLEGAL MOVE.")

View File

@@ -40,7 +40,7 @@ def new_board():
return board return board
def print_instructions(): def print_instructions() -> None:
print( print(
""" """
HERE IS THE BOARD: HERE IS THE BOARD:
@@ -73,7 +73,7 @@ NUMBERS. OK, LET'S BEGIN.
) )
def print_board(board): def print_board(board) -> None:
"""Prints the boards using indexes in the passed parameter""" """Prints the boards using indexes in the passed parameter"""
print(" " * 2 + board[13] + board[14] + board[15]) print(" " * 2 + board[13] + board[14] + board[15])
print(" " * 2 + board[22] + board[23] + board[24]) print(" " * 2 + board[22] + board[23] + board[24])
@@ -108,7 +108,7 @@ def print_board(board):
print(" " * 2 + board[67] + board[68] + board[69]) print(" " * 2 + board[67] + board[68] + board[69])
def play_game(): def play_game() -> None:
# Create new board # Create new board
board = new_board() board = new_board()

View File

@@ -3,7 +3,7 @@ import random
import time import time
def basic_print(*zones, **kwargs): def basic_print(*zones, **kwargs) -> None:
"""Simulates the PRINT command from BASIC to some degree. """Simulates the PRINT command from BASIC to some degree.
Supports `printing zones` if given multiple arguments.""" Supports `printing zones` if given multiple arguments."""
@@ -92,7 +92,7 @@ def setup_horses():
return [round(total / odd, 2) for odd in odds] return [round(total / odd, 2) for odd in odds]
def print_horse_odds(odds): def print_horse_odds(odds) -> None:
"""Print the odds for each horse""" """Print the odds for each horse"""
basic_print("") basic_print("")
@@ -146,7 +146,7 @@ def get_distance(odd):
return 7 return 7
def print_race_state(total_distance, race_pos): def print_race_state(total_distance, race_pos) -> None:
"""Outputs the current state/stop of the race. """Outputs the current state/stop of the race.
Each horse is placed according to the distance they have travelled. In Each horse is placed according to the distance they have travelled. In
case some horses travelled the same distance, their numbers are printed case some horses travelled the same distance, their numbers are printed
@@ -226,7 +226,7 @@ def simulate_race(odds):
time.sleep(1) time.sleep(1)
def print_race_results(race_positions, odds, bets, player_names): def print_race_results(race_positions, odds, bets, player_names) -> None:
"""Print the race results, as well as the winnings of each player""" """Print the race results, as well as the winnings of each player"""
# print the race positions first # print the race positions first

View File

@@ -20,7 +20,7 @@ g = 10
EXPECTED_ACCURACY_PERCENT = 15 EXPECTED_ACCURACY_PERCENT = 15
def print_with_tab(spaces_count, msg): def print_with_tab(spaces_count, msg) -> None:
if spaces_count > 0: if spaces_count > 0:
spaces = " " * spaces_count spaces = " " * spaces_count
else: else:

View File

@@ -15,7 +15,7 @@ import random
BELLS_ON_SUCCESS = False BELLS_ON_SUCCESS = False
def print_with_tab(space_count, msg): def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0: if space_count > 0:
spaces = " " * space_count spaces = " " * space_count
else: else:
@@ -24,7 +24,7 @@ def print_with_tab(space_count, msg):
print(spaces + msg) print(spaces + msg)
def print_instructions(): def print_instructions() -> None:
print("LETTER GUESSING GAME") print("LETTER GUESSING GAME")
print() print()
print("I'LL THINK OF A LETTER OF THE ALPHABET, A TO Z.") print("I'LL THINK OF A LETTER OF THE ALPHABET, A TO Z.")

View File

@@ -13,12 +13,12 @@ MAX_WIDTH = 70
MAX_HEIGHT = 24 MAX_HEIGHT = 24
def print_centered(msg): def print_centered(msg) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()

View File

@@ -67,13 +67,13 @@ questions = [
] ]
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((64 - len(msg)) // 2) spaces = " " * ((64 - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_instructions(): def print_instructions() -> None:
print("TEST YOUR KNOWLEDGE OF CHILDREN'S LITERATURE.") print("TEST YOUR KNOWLEDGE OF CHILDREN'S LITERATURE.")
print() print()
print("THIS IS A MULTIPLE-CHOICE QUIZ.") print("THIS IS A MULTIPLE-CHOICE QUIZ.")

View File

@@ -35,12 +35,12 @@ BURN_RIGHT = BURN_LEFT + BURN_WIDTH
PhysicalState = collections.namedtuple("PhysicalState", ["velocity", "altitude"]) PhysicalState = collections.namedtuple("PhysicalState", ["velocity", "altitude"])
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -74,7 +74,7 @@ def add_ljust(line, s, pos):
return line + s return line + s
def print_instructions(): def print_instructions() -> None:
# Somebody had a bad experience with Xerox. # Somebody had a bad experience with Xerox.
print("THIS IS A COMPUTER SIMULATION OF AN APOLLO LUNAR") print("THIS IS A COMPUTER SIMULATION OF AN APOLLO LUNAR")
@@ -86,7 +86,7 @@ def print_instructions():
print() print()
def print_intro(): def print_intro() -> None:
print("SET BURN RATE OF RETRO ROCKETS TO ANY VALUE BETWEEN") print("SET BURN RATE OF RETRO ROCKETS TO ANY VALUE BETWEEN")
print("0 (FREE FALL) AND 200 (MAXIMUM BURN) POUNDS PER SECOND.") print("0 (FREE FALL) AND 200 (MAXIMUM BURN) POUNDS PER SECOND.")
print("SET NEW BURN RATE EVERY 10 SECONDS.") print("SET NEW BURN RATE EVERY 10 SECONDS.")
@@ -127,7 +127,7 @@ def show_out_of_fuel(sim_clock, capsule):
show_landing(sim_clock, capsule) show_landing(sim_clock, capsule)
def format_line_for_report(t, miles, feet, velocity, fuel, burn_rate, is_header): def format_line_for_report(t, miles, feet, velocity, fuel, burn_rate, is_header) -> str:
line = add_rjust("", t, SECONDS_RIGHT) line = add_rjust("", t, SECONDS_RIGHT)
line = add_rjust(line, miles, ALT_MI_RIGHT) line = add_rjust(line, miles, ALT_MI_RIGHT)
line = add_rjust(line, feet, ALT_FT_RIGHT) line = add_rjust(line, feet, ALT_FT_RIGHT)
@@ -199,7 +199,7 @@ class Capsule:
return PhysicalState(altitude=new_altitude, velocity=new_velocity) return PhysicalState(altitude=new_altitude, velocity=new_velocity)
def make_state_display_string(self, sim_clock): def make_state_display_string(self, sim_clock) -> str:
seconds = sim_clock.elapsed_time seconds = sim_clock.elapsed_time
miles = int(self.a) miles = int(self.a)
feet = int(5280 * (self.a - miles)) feet = int(5280 * (self.a - miles))

View File

@@ -1,9 +1,17 @@
import random import random
import sys import sys
from typing import List, Union
# Global variables
colors = ["BLACK", "WHITE", "RED", "GREEN", "ORANGE", "YELLOW", "PURPLE", "TAN"]
color_letters = "BWRGOYPT"
num_positions = 0
num_colors = 100
human_score = 0
computer_score = 0
def main(): def main() -> None:
global colors, color_letters, num_positions, num_colors, human_score, computer_score global colors, color_letters, num_positions, num_colors, human_score, computer_score
colors = ["BLACK", "WHITE", "RED", "GREEN", "ORANGE", "YELLOW", "PURPLE", "TAN"] colors = ["BLACK", "WHITE", "RED", "GREEN", "ORANGE", "YELLOW", "PURPLE", "TAN"]
color_letters = "BWRGOYPT" color_letters = "BWRGOYPT"
@@ -33,21 +41,23 @@ def main():
while current_round <= num_rounds: while current_round <= num_rounds:
print(f"Round number {current_round}") print(f"Round number {current_round}")
num_moves = 1 num_moves = 1
guesses = [] guesses: List[List[Union[str, int]]] = []
turn_over = False turn_over = False
print("Guess my combination ...") print("Guess my combination ...")
answer = int(possibilities * random.random()) answer = int(possibilities * random.random())
numeric_answer = [-1] * num_positions numeric_answer = [-1] * num_positions
for _ in range(0, answer): for _ in range(0, answer):
numeric_answer = get_possibility(numeric_answer) numeric_answer = get_possibility(numeric_answer)
# human_readable_answer = make_human_readable(numeric_answer) # human_readable_answer = make_human_readable(numeric_answer, color_letters)
while num_moves < 10 and not turn_over: while num_moves < 10 and not turn_over:
print(f"Move # {num_moves} Guess : ") print(f"Move # {num_moves} Guess : ")
user_command = input("Guess ") user_command = input("Guess ")
if user_command == "BOARD": if user_command == "BOARD":
print_board(guesses) # 2000 print_board(guesses) # 2000
elif user_command == "QUIT": # 2500 elif user_command == "QUIT": # 2500
human_readable_answer = make_human_readable(numeric_answer) human_readable_answer = make_human_readable(
numeric_answer, color_letters
)
print(f"QUITTER! MY COMBINATION WAS: {human_readable_answer}") print(f"QUITTER! MY COMBINATION WAS: {human_readable_answer}")
print("GOOD BYE") print("GOOD BYE")
quit() quit()
@@ -59,14 +69,14 @@ def main():
print(f"INVALID GUESS: {invalid_letters}") print(f"INVALID GUESS: {invalid_letters}")
else: else:
guess_results = compare_two_positions( guess_results = compare_two_positions(
user_command, make_human_readable(numeric_answer) user_command, make_human_readable(numeric_answer, color_letters)
) )
print(f"Results: {guess_results}") print(f"Results: {guess_results}")
if guess_results[1] == num_positions: # correct guess if guess_results[1] == num_positions: # correct guess
turn_over = True turn_over = True
print(f"You guessed it in {num_moves} moves!") print(f"You guessed it in {num_moves} moves!")
human_score = human_score + num_moves human_score = human_score + num_moves
print_score() print_score(computer_score, human_score)
else: else:
print( print(
"You have {} blacks and {} whites".format( "You have {} blacks and {} whites".format(
@@ -79,11 +89,11 @@ def main():
print("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!") print("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!")
print( print(
"THE ACTUAL COMBINATION WAS: {}".format( "THE ACTUAL COMBINATION WAS: {}".format(
make_human_readable(numeric_answer) make_human_readable(numeric_answer, color_letters)
) )
) )
human_score = human_score + num_moves human_score = human_score + num_moves
print_score() print_score(computer_score, human_score)
# COMPUTER TURN # COMPUTER TURN
guesses = [] guesses = []
@@ -124,18 +134,20 @@ def main():
numeric_guess = [-1] * num_positions numeric_guess = [-1] * num_positions
for _ in range(0, guess): for _ in range(0, guess):
numeric_guess = get_possibility(numeric_guess) numeric_guess = get_possibility(numeric_guess)
human_readable_guess = make_human_readable(numeric_guess) human_readable_guess = make_human_readable(
print(f"My guess is: {human_readable_guess}") numeric_guess, color_letters
blacks, whites = input("ENTER BLACKS, WHITES (e.g. 1,2): ").split(
","
) )
blacks = int(blacks) print(f"My guess is: {human_readable_guess}")
whites = int(whites) blacks_str, whites_str = input(
"ENTER BLACKS, WHITES (e.g. 1,2): "
).split(",")
blacks = int(blacks_str)
whites = int(whites_str)
if blacks == num_positions: # Correct guess if blacks == num_positions: # Correct guess
print(f"I GOT IT IN {num_moves} MOVES") print(f"I GOT IT IN {num_moves} MOVES")
turn_over = True turn_over = True
computer_score = computer_score + num_moves computer_score = computer_score + num_moves
print_score() print_score(computer_score, human_score)
else: else:
num_moves += 1 num_moves += 1
for i in range(0, possibilities): for i in range(0, possibilities):
@@ -147,21 +159,21 @@ def main():
numeric_possibility numeric_possibility
) )
human_readable_possibility = make_human_readable( human_readable_possibility = make_human_readable(
numeric_possibility numeric_possibility, color_letters
) # 4000 ) # 4000
comparison = compare_two_positions( comparison = compare_two_positions(
human_readable_possibility, human_readable_guess human_readable_possibility, human_readable_guess
) )
print(comparison) print(comparison)
if (blacks > comparison[1]) or (whites > comparison[2]): if (blacks > comparison[1]) or (whites > comparison[2]): # type: ignore
all_possibilities[i] = 0 all_possibilities[i] = 0
if not turn_over: # COMPUTER DID NOT GUESS if not turn_over: # COMPUTER DID NOT GUESS
print("I USED UP ALL MY MOVES!") print("I USED UP ALL MY MOVES!")
print("I GUESS MY CPU IS JUST HAVING AN OFF DAY.") print("I GUESS MY CPU IS JUST HAVING AN OFF DAY.")
computer_score = computer_score + num_moves computer_score = computer_score + num_moves
print_score() print_score(computer_score, human_score)
current_round += 1 current_round += 1
print_score(is_final_score=True) print_score(computer_score, human_score, is_final_score=True)
sys.exit() sys.exit()
@@ -177,7 +189,7 @@ def get_invalid_letters(user_command):
# 2000 # 2000
def print_board(guesses): def print_board(guesses) -> None:
"""Prints previous guesses within the round.""" """Prints previous guesses within the round."""
print("Board") print("Board")
print("Move\tGuess\tBlack White") print("Move\tGuess\tBlack White")
@@ -209,7 +221,7 @@ def get_possibility(possibility):
# 4500 # 4500
def compare_two_positions(guess, answer): def compare_two_positions(guess: str, answer: str) -> List[Union[str, int]]:
"""Returns blacks (correct color and position) and whites (correct color only) for candidate position (guess) versus reference position (answer).""" """Returns blacks (correct color and position) and whites (correct color only) for candidate position (guess) versus reference position (answer)."""
increment = 0 increment = 0
blacks = 0 blacks = 0
@@ -235,7 +247,7 @@ def compare_two_positions(guess, answer):
# 5000 + logic from 1160 # 5000 + logic from 1160
def print_score(is_final_score=False): def print_score(computer_score, human_score, is_final_score: bool = False) -> None:
"""Prints score after each turn ends, including final score at end of game.""" """Prints score after each turn ends, including final score at end of game."""
if is_final_score: if is_final_score:
print("GAME OVER") print("GAME OVER")
@@ -247,7 +259,7 @@ def print_score(is_final_score=False):
# 4000, 5500, 6000 subroutines are all identical # 4000, 5500, 6000 subroutines are all identical
def make_human_readable(num): def make_human_readable(num: List[int], color_letters) -> str:
"""Make the numeric representation of a position human readable.""" """Make the numeric representation of a position human readable."""
retval = "" retval = ""
for i in range(0, len(num)): for i in range(0, len(num)):

View File

@@ -13,11 +13,11 @@ To conclude the program, type 0.
) )
def print_dice(n): def print_dice(n: int) -> None:
def print_0(): def print_0() -> None:
print("| |") print("| |")
def print_2(): def print_2() -> None:
print("| * * |") print("| * * |")
print(" ----- ") print(" ----- ")

View File

@@ -2,7 +2,7 @@ from math import sqrt
from random import randint from random import randint
def introduction(): def introduction() -> None:
print( print(
"""The object of this game is to find 4 mugwumps """The object of this game is to find 4 mugwumps
hidden on a 10*10 grid. Homebase is position 0,0. hidden on a 10*10 grid. Homebase is position 0,0.
@@ -38,7 +38,7 @@ def calculate_distance(guess, mugwump):
return d return d
def play_again(): def play_again() -> None:
print("THAT WAS FUN! LET'S PLAY AGAIN.......") print("THAT WAS FUN! LET'S PLAY AGAIN.......")
choice = input("Press Enter to play again, any other key then Enter to quit.") choice = input("Press Enter to play again, any other key then Enter to quit.")
if choice == "": if choice == "":

View File

@@ -7,7 +7,7 @@ Ported by Dave LeCompte
""" """
def print_with_tab(space_count, msg): def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0: if space_count > 0:
spaces = " " * space_count spaces = " " * space_count
else: else:

View File

@@ -15,7 +15,7 @@ Ported by Dave LeCompte
import time import time
def print_with_tab(spaces_count, msg): def print_with_tab(spaces_count: int, msg: str) -> None:
if spaces_count > 0: if spaces_count > 0:
spaces = " " * spaces_count spaces = " " * spaces_count
else: else:

View File

@@ -44,7 +44,7 @@ class NIM:
def _command_integrity(self, num, pile): def _command_integrity(self, num, pile):
return pile <= 4 and pile >= 1 and num <= self.piles[pile] return pile <= 4 and pile >= 1 and num <= self.piles[pile]
def print_pegs(self): def print_pegs(self) -> None:
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))

View File

@@ -9,7 +9,7 @@ Ported by Dave LeCompte
import random import random
def print_with_tab(num_spaces, msg): def print_with_tab(num_spaces: int, msg: str) -> None:
if num_spaces > 0: if num_spaces > 0:
spaces = " " * num_spaces spaces = " " * num_spaces
else: else:
@@ -18,7 +18,7 @@ def print_with_tab(num_spaces, msg):
print(spaces + msg) print(spaces + msg)
def print_instructions(): def print_instructions() -> None:
print("YOU HAVE 100 POINTS. BY GUESSING NUMBERS FROM 1 TO 5, YOU") print("YOU HAVE 100 POINTS. BY GUESSING NUMBERS FROM 1 TO 5, YOU")
print("CAN GAIN OR LOSE POINTS DEPENDING UPON HOW CLOSE YOU GET TO") print("CAN GAIN OR LOSE POINTS DEPENDING UPON HOW CLOSE YOU GET TO")
print("A RANDOM NUMBER SELECTED BY THE COMPUTER.") print("A RANDOM NUMBER SELECTED BY THE COMPUTER.")

View File

@@ -12,12 +12,12 @@ import random
PAGE_WIDTH = 64 PAGE_WIDTH = 64
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_instructions(): def print_instructions() -> None:
print( print(
"""SOMEWHERE ABOVE YOUR PLANET IS A ROMULAN SHIP. """SOMEWHERE ABOVE YOUR PLANET IS A ROMULAN SHIP.

View File

@@ -14,12 +14,12 @@ customer_names = [chr(65 + x) for x in range(16)]
street_names = [str(n) for n in range(1, 5)] street_names = [str(n) for n in range(1, 5)]
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -27,16 +27,16 @@ def print_header(title):
print() print()
def print_ticks(): def print_ticks() -> None:
for _ in range(4): for _ in range(4):
print("-") print("-")
def print_ruler(): def print_ruler() -> None:
print(" -----1-----2-----3-----4-----") print(" -----1-----2-----3-----4-----")
def print_street(i): def print_street(i: int) -> None:
street_number = 3 - i street_number = 3 - i
street_name = street_names[street_number] street_name = street_names[street_number]
@@ -52,7 +52,7 @@ def print_street(i):
print(line) print(line)
def print_map(): def print_map() -> None:
print("MAP OF THE CITY OF HYATTSVILLE") print("MAP OF THE CITY OF HYATTSVILLE")
print() print()
print_ruler() print_ruler()
@@ -64,7 +64,7 @@ def print_map():
print() print()
def print_instructions(): def print_instructions() -> str:
print("PIZZA DELIVERY GAME") print("PIZZA DELIVERY GAME")
print() print()
print("WHAT IS YOUR FIRST NAME?") print("WHAT IS YOUR FIRST NAME?")
@@ -101,7 +101,7 @@ def yes_no_prompt(msg):
print("'YES' OR 'NO' PLEASE, NOW THEN,") print("'YES' OR 'NO' PLEASE, NOW THEN,")
def print_more_directions(player_name): def print_more_directions(player_name: str) -> None:
print() print()
print("SOMEBODY WILL ASK FOR A PIZZA TO BE") print("SOMEBODY WILL ASK FOR A PIZZA TO BE")
print("DELIVERED. THEN A DELIVERY BOY WILL") print("DELIVERED. THEN A DELIVERY BOY WILL")

View File

@@ -26,12 +26,12 @@ phrase = 1
line = "" line = ""
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def process_phrase_1(): def process_phrase_1() -> str:
global line global line
line_1_options = [ line_1_options = [
@@ -46,7 +46,7 @@ def process_phrase_1():
return line return line
def process_phrase_2(): def process_phrase_2() -> None:
global line global line
global u global u
@@ -63,7 +63,7 @@ def process_phrase_2():
u = u_modifier u = u_modifier
def process_phrase_3(): def process_phrase_3() -> None:
global line global line
phrases = [ phrases = [
@@ -79,7 +79,7 @@ def process_phrase_3():
line = line + words line = line + words
def process_phrase_4(): def process_phrase_4() -> None:
global line global line
phrases = [ phrases = [

View File

@@ -141,7 +141,7 @@ def str_with_tab(indent: int, text: str, uppercase: bool = True) -> str:
return " " * indent + text return " " * indent + text
def intro(): def intro() -> None:
"""Print the intro and print instructions if desired.""" """Print the intro and print instructions if desired."""
print(str_with_tab(33, "Queen")) print(str_with_tab(33, "Queen"))
print(str_with_tab(15, "Creative Computing Morristown, New Jersey")) print(str_with_tab(15, "Creative Computing Morristown, New Jersey"))

View File

@@ -66,7 +66,7 @@ def game_loop():
return return
def print_list(numbers): def print_list(numbers) -> None:
"""Print out the list""" """Print out the list"""
print(" ".join(map(str, numbers))) print(" ".join(map(str, numbers)))

View File

@@ -21,7 +21,7 @@ from random import random
NUMBER_OF_ROUNDS = 9 NUMBER_OF_ROUNDS = 9
def initial_message(): def initial_message() -> None:
print(" " * 28 + "Russian Roulette") print(" " * 28 + "Russian Roulette")
print(" " * 15 + "Creative Computing Morristown, New Jersey\n\n\n") print(" " * 15 + "Creative Computing Morristown, New Jersey\n\n\n")
print("This is a game of >>>>>>>>>>Russian Roulette.\n") print("This is a game of >>>>>>>>>>Russian Roulette.\n")

View File

@@ -225,7 +225,7 @@ def create_blank_board():
# #
# print out the game board for testing # print out the game board for testing
# purposes # purposes
def print_board(board): def print_board(board) -> None:
# print board header (column numbers) # print board header (column numbers)
print(" ", end="") print(" ", end="")

View File

@@ -211,7 +211,7 @@ def jump_stats(previous_jumps, chute_altitude):
return n_previous_jumps, n_better return n_previous_jumps, n_better
def print_splat(time_on_impact): def print_splat(time_on_impact) -> None:
"""Parachute opened too late!""" """Parachute opened too late!"""
print(f"{time_on_impact:.2f}\t\tSPLAT") print(f"{time_on_impact:.2f}\t\tSPLAT")
print( print(
@@ -232,7 +232,7 @@ def print_splat(time_on_impact):
) )
def print_results(n_previous_jumps, n_better): def print_results(n_previous_jumps, n_better) -> None:
"""Compare current jump to previous successful jumps.""" """Compare current jump to previous successful jumps."""
k = n_previous_jumps k = n_previous_jumps
k1 = n_better k1 = n_better
@@ -277,13 +277,13 @@ def print_results(n_previous_jumps, n_better):
) )
def print_centered(msg): def print_centered(msg: str) -> None:
"""Print centered text.""" """Print centered text."""
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(): def print_header() -> None:
print_centered("SPLAT") print_centered("SPLAT")
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print( print(

View File

@@ -28,7 +28,7 @@ MAX_NUM = 100
MAX_GUESSES = 7 MAX_GUESSES = 7
def print_instructions(): def print_instructions() -> None:
"""Instructions on how to play""" """Instructions on how to play"""
print("I am thinking of a whole number from 1 to %d" % MAX_NUM) print("I am thinking of a whole number from 1 to %d" % MAX_NUM)
print("Try to guess my number. After you guess, I") print("Try to guess my number. After you guess, I")
@@ -38,7 +38,7 @@ def print_instructions():
print("means really close! You get %d guesses." % MAX_GUESSES) print("means really close! You get %d guesses." % MAX_GUESSES)
def print_stars(secret_number, guess): def print_stars(secret_number, guess) -> None:
diff = abs(guess - secret_number) diff = abs(guess - secret_number)
stars = "" stars = ""
for i in range(8): for i in range(8):

View File

@@ -49,7 +49,7 @@ class Stock_Market:
for stock, change in zip(self.data.values(), self.changes): for stock, change in zip(self.data.values(), self.changes):
stock["Price"] = round(stock["Price"] + (change / 100) * stock["Price"], 2) stock["Price"] = round(stock["Price"] + (change / 100) * stock["Price"], 2)
def print_exchange_average(self): def print_exchange_average(self) -> None:
sum = 0 sum = 0
for stock in self.data.values(): for stock in self.data.values():
@@ -65,7 +65,7 @@ class Stock_Market:
return round(sum / 5, 2) return round(sum / 5, 2)
def print_first_day(self): def print_first_day(self) -> None:
print("\nSTOCK\t\t\t\t\tINITIALS\tPRICE/SHARE($)") print("\nSTOCK\t\t\t\t\tINITIALS\tPRICE/SHARE($)")
for stock, data in self.data.items(): for stock, data in self.data.items():
@@ -94,7 +94,7 @@ class Stock_Market:
return new_holdings return new_holdings
def print_trading_day(self): def print_trading_day(self) -> None:
print("STOCK\tPRICE/SHARE\tHOLDINGS\tNET. Value\tPRICE CHANGE") print("STOCK\tPRICE/SHARE\tHOLDINGS\tNET. Value\tPRICE CHANGE")
for stock, data, change in zip( for stock, data, change in zip(
@@ -128,7 +128,7 @@ class Stock_Market:
self.stock_assets = round(sum, 2) self.stock_assets = round(sum, 2)
def print_assets(self): def print_assets(self) -> None:
print(f"\nTOTAL STOCK ASSETS ARE: ${self.stock_assets:.2f}") print(f"\nTOTAL STOCK ASSETS ARE: ${self.stock_assets:.2f}")
print(f"TOTAL CASH ASSETS ARE: ${self.cash_assets:.2f}") print(f"TOTAL CASH ASSETS ARE: ${self.cash_assets:.2f}")
@@ -162,7 +162,7 @@ class Stock_Market:
stock["Holdings"] += new_holding stock["Holdings"] += new_holding
def print_instruction(): def print_instruction() -> None:
print( print(
""" """

View File

@@ -14,13 +14,57 @@
import random import random
from math import sqrt from math import sqrt
from typing import Any, Callable, Dict, List from typing import Any, Callable, Dict, List, Tuple
# Global variables # Global variables
restart = False restart = False
s = 0 s = 0
e = 0 e = 0
d: List[int] = [] d: List[int] = []
k: List[List[float]] = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Klingons in current quadrant
devices = [
"WARP ENGINES",
"SHORT RANGE SENSORS",
"LONG RANGE SENSORS",
"PHASER CONTROL",
"PHOTON TUBES",
"DAMAGE CONTROL",
"SHIELD CONTROL",
"LIBRARY-COMPUTER",
]
c = [
[0, 1],
[-1, 1],
[-1, 0],
[-1, -1],
[0, -1],
[1, -1],
[1, 0],
[1, 1],
[0, 1],
] # vectors in cardinal directions
q1 = s1 = 0
q2 = s2 = 0
k3 = b3 = s3 = 0 # Klingons, bases, stars in quad.
b4 = b5 = 0
qs = " " * 192 # quadrant string
# set up global game variables
g = [[0] * 8 for _ in range(8)] # galaxy map
z = [[0] * 8 for _ in range(8)] # charted galaxy map
d = [0] * 8 # damage stats for devices
t = t0 = 100 * random.randint(20, 39) # stardate (current, initial)
t9 = random.randint(25, 34) # mission duration (stardates)
docked = False # true when docked at starbase
e = e0 = 3000 # energy (current, initial)
p = p0 = 10 # torpedoes (current, initial)
s = 0 # shields
k9, b9 = 0, 0 # total Klingons, bases in galaxy
# ^ bug in original, was b9 = 2
s9 = 200 # avg. Klingon shield strength
k7 = k9 # Klingons at start of game
d4 = 0.5 * random.random() # extra delay in repairs at base
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
# Utility functions # Utility functions
@@ -84,7 +128,7 @@ def compare_marker(row, col, test_marker):
return qs[pos : (pos + 3)] == test_marker return qs[pos : (pos + 3)] == test_marker
def find_empty_place(): def find_empty_place() -> Tuple[int, int]:
# Find an empty location in the current quadrant. # Find an empty location in the current quadrant.
while True: while True:
row, col = fnr(), fnr() row, col = fnr(), fnr()
@@ -97,7 +141,7 @@ def find_empty_place():
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
def navigation(): def navigation() -> None:
# Take navigation input and move the Enterprise. # Take navigation input and move the Enterprise.
global d, s, e, k, qs, t, q1, q2, s1, s2 global d, s, e, k, qs, t, q1, q2, s1, s2
@@ -148,9 +192,9 @@ def navigation():
line = "" line = ""
for i in range(8): for i in range(8):
if d[i] < 0: if d[i] < 0:
d[i] += min(warp, 1) d[i] += min(warp, 1) # type: ignore
if -0.1 < d[i] < 0: if -0.1 < d[i] < 0:
d[i] = -0.1 d[i] = -0.1 # type: ignore
elif d[i] >= 0: elif d[i] >= 0:
if len(line) == 0: if len(line) == 0:
line = "DAMAGE CONTROL REPORT:" line = "DAMAGE CONTROL REPORT:"
@@ -175,13 +219,13 @@ def navigation():
x, y = s1, s2 x, y = s1, s2
for _ in range(n): for _ in range(n):
s1 += x1 s1 += x1 # type: ignore
s2 += x2 s2 += x2 # type: ignore
if s1 < 0 or s1 > 7 or s2 < 0 or s2 > 7: if s1 < 0 or s1 > 7 or s2 < 0 or s2 > 7:
# exceeded quadrant limits; calculate final position # exceeded quadrant limits; calculate final position
x += 8 * q1 + n * x1 x += 8 * q1 + n * x1 # type: ignore
y += 8 * q2 + n * x2 y += 8 * q2 + n * x2 # type: ignore
q1, q2 = int(x / 8), int(y / 8) q1, q2 = int(x / 8), int(y / 8)
s1, s2 = int(x - q1 * 8), int(y - q2 * 8) s1, s2 = int(x - q1 * 8), int(y - q2 * 8)
if s1 < 0: if s1 < 0:
@@ -238,7 +282,7 @@ def navigation():
insert_marker(int(s1), int(s2), "<*>") insert_marker(int(s1), int(s2), "<*>")
maneuver_energy(n) maneuver_energy(n)
t += 0.1 * int(10 * warp) if warp < 1 else 1 t += 0.1 * int(10 * warp) if warp < 1 else 1 # type: ignore
if t > t0 + t9: if t > t0 + t9:
end_game(won=False, quit=False) end_game(won=False, quit=False)
return return
@@ -259,7 +303,7 @@ def maneuver_energy(n):
s = max(0, s) s = max(0, s)
def short_range_scan(): def short_range_scan() -> None:
# Print a short range scan. # Print a short range scan.
global docked, e, p, s global docked, e, p, s
@@ -317,7 +361,7 @@ def short_range_scan():
print(sep) print(sep)
def long_range_scan(): def long_range_scan() -> None:
# Print a long range scan. # Print a long range scan.
global z, g global z, g
@@ -352,7 +396,7 @@ def print_scan_results(
print(sep) print(sep)
def phaser_control(): def phaser_control() -> None:
# Take phaser control input and fire phasers. # Take phaser control input and fire phasers.
global e, k, g, z, k3, k9 global e, k, g, z, k3, k9
@@ -384,7 +428,7 @@ def phaser_control():
e -= x e -= x
if d[7] < 0: # bug in original, was d[6] if d[7] < 0: # bug in original, was d[6]
x *= random.random() x *= random.random() # type: ignore
h1 = int(x / k3) h1 = int(x / k3)
for i in range(3): for i in range(3):
@@ -414,7 +458,7 @@ def phaser_control():
klingons_fire() klingons_fire()
def photon_torpedoes(): def photon_torpedoes() -> None:
# Take photon torpedo input and process firing of torpedoes. # Take photon torpedo input and process firing of torpedoes.
global e, p, k3, k9, k, b3, b9, docked, g, z global e, p, k3, k9, k, b3, b9, docked, g, z
@@ -445,8 +489,8 @@ def photon_torpedoes():
x3, y3 = x, y x3, y3 = x, y
print("TORPEDO TRACK:") print("TORPEDO TRACK:")
while True: while True:
x += x1 x += x1 # type: ignore
y += x2 y += x2 # type: ignore
x3, y3 = round(x), round(y) x3, y3 = round(x), round(y)
if x3 < 0 or x3 > 7 or y3 < 0 or y3 > 7: if x3 < 0 or x3 > 7 or y3 < 0 or y3 > 7:
print("TORPEDO MISSED") print("TORPEDO MISSED")
@@ -523,7 +567,7 @@ def klingons_fire():
print(f"DAMAGE CONTROL REPORTS '{devices[r1]} DAMAGED BY THE HIT'") print(f"DAMAGE CONTROL REPORTS '{devices[r1]} DAMAGED BY THE HIT'")
def shield_control(): def shield_control() -> None:
# Raise or lower the shields. # Raise or lower the shields.
global e, s global e, s
@@ -590,7 +634,7 @@ def damage_control():
t += d3 + 0.1 t += d3 + 0.1
def computer(): def computer() -> None:
# Perform the various functions of the library computer. # Perform the various functions of the library computer.
global d, z, k9, t0, t9, t, b9, s1, s2, b4, b5 global d, z, k9, t0, t9, t, b9, s1, s2, b4, b5
@@ -718,7 +762,7 @@ def computer():
) )
def print_direction(from1, from2, to1, to2): def print_direction(from1, from2, to1, to2) -> None:
# Print direction and distance between two locations in the grid. # Print direction and distance between two locations in the grid.
delta1 = -(to1 - from1) # flip so positive is up (heading = 3) delta1 = -(to1 - from1) # flip so positive is up (heading = 3)
delta2 = to2 - from2 delta2 = to2 - from2
@@ -752,7 +796,7 @@ def print_direction(from1, from2, to1, to2):
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
def startup(): def startup() -> None:
# Initialize the game variables and map, and print startup messages. # Initialize the game variables and map, and print startup messages.
global g, z, d, t, t0, t9, docked, e, e0, p, p0, s, k9, b9, s9, c global g, z, d, t, t0, t9, docked, e, e0, p, p0, s, k9, b9, s9, c
global devices, q1, q2, s1, s2, k7 global devices, q1, q2, s1, s2, k7
@@ -850,7 +894,7 @@ def startup():
) )
def new_quadrant(): def new_quadrant() -> None:
# Enter a new quadrant: populate map and print a short range scan. # Enter a new quadrant: populate map and print a short range scan.
global z, k3, b3, s3, d4, k, qs, b4, b5 global z, k3, b3, s3, d4, k, qs, b4, b5
@@ -894,7 +938,9 @@ def new_quadrant():
short_range_scan() short_range_scan()
def end_game(won=False, quit=True, enterprise_killed=False): def end_game(
won: bool = False, quit: bool = True, enterprise_killed: bool = False
) -> None:
# Handle end-of-game situations. # Handle end-of-game situations.
global restart global restart

View File

@@ -13,7 +13,7 @@ def get_yes_no(prompt):
return response[0] != "N" return response[0] != "N"
def print_header(): def print_header() -> None:
for _ in range(12): for _ in range(12):
print() print()
t10 = " " * 10 t10 = " " * 10
@@ -28,7 +28,7 @@ def print_header():
print() print()
def print_instructions(): def print_instructions() -> None:
# Back in the 70s, at this point, the user would be prompted to # Back in the 70s, at this point, the user would be prompted to
# turn on their (printing) TTY to capture the output to hard copy. # turn on their (printing) TTY to capture the output to hard copy.

View File

@@ -0,0 +1,11 @@
import io
import pytest
from superstartrek import main
def test_main(monkeypatch, capsys):
monkeypatch.setattr("sys.stdin", io.StringIO("NAV\n1\n1\nSRS\nXXX\nXXX\n"))
with pytest.raises(SystemExit):
main()
# captured = capsys.readouterr()

View File

@@ -11,12 +11,12 @@ import random
PAGE_WIDTH = 64 PAGE_WIDTH = 64
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -24,7 +24,7 @@ def print_header(title):
print() print()
def print_instructions(): def print_instructions() -> None:
print("A SYNONYM OF A WORD MEANS ANOTHER WORD IN THE ENGLISH") print("A SYNONYM OF A WORD MEANS ANOTHER WORD IN THE ENGLISH")
print("LANGUAGE WHICH HAS THE SAME OR VERY NEARLY THE SAME MEANING.") print("LANGUAGE WHICH HAS THE SAME OR VERY NEARLY THE SAME MEANING.")
print("I CHOOSE A WORD -- YOU TYPE A SYNONYM.") print("I CHOOSE A WORD -- YOU TYPE A SYNONYM.")
@@ -49,7 +49,7 @@ synonym_words = [
] ]
def print_right(): def print_right() -> None:
print(random.choice(right_words)) print(random.choice(right_words))

View File

@@ -12,12 +12,12 @@ import random
PAGE_WIDTH = 64 PAGE_WIDTH = 64
def print_centered(msg): def print_centered(msg: str) -> None:
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2) spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg) print(spaces + msg)
def print_header(title): def print_header(title: str) -> None:
print_centered(title) print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
@@ -25,7 +25,7 @@ def print_header(title):
print() print()
def print_instructions(): def print_instructions() -> None:
print("YOU ARE THE WEAPONS OFFICER ON THE STARSHIP ENTERPRISE") print("YOU ARE THE WEAPONS OFFICER ON THE STARSHIP ENTERPRISE")
print("AND THIS IS A TEST TO SEE HOW ACCURATE A SHOT YOU") print("AND THIS IS A TEST TO SEE HOW ACCURATE A SHOT YOU")
print("ARE IN A THREE-DIMENSIONAL RANGE. YOU WILL BE TOLD") print("ARE IN A THREE-DIMENSIONAL RANGE. YOU WILL BE TOLD")

View File

@@ -165,7 +165,7 @@ class TicTacToe:
return c1 - gap + i, c2 + gap return c1 - gap + i, c2 + gap
def display(Game: TicTacToe): def display(Game: TicTacToe) -> None:
line1 = "" line1 = ""
for i in range(0, Game.dim_sz): for i in range(0, Game.dim_sz):
for j in range(0, Game.dim_sz - 1): for j in range(0, Game.dim_sz - 1):
@@ -181,7 +181,7 @@ def display(Game: TicTacToe):
print(line1, "\n\n") print(line1, "\n\n")
def play(): def play() -> None:
Pick = input("Pick 'X' or 'O' ").strip().upper() Pick = input("Pick 'X' or 'O' ").strip().upper()
if Pick == "O": if Pick == "O":
Game = TicTacToe("O") Game = TicTacToe("O")

View File

@@ -8,7 +8,7 @@ class Disk:
def size(self): def size(self):
return self.__size return self.__size
def print(self): def print(self) -> None:
print("[ %s ]" % self.size()) print("[ %s ]" % self.size())
@@ -39,7 +39,7 @@ class Tower:
raise Exception("empty pop") raise Exception("empty pop")
return self.__disks.pop() return self.__disks.pop()
def print(self): def print(self) -> None:
r = "Needle: [%s]" % (", ".join([str(x.size()) for x in self.__disks])) r = "Needle: [%s]" % (", ".join([str(x.size()) for x in self.__disks]))
print(r) print(r)
@@ -63,7 +63,7 @@ class Game:
def winner(self): def winner(self):
return self.__towers[0].empty() and self.__towers[1].empty() return self.__towers[0].empty() and self.__towers[1].empty()
def print(self): def print(self) -> None:
for t in self.__towers: for t in self.__towers:
t.print() t.print()

View File

@@ -16,7 +16,7 @@ import datetime
GET_TODAY_FROM_SYSTEM = True GET_TODAY_FROM_SYSTEM = True
def print_with_tab(space_count, s): def print_with_tab(space_count: int, s: str) -> None:
if space_count > 0: if space_count > 0:
spaces = " " * space_count spaces = " " * space_count
else: else: