Python: Add type annotations

This commit is contained in:
Martin Thoma
2022-03-19 22:10:26 +01:00
committed by Alexander Wunschik
parent b95a514e84
commit 83b3dc402c
79 changed files with 509 additions and 461 deletions

View File

@@ -2,4 +2,5 @@ pytest
flake8
flake8-bugbear
flake8-comprehensions
flake8_implicit_str_concat
mypy

View File

@@ -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")

View File

@@ -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)

View File

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

View File

@@ -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()

View File

@@ -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")

View File

@@ -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")

View File

@@ -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

View File

@@ -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()

View File

@@ -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()

View File

@@ -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)

View File

@@ -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)

View File

@@ -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}"

View File

@@ -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()

View File

@@ -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()

View File

@@ -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()

View File

@@ -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:

View File

@@ -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)},

View File

@@ -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,29 +79,40 @@ 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:
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:
elif A < 2:
print("GOOD LUCK. YOU'LL NEED IT.")
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:
print()
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:
@@ -140,7 +151,7 @@ while True:
elif E < 3:
break
if E == 0:
M = 3
M: Union[int, float] = 3
elif E == 1:
M = 2
else:
@@ -215,8 +226,6 @@ while True:
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:

View File

@@ -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)

View File

@@ -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

View File

@@ -23,7 +23,7 @@
import random
def main():
def main() -> None:
WORDS = [
[
"Ability",

View File

@@ -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)

View File

@@ -100,7 +100,7 @@ def print_thanks():
print()
def main():
def main() -> None:
print_header("CHANGE")
print_introduction()

View File

@@ -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()

View File

@@ -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()

View File

@@ -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)")

View File

@@ -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()

View File

@@ -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()

View File

@@ -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")

View File

@@ -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()

View File

@@ -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).

View File

@@ -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

View File

@@ -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()

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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")

View File

@@ -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()

View File

@@ -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()

View File

@@ -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()

View File

@@ -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()

View File

@@ -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()

View File

@@ -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()

View File

@@ -48,7 +48,7 @@ def get_pattern():
c += 1
def main():
def main() -> None:
print_header("LIFE")
pattern = get_pattern()

View File

@@ -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()

View File

@@ -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")

View File

@@ -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:

View File

@@ -46,7 +46,7 @@ def print_dice(n):
print(" ----- ")
def main():
def main() -> None:
while True:
d1 = randint(1, 6)

View File

@@ -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()

View File

@@ -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()

View File

@@ -70,7 +70,7 @@ class NIM:
return sum == 0
def main():
def main() -> None:
# Game initialization
game = NIM()

View File

@@ -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")

View File

@@ -7,7 +7,7 @@ def tab(x):
return " " * x
def main():
def main() -> None:
# Initial instructions
print(tab(30) + "ONE CHECK")

View File

@@ -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()

View File

@@ -150,7 +150,7 @@ def play_game(num_turns, player_name):
break
def main():
def main() -> None:
print_header("PIZZA")
player_name = print_instructions()

View File

@@ -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()

View File

@@ -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")

View File

@@ -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")

View File

@@ -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

View File

@@ -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

View File

@@ -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"

View File

@@ -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))

View File

@@ -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

View File

@@ -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:

View File

@@ -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")

View File

@@ -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,

View File

@@ -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

View File

@@ -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()

View File

@@ -160,7 +160,7 @@ def play_game():
next_target()
def main():
def main() -> None:
print_header("TARGET")
print_instructions()

View File

@@ -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")

View File

@@ -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.

View File

@@ -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")

View File

@@ -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"):

View File

@@ -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")

View File

@@ -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-#")

View File

@@ -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()

View File

@@ -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")