Simplify Python Code

print_with_tab / print_with_whitespace is trivial with Python
string formatting and was mostly used in only 2 lines.
This commit is contained in:
Martin Thoma
2022-04-02 07:32:09 +02:00
parent 354c1f9ab3
commit c500424956
47 changed files with 208 additions and 387 deletions

View File

@@ -24,7 +24,6 @@ cards = {
def play_game() -> None: def play_game() -> None:
"""Play the game"""
cash = 100 cash = 100
while cash > 0: while cash > 0:
print(f"You now have {cash} dollars\n") print(f"You now have {cash} dollars\n")
@@ -64,16 +63,6 @@ def play_game() -> None:
def main() -> None: def main() -> None:
"""Main"""
keep_playing = True
while keep_playing:
play_game()
keep_playing = input("Try again? (yes or no) ").lower().startswith("y")
print("Ok hope you had fun")
if __name__ == "__main__":
print( print(
""" """
Acey-Ducey is played in the following manner Acey-Ducey is played in the following manner
@@ -84,4 +73,13 @@ a value between the first two.
If you do not want to bet, input a 0 If you do not want to bet, input a 0
""" """
) )
keep_playing = True
while keep_playing:
play_game()
keep_playing = input("Try again? (yes or no) ").lower().startswith("y")
print("Ok hope you had fun")
if __name__ == "__main__":
main() main()

View File

@@ -1,7 +1,7 @@
import random
import enum import enum
from typing import List, Tuple import random
from dataclasses import dataclass from dataclasses import dataclass
from typing import List, Tuple
# Python translation by Frank Palazzolo - 2/2021 # Python translation by Frank Palazzolo - 2/2021
@@ -77,18 +77,15 @@ EXIT_RIGHT = 2
def main() -> None: def main() -> None:
welcome_header() print_intro()
width, length = get_maze_dimensions() width, length = get_maze_dimensions()
maze = build_maze(width, length) maze = build_maze(width, length)
maze.display() maze.display()
def welcome_header() -> None: def print_intro() -> None:
print(" " * 28 + "AMAZING PROGRAM") print(" " * 28 + "AMAZING PROGRAM")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
def build_maze(width: int, length: int) -> Maze: def build_maze(width: int, length: int) -> Maze:

View File

@@ -119,7 +119,7 @@ def avoid_void_input(message: str) -> str:
return answer return answer
def initial_message() -> None: def print_intro() -> None:
print(" " * 32 + "Animal") print(" " * 32 + "Animal")
print(" " * 15 + "Creative Computing Morristown, New Jersey\n") print(" " * 15 + "Creative Computing Morristown, New Jersey\n")
print("Play ´Guess the Animal´") print("Play ´Guess the Animal´")
@@ -133,7 +133,7 @@ def main() -> None:
root = Node("Does it swim?", yes_child, no_child) root = Node("Does it swim?", yes_child, no_child)
# Main loop of game # Main loop of game
initial_message() print_intro()
keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y" keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y"
while keep_playing: while keep_playing:
keep_asking = True keep_asking = True

View File

@@ -81,14 +81,6 @@ MAX_HISTORY = 9
LOSING_BOOK_SIZE = 50 LOSING_BOOK_SIZE = 50
def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + msg)
def draw_pit(line: str, board, pit_index) -> str: def draw_pit(line: str, board, pit_index) -> str:
val = board[pit_index] val = board[pit_index]
line = line + " " line = line + " "
@@ -362,10 +354,8 @@ def player_move(board) -> Tuple[int, bool, int]:
def main() -> None: def main() -> None:
print_with_tab(34, "AWARI") print(" " * 34 + "AWARI")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n")
print()
print()
board = [0] * 14 # clear the board representation board = [0] * 14 # clear the board representation
global losing_book global losing_book

View File

@@ -106,8 +106,7 @@ def build_result_string(num: List[str], guess: str) -> str:
def main() -> None: def main() -> None:
# Intro text # Intro text
print("\n Bagels") print("\n Bagels")
print("Creative Computing Morristown, New Jersey") print("Creative Computing Morristown, New Jersey\n\n")
print("\n\n")
# Anything other than N* will show the rules # Anything other than N* will show the rules
response = input("Would you like the rules (Yes or No)? ") response = input("Would you like the rules (Yes or No)? ")

View File

@@ -9,7 +9,7 @@ import random
from typing import List, Literal, Optional from typing import List, Literal, Optional
def explain_keyboard_inputs() -> None: def print_intro() -> None:
print("\t\t\t Basketball") print("\t\t\t Basketball")
print("\t Creative Computing Morristown, New Jersey\n\n\n") print("\t Creative Computing Morristown, New Jersey\n\n\n")
print("This is Dartmouth College basketball. ") print("This is Dartmouth College basketball. ")
@@ -35,7 +35,7 @@ class Basketball:
self.shot_choices: List[Literal[0, 1, 2, 3, 4]] = [0, 1, 2, 3, 4] self.shot_choices: List[Literal[0, 1, 2, 3, 4]] = [0, 1, 2, 3, 4]
self.z1: Optional[float] = None self.z1: Optional[float] = None
explain_keyboard_inputs() print_intro()
self.defense = get_defense_choice(self.defense_choices) self.defense = get_defense_choice(self.defense_choices)
@@ -154,7 +154,7 @@ class Basketball:
# ball is passed back to you # ball is passed back to you
self.ball_passed_back() self.ball_passed_back()
else: else:
print("") print()
self.dartmouth_non_jump_shot() self.dartmouth_non_jump_shot()
else: else:
print("Shot is good.") print("Shot is good.")
@@ -268,7 +268,7 @@ class Basketball:
self.opponent_ball() self.opponent_ball()
else: else:
if random.random() > 0.5: if random.random() > 0.5:
print("") print()
self.opponent_non_jumpshot() self.opponent_non_jumpshot()
else: else:
print("Pass back to " + self.opponent + " guard.\n") print("Pass back to " + self.opponent + " guard.\n")
@@ -304,14 +304,14 @@ class Basketball:
self.opponent_ball() self.opponent_ball()
else: else:
if random.random() > 0.5: if random.random() > 0.5:
print("") print()
self.opponent_non_jumpshot() self.opponent_non_jumpshot()
else: else:
print("Pass back to " + self.opponent + " guard.\n") print("Pass back to " + self.opponent + " guard.\n")
self.opponent_ball() self.opponent_ball()
else: else:
if random.random() > 0.5: if random.random() > 0.5:
print("") print()
self.opponent_non_jumpshot() self.opponent_non_jumpshot()
else: else:
print("Pass back to " + self.opponent + " guard\n") print("Pass back to " + self.opponent + " guard\n")

View File

@@ -242,7 +242,7 @@ class Game:
players.append(Player.new(PlayerType.Player, i)) players.append(Player.new(PlayerType.Player, i))
if get_char_from_user_input("Do you want instructions", ["y", "n"]) == "y": if get_char_from_user_input("Do you want instructions", ["y", "n"]) == "y":
instructions() print_instructions()
print() print()
return Game(players=players, decks=Decks.new(), games_played=0) return Game(players=players, decks=Decks.new(), games_played=0)
@@ -284,7 +284,7 @@ class Game:
# turn loop, ends when player finishes their turn # turn loop, ends when player finishes their turn
while True: while True:
clear() clear()
welcome() print_welcome_screen()
print(f"\n\t\t\tGame {game}") print(f"\n\t\t\tGame {game}")
print(scores) print(scores)
print(player_hands_message) print(player_hands_message)
@@ -407,7 +407,7 @@ STARTING_BALANCE: int = 100
def main() -> None: def main() -> None:
game: Game game: Game
welcome() print_welcome_screen()
# create game # create game
game = Game.new( game = Game.new(
@@ -421,9 +421,7 @@ def main() -> None:
char = get_char_from_user_input("Play Again?", ["y", "n"]) char = get_char_from_user_input("Play Again?", ["y", "n"])
def welcome() -> None: def print_welcome_screen() -> None:
"""prints the welcome screen"""
# welcome message
print( print(
""" """
BLACK JACK BLACK JACK
@@ -432,8 +430,7 @@ def welcome() -> None:
) )
def instructions() -> None: def print_instructions() -> None:
"""prints the instructions"""
print( print(
""" """
THIS IS THE GAME OF 21. AS MANY AS 7 PLAYERS MAY PLAY THE THIS IS THE GAME OF 21. AS MANY AS 7 PLAYERS MAY PLAY THE

View File

@@ -4,9 +4,9 @@ from functools import partial
from typing import Callable, List, Set from typing import Callable, List, Set
def display_intro() -> None: def print_intro() -> None:
print("" * 33 + "BOMBARDMENT") print(" " * 33 + "BOMBARDMENT")
print("" * 15 + " CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + " CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n") print("\n\n")
print("YOU ARE ON A BATTLEFIELD WITH 4 PLATOONS AND YOU") print("YOU ARE ON A BATTLEFIELD WITH 4 PLATOONS AND YOU")
print("HAVE 25 OUTPOSTS AVAILABLE WHERE THEY MAY BE PLACED.") print("HAVE 25 OUTPOSTS AVAILABLE WHERE THEY MAY BE PLACED.")
@@ -28,7 +28,6 @@ def display_field() -> None:
for row in range(5): for row in range(5):
initial = row * 5 + 1 initial = row * 5 + 1
print("\t".join([str(initial + column) for column in range(5)])) print("\t".join([str(initial + column) for column in range(5)]))
print("\n" * 9) print("\n" * 9)
@@ -128,8 +127,8 @@ ENEMY_PROGRESS_MESSAGES = (
) )
def play() -> None: def main() -> None:
display_intro() print_intro()
display_field() display_field()
enemy_positions = generate_enemy_positions() enemy_positions = generate_enemy_positions()
@@ -162,4 +161,4 @@ def play() -> None:
if __name__ == "__main__": if __name__ == "__main__":
play() main()

View File

@@ -77,7 +77,7 @@ def read_punch_profiles(filepath: Path) -> Dict[Literal[1, 2, 3, 4], PunchProfil
return result # type: ignore return result # type: ignore
def play() -> None: def main() -> None:
print("BOXING") print("BOXING")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n") print("\n\n")
@@ -179,4 +179,4 @@ def play_round(round_number: int, player: Player, opponent: Player) -> None:
if __name__ == "__main__": if __name__ == "__main__":
play() main()

View File

@@ -36,10 +36,6 @@ class State:
print_legs(self.legs) print_legs(self.legs)
def print_n_whitespaces(n: int) -> None:
print(" " * n, end="")
def print_n_newlines(n: int) -> None: def print_n_newlines(n: int) -> None:
for _ in range(n): for _ in range(n):
print() print()
@@ -47,7 +43,7 @@ def print_n_newlines(n: int) -> None:
def print_feelers(n_feelers: int, is_player: bool = True) -> None: def print_feelers(n_feelers: int, is_player: bool = True) -> None:
for _ in range(4): for _ in range(4):
print_n_whitespaces(10) print(" " * 10, end="")
for _ in range(n_feelers): for _ in range(n_feelers):
print("A " if is_player else "F ", end="") print("A " if is_player else "F ", end="")
print() print()
@@ -77,7 +73,7 @@ def print_body(has_tail: bool = False) -> None:
def print_legs(n_legs: int) -> None: def print_legs(n_legs: int) -> None:
for _ in range(2): for _ in range(2):
print_n_whitespaces(5) print(" " * 5, end="")
for _ in range(n_legs): for _ in range(n_legs):
print(" L", end="") print(" L", end="")
print() print()
@@ -156,10 +152,8 @@ def handle_roll(diceroll: Literal[1, 2, 3, 4, 5, 6], state: State) -> bool:
def main() -> None: def main() -> None:
print_n_whitespaces(34) print(" " * 34 + "BUG")
print("BUG") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_whitespaces(15)
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(3) print_n_newlines(3)
print("THE GAME BUG") print("THE GAME BUG")

View File

@@ -3,10 +3,6 @@ import random
from typing import Dict, List, Literal, Tuple, Union from typing import Dict, List, Literal, Tuple, Union
def print_n_whitespaces(n: int) -> None:
print(" " * n, end="")
def print_n_newlines(n: int) -> None: def print_n_newlines(n: int) -> None:
for _ in range(n): for _ in range(n):
print() print()
@@ -73,10 +69,8 @@ def calculate_final_score(
def print_header() -> None: def print_header() -> None:
print_n_whitespaces(34) print(" " * 34 + "BULL")
print("BULL") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_whitespaces(15)
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_n_newlines(2) print_n_newlines(2)

View File

@@ -8,20 +8,14 @@ with open("data.json") as f:
DATA = tuple(json.load(f)) DATA = tuple(json.load(f))
def display_intro() -> None: def print_intro() -> None:
print(tab(33) + "BUNNY") print(" " * 33 + "BUNNY")
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n") print("\n\n")
def tab(column: int) -> str: def main() -> None:
"""Emulates the TAB command in BASIC. Returns a string with ASCII print_intro()
codes for setting the cursor to the specified column."""
return f"\r\33[{column}C"
def play() -> None:
display_intro()
# Using an iterator will give us a similar interface to BASIC's READ # Using an iterator will give us a similar interface to BASIC's READ
# command. Instead of READ, we will call 'next(data)' to fetch the next element. # command. Instead of READ, we will call 'next(data)' to fetch the next element.
@@ -55,7 +49,7 @@ def play() -> None:
# position of a line segment. # position of a line segment.
start = command start = command
# Position cursor at start # Position cursor at start
print(tab(start), end="") print(" " * start, end="")
# The following number, indicates the end of the segment. # The following number, indicates the end of the segment.
end = next(data) end = next(data)
@@ -67,4 +61,4 @@ def play() -> None:
if __name__ == "__main__": if __name__ == "__main__":
play() main()

View File

@@ -91,7 +91,7 @@ def main() -> None:
phrase += section[random.randint(0, len(section) - 1)] phrase += section[random.randint(0, len(section) - 1)]
print(phrase) print(phrase)
print("") print()
response = input("? ") response = input("? ")
try: try:

View File

@@ -88,17 +88,13 @@ def compute_change() -> None:
print(f"{change_in_pennies} PENNY(S)") print(f"{change_in_pennies} PENNY(S)")
def print_thanks() -> None:
print("THANK YOU, COME AGAIN.\n\n")
def main() -> None: def main() -> None:
print_header("CHANGE") print_header("CHANGE")
print_introduction() print_introduction()
while True: while True:
compute_change() compute_change()
print_thanks() print("THANK YOU, COME AGAIN.\n\n")
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -11,15 +11,6 @@ import random
MAX_LIVES = 9 MAX_LIVES = 9
def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + msg)
def play_scenario() -> bool: def play_scenario() -> bool:
acid_amount = random.randint(1, 50) acid_amount = random.randint(1, 50)
@@ -58,8 +49,8 @@ def show_ending() -> None:
def main() -> None: def main() -> None:
print_with_tab(33, "CHEMIST") print(" " * 33 + "CHEMIST")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print("THE FICTITIOUS CHEMICAL KRYPTOCYANIC ACID CAN ONLY BE") print("THE FICTITIOUS CHEMICAL KRYPTOCYANIC ACID CAN ONLY BE")
print("DILUTED BY THE RATIO OF 7 PARTS WATER TO 3 PARTS ACID.") print("DILUTED BY THE RATIO OF 7 PARTS WATER TO 3 PARTS ACID.")

View File

@@ -69,9 +69,9 @@ def play_game():
player = 0 player = 0
alive = True alive = True
while alive: while alive:
print("") print()
print(cookie.render()) print(cookie.render())
print("") print()
player += 1 player += 1
if player > players: if player > players:
player = 1 player = 1

View File

@@ -1,11 +1,11 @@
"""
Original game design: Cram, Goodie, Hibbard Lexington H.S.
Modifications: G. Paul, R. Hess (Ties), 1973
"""
import math import math
from typing import List from typing import List
def tab(n: int) -> str:
return " " * n
def get_choice(prompt: str, choices: List[str]) -> str: def get_choice(prompt: str, choices: List[str]) -> str:
while True: while True:
choice = input(prompt) choice = input(prompt)
@@ -96,13 +96,9 @@ def main():
salaries = {} salaries = {}
ammunition = {} ammunition = {}
oa = {} oa = {}
print(tab(26) + "CIVIL WAR") print(" " * 26 + "CIVIL WAR")
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
# Original game design: Cram, Goodie, Hibbard Lexington H.S.
# Modifications: G. Paul, R. Hess (Ties), 1973
# Union info on likely confederate strategy # Union info on likely confederate strategy
sa[1] = 25 sa[1] = 25
sa[2] = 25 sa[2] = 25

View File

@@ -116,7 +116,7 @@ def attack_second() -> None:
num_units = 0 num_units = 0
unit_type = 0 unit_type = 0
print("") print()
print(" YOU ME") print(" YOU ME")
print("ARMY ", end="") print("ARMY ", end="")
print("%-14s%s\n" % (usr_army, cpu_army), end="") print("%-14s%s\n" % (usr_army, cpu_army), end="")
@@ -176,7 +176,7 @@ def attack_second() -> None:
plane_crash_win = True plane_crash_win = True
if not plane_crash_win: if not plane_crash_win:
print("") print()
print("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,") print("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,")
if plane_crash_win or ( if plane_crash_win or (

View File

@@ -20,10 +20,7 @@ def throw_dice() -> int:
def main() -> None: def main() -> None:
print(" " * 33 + "Craps") print(" " * 33 + "Craps")
print(" " * 15 + "Creative Computing Morristown, New Jersey") print(" " * 15 + "Creative Computing Morristown, New Jersey\n\n\n")
print()
print()
print()
winnings = 0 winnings = 0
print("2,3,12 are losers; 4,5,6,8,9,10 are points; 7,11 are natural winners.") print("2,3,12 are losers; 4,5,6,8,9,10 are points; 7,11 are natural winners.")

View File

@@ -1,7 +1,9 @@
# Original BASIC version as published in Basic Computer Games (1978) """
# https://www.atariarchives.org/basicgames/showpage.php?page=55 Original BASIC version as published in Basic Computer Games (1978)
# https://www.atariarchives.org/basicgames/showpage.php?page=55
# Converted to Python by Anson VanDoren in 2021
Converted to Python by Anson VanDoren in 2021
"""
import math import math
import random import random
@@ -38,7 +40,7 @@ def get_num_charges() -> Tuple[int, int]:
def ask_for_new_game() -> None: def ask_for_new_game() -> None:
answer = input("Another game (Y or N): ") answer = input("Another game (Y or N): ")
if answer.lower().strip()[0] == "y": if answer.lower().strip()[0] == "y":
start_new_game() main()
else: else:
print("OK. Hope you enjoyed yourself") print("OK. Hope you enjoyed yourself")
exit() exit()
@@ -112,10 +114,10 @@ def play_game(search_area, num_charges):
ask_for_new_game() ask_for_new_game()
def start_new_game() -> None: def main() -> None:
search_area, num_charges = get_num_charges() search_area, num_charges = get_num_charges()
play_game(search_area, num_charges) play_game(search_area, num_charges)
if __name__ == "__main__": if __name__ == "__main__":
start_new_game() main()

View File

@@ -7,14 +7,6 @@ Ported by Dave LeCompte
""" """
def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + msg)
def print_diamond(begin_width, end_width, step, width, count) -> None: def print_diamond(begin_width, end_width, step, width, count) -> None:
edgeString = "CC" edgeString = "CC"
fill = "!" fill = "!"
@@ -38,11 +30,8 @@ def print_diamond(begin_width, end_width, step, width, count) -> None:
def main() -> None: def main() -> None:
print_with_tab(33, "DIAMOND") print(" " * 33, "DIAMOND")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
print("FOR A PRETTY DIAMOND PATTERN,") print("FOR A PRETTY DIAMOND PATTERN,")
print("TYPE IN AN ODD NUMBER BETWEEN 5 AND 21") print("TYPE IN AN ODD NUMBER BETWEEN 5 AND 21")
width = int(input()) width = int(input())

View File

@@ -48,7 +48,7 @@ def main() -> None:
still_playing = True still_playing = True
while still_playing: while still_playing:
print("") print()
n = int(input("How many rolls? ")) n = int(input("How many rolls? "))
# Roll the dice n times # Roll the dice n times
@@ -64,7 +64,7 @@ def main() -> None:
print(" %-14d%d" % (i, freq[i])) print(" %-14d%d" % (i, freq[i]))
# Keep playing? # Keep playing?
print("") print()
response = input("Try again? ") response = input("Try again? ")
if len(response) > 0 and response.upper()[0] == "Y": if len(response) > 0 and response.upper()[0] == "Y":
# Clear out the frequency list # Clear out the frequency list

View File

@@ -35,7 +35,7 @@ def serious_error(msg):
exit(1) exit(1)
def welcome_screen(): def print_intro():
print("Welcome to Even Wins!") print("Welcome to Even Wins!")
print("Based on evenwins.bas from Creative Computing") print("Based on evenwins.bas from Creative Computing")
print() print()
@@ -149,7 +149,7 @@ def game_over():
print("You are the winner! Congratulations!") print("You are the winner! Congratulations!")
else: else:
print("The computer wins: all hail mighty silicon!") print("The computer wins: all hail mighty silicon!")
print("") print()
def computer_turn(): def computer_turn():
@@ -211,7 +211,7 @@ def play_game():
def main() -> None: def main() -> None:
global whose_turn global whose_turn
welcome_screen() print_intro()
while True: while True:
choose_first_player() choose_first_player()

View File

@@ -22,12 +22,6 @@ 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) -> None:
"""Print the words at the specified column"""
spaces = " " * column # make a fat string of spaces
print(spaces + words)
def show_introduction() -> None: def show_introduction() -> None:
"""Show the player the introductory message""" """Show the player the introductory message"""
print("YOU ARE THE LEADER OF A FRENCH FUR TRADING EXPEDITION IN ") print("YOU ARE THE LEADER OF A FRENCH FUR TRADING EXPEDITION IN ")
@@ -36,7 +30,7 @@ def show_introduction() -> None:
print("FORTS AT WHICH YOU MAY TRADE. THE COST OF SUPPLIES") print("FORTS AT WHICH YOU MAY TRADE. THE COST OF SUPPLIES")
print("AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND") print("AND THE AMOUNT YOU RECEIVE FOR YOUR FURS WILL DEPEND")
print("ON THE FORT THAT YOU CHOOSE.") print("ON THE FORT THAT YOU CHOOSE.")
print("") print()
def get_fort_choice() -> int: def get_fort_choice() -> int:
@@ -45,7 +39,7 @@ def get_fort_choice() -> int:
prompting the user.""" prompting the user."""
result = 0 result = 0
while result == 0: while result == 0:
print("") print()
print("YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2,") print("YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2,")
print("OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)") print("OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)")
print("AND IS UNDER THE PROTECTION OF THE FRENCH ARMY.") print("AND IS UNDER THE PROTECTION OF THE FRENCH ARMY.")
@@ -70,7 +64,7 @@ def get_fort_choice() -> int:
def show_fort_comment(which_fort): def show_fort_comment(which_fort):
"""Print the description for the fort""" """Print the description for the fort"""
print("") print()
if which_fort == FORT_MONTREAL: if which_fort == FORT_MONTREAL:
print("YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT") print("YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT")
print("IS FAR FROM ANY SEAPORT. THE VALUE") print("IS FAR FROM ANY SEAPORT. THE VALUE")
@@ -89,7 +83,7 @@ def show_fort_comment(which_fort):
else: else:
print("Internal error #1, fort " + str(which_fort) + " does not exist") print("Internal error #1, fort " + str(which_fort) + " does not exist")
sys.exit(1) # you have a bug sys.exit(1) # you have a bug
print("") print()
def get_yes_or_no(): def get_yes_or_no():
@@ -116,7 +110,7 @@ def get_furs_purchase():
print("YOUR " + str(MAX_FURS) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING") print("YOUR " + str(MAX_FURS) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING")
print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.") print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.")
print("") print()
for i in range(len(FUR_NAMES)): for i in range(len(FUR_NAMES)):
print("HOW MANY " + FUR_NAMES[i] + " DO YOU HAVE") print("HOW MANY " + FUR_NAMES[i] + " DO YOU HAVE")
@@ -130,11 +124,10 @@ def get_furs_purchase():
return results return results
if __name__ == "__main__": def main():
print(" " * 31 + "FUR TRADER")
print_at_column(31, "FUR TRADER") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print_at_column(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "(Ported to Python Oct 2012 krt@krt.com.au)")
print_at_column(15, "(Ported to Python Oct 2012 krt@krt.com.au)")
print("\n\n\n") print("\n\n\n")
game_state = "starting" game_state = "starting"
@@ -155,13 +148,13 @@ if __name__ == "__main__":
game_state = "trading" game_state = "trading"
elif game_state == "trading": elif game_state == "trading":
print("") print()
print("YOU HAVE $ %1.2f IN SAVINGS" % (player_funds)) print("YOU HAVE $ %1.2f IN SAVINGS" % (player_funds))
print("AND " + str(MAX_FURS) + " FURS TO BEGIN THE EXPEDITION") print("AND " + str(MAX_FURS) + " FURS TO BEGIN THE EXPEDITION")
player_furs = get_furs_purchase() player_furs = get_furs_purchase()
if sum(player_furs) > MAX_FURS: if sum(player_furs) > MAX_FURS:
print("") print()
print("YOU MAY NOT HAVE THAT MANY FURS.") print("YOU MAY NOT HAVE THAT MANY FURS.")
print("DO NOT TRY TO CHEAT. I CAN ADD.") print("DO NOT TRY TO CHEAT. I CAN ADD.")
print("YOU MUST START AGAIN.") print("YOU MUST START AGAIN.")
@@ -178,7 +171,7 @@ if __name__ == "__main__":
game_state = "travelling" game_state = "travelling"
elif game_state == "travelling": elif game_state == "travelling":
print("") print()
if which_fort == FORT_MONTREAL: if which_fort == FORT_MONTREAL:
mink_price = ( mink_price = (
int((0.2 * random.random() + 0.70) * 100 + 0.5) / 100 int((0.2 * random.random() + 0.70) * 100 + 0.5) / 100
@@ -234,7 +227,7 @@ if __name__ == "__main__":
) )
sys.exit(1) # you have a bug sys.exit(1) # you have a bug
print("") print()
print("SUPPLIES AT FORT STADACONA COST $125.00.") print("SUPPLIES AT FORT STADACONA COST $125.00.")
print("YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00.") print("YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00.")
player_funds -= 140 player_funds -= 140
@@ -281,7 +274,7 @@ if __name__ == "__main__":
) )
sys.exit(1) # you have a bug sys.exit(1) # you have a bug
print("") print()
print("SUPPLIES AT NEW YORK COST $85.00.") print("SUPPLIES AT NEW YORK COST $85.00.")
print("YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00.") print("YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00.")
player_funds -= 105 player_funds -= 105
@@ -296,7 +289,7 @@ if __name__ == "__main__":
ermine_value = ermine_price * player_furs[FUR_ERMINE] ermine_value = ermine_price * player_furs[FUR_ERMINE]
mink_value = mink_price * player_furs[FUR_MINK] mink_value = mink_price * player_furs[FUR_MINK]
print("") print()
print("YOUR BEAVER SOLD FOR $%6.2f" % (beaver_value)) print("YOUR BEAVER SOLD FOR $%6.2f" % (beaver_value))
print("YOUR FOX SOLD FOR $%6.2f" % (fox_value)) print("YOUR FOX SOLD FOR $%6.2f" % (fox_value))
print("YOUR ERMINE SOLD FOR $%6.2f" % (ermine_value)) print("YOUR ERMINE SOLD FOR $%6.2f" % (ermine_value))
@@ -304,15 +297,19 @@ if __name__ == "__main__":
player_funds += beaver_value + fox_value + ermine_value + mink_value player_funds += beaver_value + fox_value + ermine_value + mink_value
print("") print()
print( print(
"YOU NOW HAVE $ %1.2f INCLUDING YOUR PREVIOUS SAVINGS" % (player_funds) "YOU NOW HAVE $ %1.2f INCLUDING YOUR PREVIOUS SAVINGS" % (player_funds)
) )
print("") print()
print("DO YOU WANT TO TRADE FURS NEXT YEAR?") print("DO YOU WANT TO TRADE FURS NEXT YEAR?")
should_trade = get_yes_or_no() should_trade = get_yes_or_no()
if should_trade == "N": if should_trade == "N":
sys.exit(0) # STOP sys.exit(0) # STOP
else: else:
game_state = "trading" game_state = "trading"
if __name__ == "__main__":
main()

View File

@@ -537,7 +537,7 @@ class Golf:
def set_putter_and_stroke(self, strength: float) -> None: def set_putter_and_stroke(self, strength: float) -> None:
putter = self.clubs[self.putt] putter = self.clubs[self.putt]
self.Stroke((putter[1] * (strength / 10.0)), self.putt) self.stroke((putter[1] * (strength / 10.0)), self.putt)
def ask_gauge(self, c: int) -> None: def ask_gauge(self, c: int) -> None:
self.club = self.clubs[c] self.club = self.clubs[c]
@@ -555,7 +555,7 @@ class Golf:
) )
def make_stroke(self, strength: float, c: int) -> None: def make_stroke(self, strength: float, c: int) -> None:
self.Stroke((self.club[1] * (strength / 10.0)), c) self.stroke((self.club[1] * (strength / 10.0)), c)
def tee_up(self) -> None: def tee_up(self) -> None:
# on the green? automatically select putter # on the green? automatically select putter
@@ -579,7 +579,7 @@ class Golf:
else: else:
self.ask("What club do you choose? (1-10)", 1, 10, self.ask_gauge) self.ask("What club do you choose? (1-10)", 1, 10, self.ask_gauge)
def Stroke(self, clubAmt: float, clubIndex: int) -> None: def stroke(self, clubAmt: float, clubIndex: int) -> None:
self.STROKE_NUM += 1 self.STROKE_NUM += 1
flags = 0b000000000000 flags = 0b000000000000
@@ -739,7 +739,7 @@ class Golf:
if (flags & ace) == ace: if (flags & ace) == ace:
print("Hole in One! You aced it.") print("Hole in One! You aced it.")
self.score_card_record_stroke(Ball(0, 0, 0, GameObjType.BALL)) self.score_card_record_stroke(Ball(0, 0, 0, GameObjType.BALL))
self.ReportCurrentScore() self.report_current_score()
return return
if (flags & in_trees) == in_trees: if (flags & in_trees) == in_trees:
@@ -777,7 +777,7 @@ class Golf:
msg = "It's in!" msg = "It's in!"
print(msg) print(msg)
self.score_card_record_stroke(Ball(plot.X, plot.Y, 0, GameObjType.BALL)) self.score_card_record_stroke(Ball(plot.X, plot.Y, 0, GameObjType.BALL))
self.ReportCurrentScore() self.report_current_score()
return return
if ((flags & slice_) == slice_) and not ((flags & on_green) == on_green): if ((flags & slice_) == slice_) and not ((flags & on_green) == on_green):
@@ -829,7 +829,7 @@ class Golf:
self.tee_up() self.tee_up()
def ReportCurrentScore(self) -> None: def report_current_score(self) -> None:
par = CourseInfo[self.HOLE_NUM].par par = CourseInfo[self.HOLE_NUM].par
if len(self.score_card[self.HOLE_NUM]) == par + 1: if len(self.score_card[self.HOLE_NUM]) == par + 1:
print("A bogey. One above par.") print("A bogey. One above par.")
@@ -986,9 +986,7 @@ class Golf:
print(" ") print(" ")
def quit_game(self) -> None: def quit_game(self) -> None:
print("") print("\nLooks like rain. Goodbye!\n")
print("Looks like rain. Goodbye!")
print("")
return return
def game_over(self) -> None: def game_over(self) -> None:

View File

@@ -2,10 +2,6 @@ import random
from typing import Any, List, Tuple from typing import Any, List, Tuple
def print_n_whitespaces(n: int) -> None:
print(" " * n, end="")
def print_board(A: List[List[Any]], n: int) -> None: 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):
@@ -23,25 +19,17 @@ def check_move(_I, _J, _N) -> bool: # 910
def print_banner() -> None: def print_banner() -> None:
print_n_whitespaces(33) print(" " * 33 + "GOMOKU")
print("GOMOKU") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print_n_whitespaces(15) print("WELCOME TO THE ORIENTAL GAME OF GOMOKO.\n")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print()
print()
print()
print("WELCOME TO THE ORIENTAL GAME OF GOMOKO.")
print()
print("THE GAME IS PLAYED ON AN N BY N GRID OF A SIZE") print("THE GAME IS PLAYED ON AN N BY N GRID OF A SIZE")
print("THAT YOU SPECIFY. DURING YOUR PLAY, YOU MAY COVER ONE GRID") print("THAT YOU SPECIFY. DURING YOUR PLAY, YOU MAY COVER ONE GRID")
print("INTERSECTION WITH A MARKER. THE OBJECT OF THE GAME IS TO GET") print("INTERSECTION WITH A MARKER. THE OBJECT OF THE GAME IS TO GET")
print("5 ADJACENT MARKERS IN A ROW -- HORIZONTALLY, VERTICALLY, OR") print("5 ADJACENT MARKERS IN A ROW -- HORIZONTALLY, VERTICALLY, OR")
print("DIAGONALLY. ON THE BOARD DIAGRAM, YOUR MOVES ARE MARKED") print("DIAGONALLY. ON THE BOARD DIAGRAM, YOUR MOVES ARE MARKED")
print("WITH A '1' AND THE COMPUTER MOVES WITH A '2'.") print("WITH A '1' AND THE COMPUTER MOVES WITH A '2'.\n")
print()
print("THE COMPUTER DOES NOT KEEP TRACK OF WHO HAS WON.") print("THE COMPUTER DOES NOT KEEP TRACK OF WHO HAS WON.")
print("TO END THE GAME, TYPE -1,-1 FOR YOUR MOVE.") print("TO END THE GAME, TYPE -1,-1 FOR YOUR MOVE.\n")
print()
def get_board_dimensions() -> int: def get_board_dimensions() -> int:

View File

@@ -71,12 +71,10 @@ def gunner() -> None:
return return
if __name__ == "__main__": def main():
print(" " * 33 + "GUNNER") print(" " * 33 + "GUNNER")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n\n") print("\n\n\n")
print("YOU ARE THE OFFICER-IN-CHARGE, GIVING ORDERS TO A GUN") print("YOU ARE THE OFFICER-IN-CHARGE, GIVING ORDERS TO A GUN")
print("CREW, TELLING THEM THE DEGREES OF ELEVATION YOU ESTIMATE") print("CREW, TELLING THEM THE DEGREES OF ELEVATION YOU ESTIMATE")
print("WILL PLACE A PROJECTILE ON TARGET. A HIT WITHIN 100 YARDS") print("WILL PLACE A PROJECTILE ON TARGET. A HIT WITHIN 100 YARDS")
@@ -85,7 +83,11 @@ if __name__ == "__main__":
while True: while True:
gunner() gunner()
Y = input("TRY AGAIN (Y OR N)? ") not_again = input("TRY AGAIN (Y OR N)? ").upper() != "Y"
if Y != "Y": if not_again:
print("\nOK. RETURN TO BASE CAMP.") print("\nOK. RETURN TO BASE CAMP.")
break break
if __name__ == "__main__":
main()

View File

@@ -12,14 +12,6 @@ import time
from typing import Optional, Tuple from typing import Optional, Tuple
def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + msg)
def get_yes_or_no() -> Tuple[bool, Optional[bool], str]: def get_yes_or_no() -> Tuple[bool, Optional[bool], str]:
msg = input() msg = input()
if msg.upper() == "YES": if msg.upper() == "YES":
@@ -179,14 +171,9 @@ def happy_goodbye(user_name: str) -> None:
def main() -> None: def main() -> None:
print_with_tab(33, "HELLO") print(" " * 33 + "HELLO")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print() print("HELLO. MY NAME IS CREATIVE COMPUTER.\n\n")
print()
print()
print("HELLO. MY NAME IS CREATIVE COMPUTER.")
print()
print()
print("WHAT'S YOUR NAME?") print("WHAT'S YOUR NAME?")
user_name = input() user_name = input()
print() print()

View File

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

View File

@@ -1,11 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
#
# Ported to Python by @iamtraction """Ported to Python by @iamtraction"""
from random import random from random import random
def direction(A, B, X, Y): def direction(A, B, X, Y) -> None:
"""Prints the direction hint for finding the hurkle.""" """Prints the direction hint for finding the hurkle."""
print("GO ", end="") print("GO ", end="")
@@ -22,7 +22,7 @@ def direction(A, B, X, Y):
print() print()
if __name__ == "__main__": def main() -> None:
print(" " * 33 + "HURKLE") print(" " * 33 + "HURKLE")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
@@ -63,3 +63,7 @@ if __name__ == "__main__":
continue continue
print("\n\nLET'S PLAY AGAIN, HURKLE IS HIDING.\n") print("\n\nLET'S PLAY AGAIN, HURKLE IS HIDING.\n")
if __name__ == "__main__":
main()

View File

@@ -20,14 +20,6 @@ g = 10
EXPECTED_ACCURACY_PERCENT = 15 EXPECTED_ACCURACY_PERCENT = 15
def print_with_tab(spaces_count, msg) -> None:
if spaces_count > 0:
spaces = " " * spaces_count
else:
spaces = ""
print(spaces + msg)
def do_quiz(): def do_quiz():
print() print()
print() print()
@@ -75,11 +67,8 @@ def ask_player(question, answer):
def main() -> None: def main() -> None:
print_with_tab(33, "KINEMA") print(" " * 33 + "KINEMA")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
while True: while True:
do_quiz() do_quiz()

View File

@@ -15,15 +15,6 @@ import random
BELLS_ON_SUCCESS = False BELLS_ON_SUCCESS = False
def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + msg)
def print_instructions() -> None: def print_instructions() -> None:
print("LETTER GUESSING GAME") print("LETTER GUESSING GAME")
print() print()
@@ -67,11 +58,8 @@ def play_game():
def main() -> None: def main() -> None:
print_with_tab(33, "LETTER") print(" " * 33 + "LETTER")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
print_instructions() print_instructions()

View File

@@ -108,7 +108,7 @@ def main() -> None:
position += length position += length
print(line_text) print(line_text)
print("") print()
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -7,14 +7,6 @@ Ported by Dave LeCompte
""" """
def print_with_tab(space_count: int, msg: str) -> None:
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + msg)
def is_yes_ish(answer: str) -> bool: def is_yes_ish(answer: str) -> bool:
cleaned = answer.strip().upper() cleaned = answer.strip().upper()
if cleaned in ["Y", "YES"]: if cleaned in ["Y", "YES"]:
@@ -23,29 +15,21 @@ def is_yes_ish(answer: str) -> bool:
def main() -> None: def main() -> None:
print_with_tab(34, "NAME") print(" " * 34 + "NAME")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
print("HELLO.") print("HELLO.")
print("MY NAME iS CREATIVE COMPUTER.") print("MY NAME iS CREATIVE COMPUTER.")
name = input("WHAT'S YOUR NAME (FIRST AND LAST)?") name = input("WHAT'S YOUR NAME (FIRST AND LAST)?")
print() print()
name_as_list = list(name) name_as_list = list(name)
reversed_name = "".join(name_as_list[::-1]) reversed_name = "".join(name_as_list[::-1])
print(f"THANK YOU, {reversed_name}.") print(f"THANK YOU, {reversed_name}.\n")
print()
print("OOPS! I GUESS I GOT IT BACKWARDS. A SMART") print("OOPS! I GUESS I GOT IT BACKWARDS. A SMART")
print("COMPUTER LIKE ME SHOULDN'T MAKE A MISTAKE LIKE THAT!") print("COMPUTER LIKE ME SHOULDN'T MAKE A MISTAKE LIKE THAT!\n\n")
print()
print()
print("BUT I JUST NOTICED YOUR LETTERS ARE OUT OF ORDER.") print("BUT I JUST NOTICED YOUR LETTERS ARE OUT OF ORDER.")
sorted_name = "".join(sorted(name_as_list)) sorted_name = "".join(sorted(name_as_list))
print(f"LET'S PUT THEM IN ORDER LIKE THIS: {sorted_name}") print(f"LET'S PUT THEM IN ORDER LIKE THIS: {sorted_name}\n\n")
print()
print()
print("DON'T YOU LIKE THAT BETTER?") print("DON'T YOU LIKE THAT BETTER?")
like_answer = input() like_answer = input()

View File

@@ -15,14 +15,6 @@ Ported by Dave LeCompte
import time import time
def print_with_tab(spaces_count: int, msg: str) -> None:
if spaces_count > 0:
spaces = " " * spaces_count
else:
spaces = ""
print(spaces + msg)
def get_yes_or_no(): def get_yes_or_no():
while True: while True:
response = input().upper() response = input().upper()
@@ -62,11 +54,8 @@ def play_game():
def main() -> None: def main() -> None:
print_with_tab(33, "NICOMA") print(" " * 33 + "NICOMA")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
print("BOOMERANG PUZZLE FROM ARITHMETICA OF NICOMACHUS -- A.D. 90!") print("BOOMERANG PUZZLE FROM ARITHMETICA OF NICOMACHUS -- A.D. 90!")
print() print()

View File

@@ -9,15 +9,6 @@ Ported by Dave LeCompte
import random import random
def print_with_tab(num_spaces: int, msg: str) -> None:
if num_spaces > 0:
spaces = " " * num_spaces
else:
spaces = ""
print(spaces + msg)
def print_instructions() -> None: 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")
@@ -33,11 +24,8 @@ def fnr():
def main() -> None: def main() -> None:
print_with_tab(33, "NUMBER") print(" " * 33 + "NUMBER")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print()
print()
print()
print_instructions() print_instructions()

View File

@@ -1,22 +1,17 @@
# ONE CHECK """
ONE CHECK
# Port to python by imiro Port to Python by imiro
"""
from typing import Tuple
def tab(x):
return " " * x
def main() -> None: def main() -> None:
# Initial instructions # Initial instructions
print(tab(30) + "ONE CHECK") print(" " * 30 + "ONE CHECK")
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print() print("SOLITAIRE CHECKER PUZZLE BY DAVID AHL\n")
print()
print()
print("SOLITAIRE CHECKER PUZZLE BY DAVID AHL")
print()
print("48 CHECKERS ARE PLACED ON THE 2 OUTSIDE SPACES OF A") print("48 CHECKERS ARE PLACED ON THE 2 OUTSIDE SPACES OF A")
print("STANDARD 64-SQUARE CHECKERBOARD. THE OBJECT IS TO") print("STANDARD 64-SQUARE CHECKERBOARD. THE OBJECT IS TO")
print("REMOVE AS MANY CHECKERS AS POSSIBLE BY DIAGONAL JUMPS") print("REMOVE AS MANY CHECKERS AS POSSIBLE BY DIAGONAL JUMPS")
@@ -25,35 +20,29 @@ def main() -> None:
print("THE BOARD PRINTED OUT ON EACH TURN '1' INDICATES A") print("THE BOARD PRINTED OUT ON EACH TURN '1' INDICATES A")
print("CHECKER AND '0' AN EMPTY SQUARE. WHEN YOU HAVE NO") print("CHECKER AND '0' AN EMPTY SQUARE. WHEN YOU HAVE NO")
print("POSSIBLE JUMPS REMAINING, INPUT A '0' IN RESPONSE TO") print("POSSIBLE JUMPS REMAINING, INPUT A '0' IN RESPONSE TO")
print("QUESTION 'JUMP FROM ?'") print("QUESTION 'JUMP FROM ?'\n")
print() print("HERE IS THE NUMERICAL BOARD:\n")
print("HERE IS THE NUMERICAL BOARD:")
print()
while True: while True:
for j in range(1, 64, 8): for j in range(1, 64, 8):
for i in range(j, j + 7): for i in range(j, j + 7):
print(i, end=(" " * (3 if i < 10 else 2))) print(i, end=(" " * (3 if i < 10 else 2)))
print(j + 7) print(j + 7)
print() print("\nAND HERE IS THE OPENING POSITION OF THE CHECKERS.\n")
print("AND HERE IS THE OPENING POSITION OF THE CHECKERS.")
print()
(jumps, left) = play_game() (jumps, left) = play_game()
print() print()
print("YOU MADE " + jumps + " JUMPS AND HAD " + left + " PIECES") print(f"YOU MADE {jumps} JUMPS AND HAD {left} PIECES")
print("REMAINING ON THE BOARD.") print("REMAINING ON THE BOARD.\n")
print()
if not (try_again()): if not (try_again()):
break break
print() print("\nO.K. HOPE YOU HAD FUN!!")
print("O.K. HOPE YOU HAD FUN!!")
def play_game(): def play_game() -> Tuple[str, str]:
# Initialize board # Initialize board
# Give more than 64 elements to accomodate 1-based indexing # Give more than 64 elements to accomodate 1-based indexing
board = [1] * 70 board = [1] * 70
@@ -71,13 +60,13 @@ def play_game():
while True: while True:
print("JUMP FROM", end=" ") print("JUMP FROM", end=" ")
f = input() f_str = input()
f = int(f) f = int(f_str)
if f == 0: if f == 0:
break break
print("TO", end=" ") print("TO", end=" ")
t = input() t_str = input()
t = int(t) t = int(t_str)
print() print()
# Check legality of move # Check legality of move
@@ -115,10 +104,10 @@ def play_game():
def try_again(): def try_again():
print("TRY AGAIN", end=" ") print("TRY AGAIN", end=" ")
answer = input() answer = input().upper()
if answer.upper() == "YES": if answer == "YES":
return True return True
elif answer.upper() == "NO": elif answer == "NO":
return False return False
print("PLEASE ANSWER 'YES' OR 'NO'.") print("PLEASE ANSWER 'YES' OR 'NO'.")
try_again() try_again()

View File

@@ -134,17 +134,10 @@ SAFE_SPOTS: Final[FrozenSet[Tuple[int, int]]] = COMPUTER_SAFE_SPOTS | frozenset(
) )
def str_with_tab(indent: int, text: str, uppercase: bool = True) -> str:
"""Create a string with ``indent`` spaces followed by ``text``."""
if uppercase:
text = text.upper()
return " " * indent + text
def intro() -> None: 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(" " * 33 + "Queen")
print(str_with_tab(15, "Creative Computing Morristown, New Jersey")) print(" " * 15 + "Creative Computing Morristown, New Jersey")
print("\n" * 2) print("\n" * 2)
if ask("DO YOU WANT INSTRUCTIONS"): if ask("DO YOU WANT INSTRUCTIONS"):
print(INSTR_TXT) print(INSTR_TXT)

View File

@@ -5,7 +5,7 @@ import textwrap
NUMCNT = 9 # How many numbers are we playing with? NUMCNT = 9 # How many numbers are we playing with?
def play(): def main():
print("REVERSE".center(72)) print("REVERSE".center(72))
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY".center(72)) print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY".center(72))
print() print()
@@ -103,6 +103,6 @@ def rules():
if __name__ == "__main__": if __name__ == "__main__":
try: try:
play() main()
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass

View File

@@ -231,7 +231,7 @@ def print_board(board) -> None:
print(" ", end="") print(" ", end="")
for z in range(BOARD_WIDTH): for z in range(BOARD_WIDTH):
print(f"{z+1:3}", end="") print(f"{z+1:3}", end="")
print("") print()
for x in range(len(board)): for x in range(len(board)):
print(f"{x+1:2}", end="") print(f"{x+1:2}", end="")
@@ -240,7 +240,7 @@ def print_board(board) -> None:
print(f"{' ':3}", end="") print(f"{' ':3}", end="")
else: else:
print(f"{board[x][y]:3}", end="") print(f"{board[x][y]:3}", end="")
print("") print()
# place_ship # place_ship
@@ -338,7 +338,7 @@ def initialize_game():
# print out the title 'screen' # print out the title 'screen'
print("{:>38}".format("SALVO")) print("{:>38}".format("SALVO"))
print("{:>57s}".format("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")) print("{:>57s}".format("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"))
print("") print()
print("{:>52s}".format("ORIGINAL BY LAWRENCE SIEGEL, 1973")) print("{:>52s}".format("ORIGINAL BY LAWRENCE SIEGEL, 1973"))
print("{:>56s}".format("PYTHON 3 PORT BY TODD KAISER, MARCH 2021")) print("{:>56s}".format("PYTHON 3 PORT BY TODD KAISER, MARCH 2021"))
print("\n") print("\n")

View File

@@ -80,7 +80,7 @@ def main() -> None:
player_has_won = False player_has_won = False
while (guess_number < MAX_GUESSES) and not player_has_won: while (guess_number < MAX_GUESSES) and not player_has_won:
print("") print()
guess = get_guess() guess = get_guess()
guess_number += 1 guess_number += 1

View File

@@ -186,8 +186,7 @@ HAVE $10,000 TO INVEST. USE INTEGERS FOR ALL YOUR INPUTS.
) )
if __name__ == "__main__": def main():
print("\t\t STOCK MARKET") print("\t\t STOCK MARKET")
help = input("\nDO YOU WANT INSTRUCTIONS(YES OR NO)? ") help = input("\nDO YOU WANT INSTRUCTIONS(YES OR NO)? ")
@@ -226,3 +225,7 @@ if __name__ == "__main__":
print("\nHOPE YOU HAD FUN!!!!") print("\nHOPE YOU HAD FUN!!!!")
input("") input("")
if __name__ == "__main__":
main()

View File

@@ -300,7 +300,7 @@ class Qubit:
print("\n") print("\n")
def humanMove(self, board): def humanMove(self, board):
print("") print()
c = "1234" c = "1234"
while True: while True:
h = input("Your move?\n") h = input("Your move?\n")

View File

@@ -181,7 +181,7 @@ def display(Game: TicTacToe) -> None:
print(line1, "\n\n") print(line1, "\n\n")
def play() -> None: def main() -> 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")
@@ -219,4 +219,4 @@ def play() -> None:
if __name__ == "__main__": if __name__ == "__main__":
play() main()

View File

@@ -191,7 +191,7 @@ def prompt_player(board):
return move return move
def play(): def main():
print(" " * 30 + "TIC-TAC-TOE") print(" " * 30 + "TIC-TAC-TOE")
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n") print("\n\n")
@@ -247,4 +247,4 @@ def play():
if __name__ == "__main__": if __name__ == "__main__":
play() main()

View File

@@ -16,15 +16,7 @@ import datetime
GET_TODAY_FROM_SYSTEM = True GET_TODAY_FROM_SYSTEM = True
def print_with_tab(space_count: int, s: str) -> None: def get_date_from_user(prompt: str):
if space_count > 0:
spaces = " " * space_count
else:
spaces = ""
print(spaces + s)
def get_date_from_user(prompt):
while True: while True:
print(prompt) print(prompt)
date_str = input() date_str = input()
@@ -62,7 +54,7 @@ def previous_day(b):
return b - 1 return b - 1
def is_leap_year(year): def is_leap_year(year: int) -> bool:
if (year % 4) != 0: if (year % 4) != 0:
return False return False
if (year % 100) != 0: if (year % 100) != 0:
@@ -113,7 +105,7 @@ def deduct_time(frac, days, years_remain, months_remain, days_remain):
def time_report(msg, years, months, days): def time_report(msg, years, months, days):
leading_spaces = 23 - len(msg) leading_spaces = 23 - len(msg)
print_with_tab(leading_spaces, msg + f"\t{years}\t{months}\t{days}") print(" " * leading_spaces + f"{msg}\t{years}\t{months}\t{days}")
def make_occupation_label(years): def make_occupation_label(years):
@@ -147,11 +139,8 @@ def end():
def main() -> None: def main() -> None:
print_with_tab(32, "WEEKDAY") print(" " * 32 + "WEEKDAY")
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
print()
print()
print()
print("WEEKDAY IS A COMPUTER DEMONSTRATION THAT") print("WEEKDAY IS A COMPUTER DEMONSTRATION THAT")
print("GIVES FACTS ABOUT A DATE OF INTEREST TO YOU.") print("GIVES FACTS ABOUT A DATE OF INTEREST TO YOU.")
print() print()
@@ -226,8 +215,8 @@ def main() -> None:
print("***HAPPY BIRTHDAY***") print("***HAPPY BIRTHDAY***")
# print report # print report
print_with_tab(23, "\tYEARS\tMONTHS\tDAYS") print(" " * 23 + "\tYEARS\tMONTHS\tDAYS")
print_with_tab(23, "\t-----\t------\t----") print(" " * 23 + "\t-----\t------\t----")
print(f"YOUR AGE (IF BIRTHDATE)\t{el_years}\t{el_months}\t{el_days}") print(f"YOUR AGE (IF BIRTHDATE)\t{el_years}\t{el_months}\t{el_days}")
life_days = (el_years * 365) + (el_months * 30) + el_days + int(el_months / 2) life_days = (el_years * 365) + (el_months * 30) + el_days + int(el_months / 2)
@@ -255,11 +244,9 @@ def main() -> None:
# Calculate retirement date # Calculate retirement date
e = year + 65 e = year + 65
print_with_tab(16, f"*** YOU MAY RETIRE IN {e} ***") print(" " * 16 + f"*** YOU MAY RETIRE IN {e} ***")
end() end()
if __name__ == "__main__": if __name__ == "__main__":
main() main()
# test_harness()

18
96_Word/python/word.py Normal file → Executable file
View File

@@ -1,7 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# WORD
# """
# Converted from BASIC to Python by Trevor Hobson WORD
Converted from BASIC to Python by Trevor Hobson
"""
import random import random
@@ -21,7 +24,7 @@ words = [
] ]
def play_game(): def play_game() -> None:
"""Play one round of the game""" """Play one round of the game"""
random.shuffle(words) random.shuffle(words)
@@ -54,16 +57,15 @@ def play_game():
if i == j: if i == j:
guess_progress[j] = guess_word[i] guess_progress[j] = guess_word[i]
print( print(
"There were", f"There were {matches}",
matches, f"matches and the common letters were... {common_letters}",
"matches and the common letters were... " + common_letters,
) )
print( print(
"From the exact letter matches, you know............ " "From the exact letter matches, you know............ "
+ "".join(guess_progress) + "".join(guess_progress)
) )
if "".join(guess_progress) == guess_word: if "".join(guess_progress) == guess_word:
print("\nYou have guessed the word. It took", guess_count, "guesses!") print(f"\nYou have guessed the word. It took {guess_count} guesses!")
break break
elif matches == 0: elif matches == 0:
print("\nIf you give up, type '?' for you next guess.") print("\nIf you give up, type '?' for you next guess.")