Merge pull request #624 from MartinThoma/py-linting-2

Python: Fix code style issues
This commit is contained in:
Jeff Atwood
2022-03-11 11:24:07 -06:00
committed by GitHub
15 changed files with 258 additions and 226 deletions

View File

@@ -28,4 +28,4 @@ jobs:
mypy . --exclude 79_Slalom --exclude 27_Civil_War --exclude 38_Fur_Trader --exclude 81_Splat --exclude 09_Battle --exclude 40_Gomoko --exclude 36_Flip_Flop --exclude 43_Hammurabi --exclude 04_Awari --exclude 78_Sine_Wave --exclude 77_Salvo --exclude 34_Digits --exclude 17_Bullfight --exclude 16_Bug mypy . --exclude 79_Slalom --exclude 27_Civil_War --exclude 38_Fur_Trader --exclude 81_Splat --exclude 09_Battle --exclude 40_Gomoko --exclude 36_Flip_Flop --exclude 43_Hammurabi --exclude 04_Awari --exclude 78_Sine_Wave --exclude 77_Salvo --exclude 34_Digits --exclude 17_Bullfight --exclude 16_Bug
- name: Test with flake8 - name: Test with flake8
run: | run: |
flake8 . --ignore E501,W504,W503,E741,F541,E203,W291,E722,E711,E712,F821,F401,E402,F841,E302,E731,E266 flake8 . --ignore E501,W504,W503,E741,F541,E203,W291,E722,E711,E712,F821,F401,E402,E731

View File

@@ -7,7 +7,11 @@ from acey_ducey import play_game
@mock.patch("random.shuffle") @mock.patch("random.shuffle")
def test_play_game_lose(mock_random_shuffle, monkeypatch, capsys) -> None: def test_play_game_lose(mock_random_shuffle, monkeypatch, capsys) -> None:
monkeypatch.setattr("sys.stdin", io.StringIO("100\n100")) monkeypatch.setattr("sys.stdin", io.StringIO("100\n100"))
mock_random_shuffle = lambda n: n
def identity(x):
return x
mock_random_shuffle = identity # noqa: F841
play_game() play_game()
captured = capsys.readouterr() captured = capsys.readouterr()
assert captured.out == ( assert captured.out == (

View File

@@ -51,8 +51,6 @@ letters = {
def print_banner(): def print_banner():
"""Print the banner"""
f = [0] * 7 f = [0] * 7
j = [0] * 9 j = [0] * 9
@@ -80,7 +78,7 @@ def print_banner():
mStr = input("Character (type 'ALL' if you want character being printed) ").upper() mStr = input("Character (type 'ALL' if you want character being printed) ").upper()
aStr = input("Statement ") aStr = input("Statement ")
# This means to prepare printer, just press Enter # This means to prepare printer, just press Enter
oStr = input("Set page ") input("Set page ")
for lStr in aStr: for lStr in aStr:
s = letters[lStr].copy() s = letters[lStr].copy()
xStr = mStr xStr = mStr
@@ -100,21 +98,19 @@ def print_banner():
f[u] = 8 - k f[u] = 8 - k
break break
for t1 in range(1, x + 1): for t1 in range(1, x + 1):
lineStr = " " * int((63 - 4.5 * y) * g1 / len(xStr) + 1) line_str = " " * int((63 - 4.5 * y) * g1 / len(xStr) + 1)
for b in range(0, f[u] + 1): for b in range(0, f[u] + 1):
if j[b] == 0: if j[b] == 0:
for i in range(1, y + 1): for i in range(1, y + 1):
lineStr = lineStr + " " * len(xStr) line_str = line_str + " " * len(xStr)
else: else:
lineStr = lineStr + xStr * y line_str = line_str + xStr * y
print(lineStr) print(line_str)
print("\n" * (2 * x - 1)) print("\n" * (2 * x - 1))
# print("\n" * 75) # Feed some more paper from the printer # print("\n" * 75) # Feed some more paper from the printer
def main(): def main():
"""Main"""
print_banner() print_banner()

View File

@@ -26,7 +26,7 @@ def play():
print("DIFFERENT PUNCHES ARE 1 FULL SWING 2 HOOK 3 UPPERCUT 4 JAB") print("DIFFERENT PUNCHES ARE 1 FULL SWING 2 HOOK 3 UPPERCUT 4 JAB")
print("WHAT IS YOUR MAN'S BEST", end=QUESTION_PROMPT) print("WHAT IS YOUR MAN'S BEST", end=QUESTION_PROMPT)
player_best = int(input()) player_best = int(input()) # noqa: TODO - this likely is a bug!
print("WHAT IS HIS VULNERABILITY", end=QUESTION_PROMPT) print("WHAT IS HIS VULNERABILITY", end=QUESTION_PROMPT)
player_weakness = int(input()) player_weakness = int(input())

View File

@@ -50,7 +50,7 @@ def get_coordinates(prompt):
try: try:
x, y = (int(c) for c in response.split(",")) x, y = (int(c) for c in response.split(","))
except ValueError as ve: except ValueError:
print(err_msg) print(err_msg)
continue continue

View File

@@ -1,23 +1,23 @@
import random import random
def printIntro(): def print_intro():
print(" DIGITS") print(" DIGITS")
print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print("\n\n") print("\n\n")
print("THIS IS A GAME OF GUESSING.") print("THIS IS A GAME OF GUESSING.")
def readInstructionChoice(): def read_instruction_choice():
print("FOR INSTRUCTIONS, TYPE '1', ELSE TYPE '0' ? ") print("FOR INSTRUCTIONS, TYPE '1', ELSE TYPE '0' ? ")
try: try:
choice = int(input()) choice = int(input())
return choice == 1 return choice == 1
except (ValueError, TypeError) as m: except (ValueError, TypeError):
return False return False
def printInstructions(): def print_instructions():
print("\n") print("\n")
print("PLEASE TAKE A PIECE OF PAPER AND WRITE DOWN") print("PLEASE TAKE A PIECE OF PAPER AND WRITE DOWN")
print("THE DIGITS '0', '1', OR '2' THIRTY TIMES AT RANDOM.") print("THE DIGITS '0', '1', OR '2' THIRTY TIMES AT RANDOM.")
@@ -30,36 +30,36 @@ def printInstructions():
print() print()
def read10Numbers(): def read_10_numbers():
print("TEN NUMBERS, PLEASE ? ") print("TEN NUMBERS, PLEASE ? ")
numbers = [] numbers = []
for i in range(10): for i in range(10):
validInput = False valid_input = False
while not validInput: while not valid_input:
try: try:
n = int(input()) n = int(input())
validInput = True valid_input = True
numbers.append(n) numbers.append(n)
except (TypeError, ValueError) as e: except (TypeError, ValueError):
print("!NUMBER EXPECTED - RETRY INPUT LINE") print("!NUMBER EXPECTED - RETRY INPUT LINE")
return numbers return numbers
def readContinueChoice(): def read_continue_choice():
print("\nDO YOU WANT TO TRY AGAIN (1 FOR YES, 0 FOR NO) ? ") print("\nDO YOU WANT TO TRY AGAIN (1 FOR YES, 0 FOR NO) ? ")
try: try:
choice = int(input()) choice = int(input())
return choice == 1 return choice == 1
except (ValueError, TypeError) as m: except (ValueError, TypeError):
return False return False
if __name__ == "__main__": if __name__ == "__main__":
printIntro() print_intro()
if readInstructionChoice(): if read_instruction_choice():
printInstructions() print_instructions()
a = 0 a = 0
b = 1 b = 1
@@ -69,28 +69,28 @@ if __name__ == "__main__":
k = [[9] * 3 for i in range(3)] k = [[9] * 3 for i in range(3)]
l = [[3] * 3 for i in range(9)] l = [[3] * 3 for i in range(9)]
continueGame = True continue_game = True
while continueGame: while continue_game:
l[0][0] = 2 l[0][0] = 2
l[4][1] = 2 l[4][1] = 2
l[8][2] = 2 l[8][2] = 2
z = 26 z = 26
z1 = 8 z1 = 8
z2 = 2 z2 = 2
runningCorrect = 0 running_correct = 0
for t in range(1, 4): for t in range(1, 4):
validNumbers = False valid_numbers = False
numbers = [] numbers = []
while not validNumbers: while not valid_numbers:
print() print()
numbers = read10Numbers() numbers = read_10_numbers()
validNumbers = True valid_numbers = True
for number in numbers: for number in numbers:
if number < 0 or number > 2: if number < 0 or number > 2:
print("ONLY USE THE DIGITS '0', '1', OR '2'.") print("ONLY USE THE DIGITS '0', '1', OR '2'.")
print("LET'S TRY AGAIN.") print("LET'S TRY AGAIN.")
validNumbers = False valid_numbers = False
break break
print( print(
@@ -100,24 +100,24 @@ if __name__ == "__main__":
for number in numbers: for number in numbers:
s = 0 s = 0
myGuess = 0 my_guess = 0
for j in range(0, 3): for j in range(0, 3):
# What did the original author have in mind ? # What did the original author have in mind ?
# The first expression always results in 0 because a is always 0 # The first expression always results in 0 because a is always 0
s1 = a * k[z2][j] + b * l[int(z1)][j] + c * m[int(z)][j] s1 = a * k[z2][j] + b * l[int(z1)][j] + c * m[int(z)][j]
if s < s1: if s < s1:
s = s1 s = s1
myGuess = j my_guess = j
elif s1 == s: elif s1 == s:
if random.random() >= 0.5: if random.random() >= 0.5:
myGuess = j my_guess = j
result = "" result = ""
if myGuess != number: if my_guess != number:
result = "WRONG" result = "WRONG"
else: else:
runningCorrect += 1 running_correct += 1
result = "RIGHT" result = "RIGHT"
m[int(z)][number] = m[int(z)][number] + 1 m[int(z)][number] = m[int(z)][number] + 1
l[int(z1)][number] = l[int(z1)][number] + 1 l[int(z1)][number] = l[int(z1)][number] + 1
@@ -125,7 +125,8 @@ if __name__ == "__main__":
z = z - (z / 9) * 9 z = z - (z / 9) * 9
z = 3 * z + number z = 3 * z + number
print( print(
"\n%-14d%-14d%-14s%-14d" % (myGuess, number, result, runningCorrect) "\n%-14d%-14d%-14s%-14d"
% (my_guess, number, result, running_correct)
) )
z1 = z - (z / 9) * 9 z1 = z - (z / 9) * 9
@@ -133,17 +134,17 @@ if __name__ == "__main__":
# print summary report # print summary report
print() print()
if runningCorrect > 10: if running_correct > 10:
print() print()
print("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.") print("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.")
print("I WIN." + "\u0007") print("I WIN." + "\u0007")
elif runningCorrect < 10: elif running_correct < 10:
print("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.") print("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.")
print("YOU BEAT ME. CONGRATULATIONS *****") print("YOU BEAT ME. CONGRATULATIONS *****")
else: else:
print("I GUESSED EXACTLY 1/3 OF YOUR NUMBERS.") print("I GUESSED EXACTLY 1/3 OF YOUR NUMBERS.")
print("IT'S A TIE GAME.") print("IT'S A TIE GAME.")
continueGame = readContinueChoice() continue_game = read_continue_choice()
print("\nTHANKS FOR THE GAME.") print("\nTHANKS FOR THE GAME.")

View File

@@ -27,9 +27,12 @@ human_marbles = -1
computer_marbles = -1 computer_marbles = -1
whose_turn = "" whose_turn = ""
# Only called during development for serious errors that are due to mistakes
# in the program. Should never be called during a regular game.
def serious_error(msg): def serious_error(msg):
"""
Only call this function during development for serious errors that are due
to mistakes in the program. Should never be called during a regular game.
"""
print("serious_error: " + msg) print("serious_error: " + msg)
exit(1) exit(1)

View File

@@ -3,12 +3,12 @@
import random # for generating random numbers import random # for generating random numbers
import sys # for system function, like exit() import sys # for system function, like exit()
### global variables for storing player's status # global variables for storing player's status
player_funds = 0 # no money player_funds = 0 # no money
player_furs = [0, 0, 0, 0] # no furs player_furs = [0, 0, 0, 0] # no furs
### Constants # Constants
FUR_MINK = 0 FUR_MINK = 0
FUR_BEAVER = 1 FUR_BEAVER = 1
FUR_ERMINE = 2 FUR_ERMINE = 2
@@ -22,13 +22,13 @@ FORT_NEWYORK = 3
FORT_NAMES = ["HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"] FORT_NAMES = ["HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"]
def printAtColumn(column: int, words: str): def print_at_column(column: int, words: str):
"""Print the words at the specified column""" """Print the words at the specified column"""
spaces = " " * column # make a fat string of spaces spaces = " " * column # make a fat string of spaces
print(spaces + words) print(spaces + words)
def showIntroduction(): def show_introduction():
"""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 ")
print("1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET") print("1776 LEAVING THE LAKE ONTARIO AREA TO SELL FURS AND GET")
@@ -39,7 +39,7 @@ def showIntroduction():
print("") print("")
def getFortChoice(): def get_fort_choice():
"""Show the player the choices of Fort, get their input, if the """Show the player the choices of Fort, get their input, if the
input is a valid choice (1,2,3) return it, otherwise keep input is a valid choice (1,2,3) return it, otherwise keep
prompting the user.""" prompting the user."""
@@ -68,7 +68,7 @@ def getFortChoice():
return result return result
def showFortComment(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:
@@ -92,7 +92,7 @@ def showFortComment(which_fort):
print("") print("")
def getYesOrNo(): def get_yes_or_no():
"""Prompt the player to enter 'YES' or 'NO'. Keep prompting until """Prompt the player to enter 'YES' or 'NO'. Keep prompting until
valid input is entered. Accept various spellings by only valid input is entered. Accept various spellings by only
checking the first letter of input. checking the first letter of input.
@@ -109,7 +109,7 @@ def getYesOrNo():
return result return result
def getFursPurchase(): def get_furs_purchase():
"""Prompt the player for how many of each fur type they want. """Prompt the player for how many of each fur type they want.
Accept numeric inputs, re-prompting on incorrect input values""" Accept numeric inputs, re-prompting on incorrect input values"""
results = [] results = []
@@ -130,15 +130,11 @@ def getFursPurchase():
return results return results
###
### MAIN
###
if __name__ == "__main__": if __name__ == "__main__":
printAtColumn(31, "FUR TRADER") print_at_column(31, "FUR TRADER")
printAtColumn(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_at_column(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
printAtColumn(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"
@@ -147,13 +143,13 @@ if __name__ == "__main__":
while True: while True:
if game_state == "starting": if game_state == "starting":
showIntroduction() show_introduction()
player_funds = 600 # Initial player start money player_funds = 600 # Initial player start money
player_furs = [0, 0, 0, 0] # Player fur inventory player_furs = [0, 0, 0, 0] # Player fur inventory
print("DO YOU WISH TO TRADE FURS?") print("DO YOU WISH TO TRADE FURS?")
should_trade = getYesOrNo() should_trade = get_yes_or_no()
if should_trade == "N": if should_trade == "N":
sys.exit(0) # STOP sys.exit(0) # STOP
game_state = "trading" game_state = "trading"
@@ -162,7 +158,7 @@ if __name__ == "__main__":
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 = getFursPurchase() player_furs = get_furs_purchase()
if sum(player_furs) > MAX_FURS: if sum(player_furs) > MAX_FURS:
print("") print("")
@@ -174,10 +170,10 @@ if __name__ == "__main__":
game_state = "choosing fort" game_state = "choosing fort"
elif game_state == "choosing fort": elif game_state == "choosing fort":
which_fort = getFortChoice() which_fort = get_fort_choice()
showFortComment(which_fort) show_fort_comment(which_fort)
print("DO YOU WANT TO TRADE AT ANOTHER FORT?") print("DO YOU WANT TO TRADE AT ANOTHER FORT?")
change_fort = getYesOrNo() change_fort = get_yes_or_no()
if change_fort == "N": if change_fort == "N":
game_state = "travelling" game_state = "travelling"
@@ -315,7 +311,7 @@ if __name__ == "__main__":
print("") print("")
print("DO YOU WANT TO TRADE FURS NEXT YEAR?") print("DO YOU WANT TO TRADE FURS NEXT YEAR?")
should_trade = getYesOrNo() should_trade = get_yes_or_no()
if should_trade == "N": if should_trade == "N":
sys.exit(0) # STOP sys.exit(0) # STOP
else: else:

View File

@@ -8,7 +8,6 @@ def gen_random():
def bad_input_850(): def bad_input_850():
print("\nHAMURABI: I CANNOT DO WHAT YOU WISH.") print("\nHAMURABI: I CANNOT DO WHAT YOU WISH.")
print("GET YOURSELF ANOTHER STEWARD!!!!!") print("GET YOURSELF ANOTHER STEWARD!!!!!")
Z = 99
def bad_input_710(S): def bad_input_710(S):
@@ -33,170 +32,178 @@ def b_input(promptstring): # emulate BASIC input. It rejects non-numeric values
return int(x) return int(x)
seed() def main():
title = "HAMURABI" seed()
title = title.rjust(32, " ") title = "HAMURABI"
print(title) title = title.rjust(32, " ")
attribution = "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY" print(title)
attribution = attribution.rjust(15, " ") attribution = "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"
print(attribution) attribution = attribution.rjust(15, " ")
print("\n\n\n") print(attribution)
print("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA") print("\n\n\n")
print("FOR A TEN-YEAR TERM OF OFFICE.\n") print("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA")
print("FOR A TEN-YEAR TERM OF OFFICE.\n")
D1 = 0 D1 = 0
P1 = 0 P1 = 0
Z = 0 # year Z = 0 # year
P = 95 # population P = 95 # population
S = 2800 # grain stores S = 2800 # grain stores
H = 3000 H = 3000
E = H - S # rats eaten E = H - S # rats eaten
Y = 3 # yield (amount of production from land). Reused as price per acre Y = 3 # yield (amount of production from land). Reused as price per acre
A = H / Y # acres of land A = H / Y # acres of land
I = 5 # immigrants I = 5 # immigrants
Q = 1 # boolean for plague, also input for buy/sell land Q = 1 # boolean for plague, also input for buy/sell land
D = 0 # people D = 0 # people
while Z < 11: # line 270. main loop. while the year is less than 11 while Z < 11: # line 270. main loop. while the year is less than 11
print("\n\n\nHAMURABI: I BEG TO REPORT TO YOU") print("\n\n\nHAMURABI: I BEG TO REPORT TO YOU")
Z = Z + 1 # year Z = Z + 1 # year
print("IN YEAR", Z, ",", D, "PEOPLE STARVED,", I, "CAME TO THE CITY,") print("IN YEAR", Z, ",", D, "PEOPLE STARVED,", I, "CAME TO THE CITY,")
P = P + I P = P + I
if Q == 0: if Q == 0:
P = int(P / 2) P = int(P / 2)
print("A HORRIBLE PLAGUE STRUCK! HALF THE PEOPLE DIED.") print("A HORRIBLE PLAGUE STRUCK! HALF THE PEOPLE DIED.")
print("POPULATION IS NOW", P) print("POPULATION IS NOW", P)
print("THE CITY NOW OWNS", A, "ACRES.") print("THE CITY NOW OWNS", A, "ACRES.")
print("YOU HARVESTED", Y, "BUSHELS PER ACRE.") print("YOU HARVESTED", Y, "BUSHELS PER ACRE.")
print("THE RATS ATE", E, "BUSHELS.") print("THE RATS ATE", E, "BUSHELS.")
print("YOU NOW HAVE ", S, "BUSHELS IN STORE.\n") print("YOU NOW HAVE ", S, "BUSHELS IN STORE.\n")
C = int(10 * random()) # random number between 1 and 10 C = int(10 * random()) # random number between 1 and 10
Y = C + 17 Y = C + 17
print("LAND IS TRADING AT", Y, "BUSHELS PER ACRE.") print("LAND IS TRADING AT", Y, "BUSHELS PER ACRE.")
Q = -99 # dummy value to track status Q = -99 # dummy value to track status
while Q == -99: # always run the loop once while Q == -99: # always run the loop once
Q = b_input("HOW MANY ACRES DO YOU WISH TO BUY? ") Q = b_input("HOW MANY ACRES DO YOU WISH TO BUY? ")
if Q < 0: if Q < 0:
Q = -1 # to avoid the corner case of Q=-99 Q = -1 # to avoid the corner case of Q=-99
bad_input_850() bad_input_850()
Z = 99 # jump out of main loop and exit Z = 99 # jump out of main loop and exit
elif Y * Q > S: # can't afford it elif Y * Q > S: # can't afford it
bad_input_710(S) bad_input_710(S)
Q = -99 # give'm a second change to get it right Q = -99 # give'm a second change to get it right
elif Y * Q <= S: # normal case, can afford it elif Y * Q <= S: # normal case, can afford it
A = A + Q # increase the number of acres by Q A = A + Q # increase the number of acres by Q
S = S - Y * Q # decrease the amount of grain in store to pay for it S = S - Y * Q # decrease the amount of grain in store to pay for it
C = 0 # WTF is C for? C = 0 # WTF is C for?
if Q == 0 and Z != 99: # maybe you want to sell some land?
Q = -99
while Q == -99:
Q = b_input("HOW MANY ACRES DO YOU WISH TO SELL? ")
if Q < 0:
bad_input_850()
Z = 99 # jump out of main loop and exit
elif Q <= A: # normal case
A = A - Q # reduce the acres
S = S + Y * Q # add to grain stores
C = 0 # still don't know what C is for
else: # Q>A error!
bad_input_720(A)
Q = -99 # reloop
print("\n")
if Q == 0 and Z != 99: # maybe you want to sell some land?
Q = -99 Q = -99
while Q == -99: while Q == -99 and Z != 99:
Q = b_input("HOW MANY ACRES DO YOU WISH TO SELL? ") Q = b_input("HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? ")
if Q < 0: if Q < 0:
bad_input_850() bad_input_850()
Z = 99 # jump out of main loop and exit Z = 99 # jump out of main loop and exit
elif Q <= A: # normal case # REM *** TRYING TO USE MORE GRAIN THAN IS IN SILOS?
A = A - Q # reduce the acres elif Q > S:
S = S + Y * Q # add to grain stores
C = 0 # still don't know what C is for
else: # Q>A error!
bad_input_720(A)
Q = -99 # reloop
print("\n")
Q = -99
while Q == -99 and Z != 99:
Q = b_input("HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? ")
if Q < 0:
bad_input_850()
# REM *** TRYING TO USE MORE GRAIN THAN IS IN SILOS?
elif Q > S:
bad_input_710(S)
Q = -99 # try again!
else: # we're good. do the transaction
S = S - Q # remove the grain from the stores
C = 1 # set the speed of light to 1. jk
print("\n")
D = -99 # dummy value to force at least one loop
while D == -99 and Z != 99:
D = b_input("HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? ")
if D < 0:
bad_input_850()
Z = 99
elif D > 0:
if D > A:
# REM *** TRYING TO PLANT MORE ACRES THAN YOU OWN?
bad_input_720(A)
D = -99
elif int(D / 2) > S:
# REM *** ENOUGH GRAIN FOR SEED?
bad_input_710(S) bad_input_710(S)
D = -99 Q = -99 # try again!
elif D > 10 * P: else: # we're good. do the transaction
# REM *** ENOUGH PEOPLE TO TEND THE CROPS? S = S - Q # remove the grain from the stores
print("BUT YOU HAVE ONLY", P, "PEOPLE TO TEND THE FIELDS! NOW THEN,") C = 1 # set the speed of light to 1. jk
D = -99
else: # we're good. decrement the grain store
S = S - int(D / 2)
C = gen_random() print("\n")
# REM *** A BOUNTIFUL HARVEST! D = -99 # dummy value to force at least one loop
Y = C while D == -99 and Z != 99:
H = D * Y D = b_input("HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? ")
E = 0 if D < 0:
bad_input_850()
Z = 99 # jump out of main loop and exit
elif D > 0:
if D > A:
# REM *** TRYING TO PLANT MORE ACRES THAN YOU OWN?
bad_input_720(A)
D = -99
elif int(D / 2) > S:
# REM *** ENOUGH GRAIN FOR SEED?
bad_input_710(S)
D = -99
elif D > 10 * P:
# REM *** ENOUGH PEOPLE TO TEND THE CROPS?
print(
"BUT YOU HAVE ONLY", P, "PEOPLE TO TEND THE FIELDS! NOW THEN,"
)
D = -99
else: # we're good. decrement the grain store
S = S - int(D / 2)
C = gen_random() C = gen_random()
if int(C / 2) == C / 2: # even number. 50/50 chance # REM *** A BOUNTIFUL HARVEST!
# REM *** RATS ARE RUNNING WILD!! Y = C
E = int(S / C) # calc losses due to rats, based on previous random number H = D * Y
E = 0
S = S - E + H # deduct losses from stores C = gen_random()
if int(C / 2) == C / 2: # even number. 50/50 chance
# REM *** RATS ARE RUNNING WILD!!
E = int(S / C) # calc losses due to rats, based on previous random number
C = gen_random() S = S - E + H # deduct losses from stores
# REM *** LET'S HAVE SOME BABIES
I = int(C * (20 * A + S) / P / 100 + 1) C = gen_random()
# REM *** HOW MANY PEOPLE HAD FULL TUMMIES? # REM *** LET'S HAVE SOME BABIES
C = int(Q / 20) I = int(C * (20 * A + S) / P / 100 + 1)
# REM *** HORROS, A 15% CHANCE OF PLAGUE # REM *** HOW MANY PEOPLE HAD FULL TUMMIES?
# yeah, should be HORRORS, but left it C = int(Q / 20)
Q = int(10 * (2 * random() - 0.3)) # REM *** HORROS, A 15% CHANCE OF PLAGUE
if P >= C and Z != 99: # if there are some people without full bellies... # yeah, should be HORRORS, but left it
# REM *** STARVE ENOUGH FOR IMPEACHMENT? Q = int(10 * (2 * random() - 0.3))
D = P - C if P >= C and Z != 99: # if there are some people without full bellies...
if D > 0.45 * P: # REM *** STARVE ENOUGH FOR IMPEACHMENT?
print("\nYOU STARVED", D, "PEOPLE IN ONE YEAR!!!") D = P - C
if D > 0.45 * P:
print("\nYOU STARVED", D, "PEOPLE IN ONE YEAR!!!")
national_fink()
Z = 99 # exit the loop
P1 = ((Z - 1) * P1 + D * 100 / P) / Z
P = C
D1 = D1 + D
if Z != 99:
print("IN YOUR 10-YEAR TERM OF OFFICE,", P1, "PERCENT OF THE")
print("POPULATION STARVED PER YEAR ON THE AVERAGE, I.E. A TOTAL OF")
print(D1, "PEOPLE DIED!!")
L = A / P
print("YOU STARTED WITH 10 ACRES PER PERSON AND ENDED WITH")
print(L, "ACRES PER PERSON.\n")
if P1 > 33 or L < 7:
national_fink() national_fink()
Z = 99 # exit the loop elif P1 > 10 or L < 9:
P1 = ((Z - 1) * P1 + D * 100 / P) / Z print("YOUR HEAVY-HANDED PERFORMANCE SMACKS OF NERO AND IVAN IV.")
P = C print("THE PEOPLE (REMIANING) FIND YOU AN UNPLEASANT RULER, AND,")
D1 = D1 + D print("FRANKLY, HATE YOUR GUTS!!")
elif P1 > 3 or L < 10:
print("YOUR PERFORMANCE COULD HAVE BEEN SOMEWHAT BETTER, BUT")
print("REALLY WASN'T TOO BAD AT ALL. ", int(P * 0.8 * random()), "PEOPLE")
print("WOULD DEARLY LIKE TO SEE YOU ASSASSINATED BUT WE ALL HAVE OUR")
print("TRIVIAL PROBLEMS.")
else:
print("A FANTASTIC PERFORMANCE!!! CHARLEMANGE, DISRAELI, AND")
print("JEFFERSON COMBINED COULD NOT HAVE DONE BETTER!\n")
for N in range(1, 10):
print("\a")
if Z != 99: print("\nSO LONG FOR NOW.\n")
print("IN YOUR 10-YEAR TERM OF OFFICE,", P1, "PERCENT OF THE")
print("POPULATION STARVED PER YEAR ON THE AVERAGE, I.E. A TOTAL OF")
print(D1, "PEOPLE DIED!!")
L = A / P
print("YOU STARTED WITH 10 ACRES PER PERSON AND ENDED WITH")
print(L, "ACRES PER PERSON.\n")
if P1 > 33 or L < 7:
national_fink()
elif P1 > 10 or L < 9:
print("YOUR HEAVY-HANDED PERFORMANCE SMACKS OF NERO AND IVAN IV.")
print("THE PEOPLE (REMIANING) FIND YOU AN UNPLEASANT RULER, AND,")
print("FRANKLY, HATE YOUR GUTS!!")
elif P1 > 3 or L < 10:
print("YOUR PERFORMANCE COULD HAVE BEEN SOMEWHAT BETTER, BUT")
print("REALLY WASN'T TOO BAD AT ALL. ", int(P * 0.8 * random()), "PEOPLE")
print("WOULD DEARLY LIKE TO SEE YOU ASSASSINATED BUT WE ALL HAVE OUR")
print("TRIVIAL PROBLEMS.")
else:
print("A FANTASTIC PERFORMANCE!!! CHARLEMANGE, DISRAELI, AND")
print("JEFFERSON COMBINED COULD NOT HAVE DONE BETTER!\n")
for N in range(1, 10):
print("\a")
print("\nSO LONG FOR NOW.\n")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,30 @@
import io
import hamurabi
def test_main(monkeypatch, capsys):
monkeypatch.setattr("sys.stdin", io.StringIO("100\n100\n100"))
hamurabi.main()
captured = capsys.readouterr()
actual_lines = captured.out.splitlines()
expected_lines = [
"HAMURABI", # 0
"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", # 1
"", # 2
"", # 3
"", # 4
"", # 5
"TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA", # 6
"FOR A TEN-YEAR TERM OF OFFICE.", # 7
"", # 8
"", # 9
"", # 10
"", # 11
"HAMURABI: I BEG TO REPORT TO YOU\n", # 12
"IN YEAR 1 , 0 PEOPLE STARVED, 5 CAME TO THE CITY,\n", # 13
"POPULATION IS NOW 100\n", # 14
"THE CITY NOW OWNS 1000.0 ACRES.", # 15
]
for i, (actual, expected) in enumerate(zip(actual_lines, expected_lines)):
assert actual.strip() == expected.strip(), f"Line {i} is wrong"

View File

@@ -32,7 +32,6 @@ def get_yes_or_no():
def ask_enjoy_question(user_name): def ask_enjoy_question(user_name):
print(f"HI THERE, {user_name}, ARE YOU ENJOYING YOURSELF HERE?") print(f"HI THERE, {user_name}, ARE YOU ENJOYING YOURSELF HERE?")
has_answer = False
while True: while True:
valid, value, msg = get_yes_or_no() valid, value, msg = get_yes_or_no()

View File

@@ -238,7 +238,7 @@ def get_coordinates():
response = input() response = input()
m1, m2 = (int(c) for c in response.split(",")) m1, m2 = (int(c) for c in response.split(","))
return m1, m2 return m1, m2
except ValueError as ve: except ValueError:
print_illegal() print_illegal()
@@ -385,7 +385,6 @@ def get_computer_spaces(board):
def has_computer_move(board): def has_computer_move(board):
for i in get_computer_spaces(board): for i in get_computer_spaces(board):
found_move = False
if board_contents(board, i + 3) == EMPTY_SPACE: if board_contents(board, i + 3) == EMPTY_SPACE:
# can move forward (down) # can move forward (down)
return True return True

View File

@@ -66,7 +66,6 @@ def add_ljust(line, s, pos):
# adds a new field to a line left justified starting at pos # adds a new field to a line left justified starting at pos
s = str(s) s = str(s)
slen = len(s)
if len(line) > pos: if len(line) > pos:
line = line[:pos] line = line[:pos]
if len(line) < pos: if len(line) < pos:

View File

@@ -94,7 +94,7 @@ def main():
num_moves = 1 num_moves = 1
inconsistent_information = False inconsistent_information = False
print("NOW I GUESS. THINK OF A COMBINATION.") print("NOW I GUESS. THINK OF A COMBINATION.")
player_ready = input("HIT RETURN WHEN READY: ") input("HIT RETURN WHEN READY: ")
while num_moves < 10 and not turn_over and not inconsistent_information: while num_moves < 10 and not turn_over and not inconsistent_information:
found_guess = False found_guess = False
computer_guess = int(possibilities * random.random()) computer_guess = int(possibilities * random.random())

View File

@@ -30,7 +30,7 @@ def get_date_from_user(prompt):
date_str = input() date_str = input()
try: try:
month_num, day_num, year_num = (int(x) for x in date_str.split(",")) month_num, day_num, year_num = (int(x) for x in date_str.split(","))
except Exception as e: except Exception:
print("I COULDN'T UNDERSTAND THAT. TRY AGAIN.") print("I COULDN'T UNDERSTAND THAT. TRY AGAIN.")
return month_num, day_num, year_num return month_num, day_num, year_num
@@ -186,11 +186,9 @@ def main():
target_day_value = calc_day_value(year, month, day) target_day_value = calc_day_value(year, month, day)
is_today = False is_today = False
is_future = False
if today_day_value < target_day_value: if today_day_value < target_day_value:
label = "WILL BE A" label = "WILL BE A"
is_future = False
elif today_day_value == target_day_value: elif today_day_value == target_day_value:
label = "IS A" label = "IS A"
is_today = True is_today = True