Python: Fix Flake8 E722 and E741

Additionally:

* Use functions to group blocks of code
* Use variable names (not just one character...)
This commit is contained in:
Martin Thoma
2022-03-12 08:17:03 +01:00
parent fc9ea8eaf9
commit af88007734
18 changed files with 846 additions and 764 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,F821,F401,E402,E731 flake8 . --ignore E501,W504,W503,F541,E203,W291,E711,F821,F401,E402,E731

View File

@@ -227,7 +227,7 @@ class Basketball:
print("Incorrect answer. Retype it. Your shot? ", end="") print("Incorrect answer. Retype it. Your shot? ", end="")
try: try:
self.shot = int(input()) self.shot = int(input())
except: except Exception:
continue continue
if self.time < 100 or random.random() < 0.5: if self.time < 100 or random.random() < 0.5:

View File

@@ -51,14 +51,14 @@ def print_at_tab(line, tab, s):
def run_simulation(delta_t, v0, coeff_rest): def run_simulation(delta_t, v0, coeff_rest):
t = [0] * 20 # time of each bounce bounce_time = [0] * 20 # time of each bounce
print("FEET") print("FEET")
print() print()
sim_dur = int(70 / (v0 / (16 * delta_t))) sim_dur = int(70 / (v0 / (16 * delta_t)))
for i in range(1, sim_dur + 1): for i in range(1, sim_dur + 1):
t[i] = v0 * coeff_rest ** (i - 1) / 16 bounce_time[i] = v0 * coeff_rest ** (i - 1) / 16
# Draw the trajectory of the bouncing ball, one slice of height at a time # 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 = int(-16 * (v0 / 32) ** 2 + v0**2 / 32 + 0.5)
@@ -66,32 +66,32 @@ def run_simulation(delta_t, v0, coeff_rest):
line = "" line = ""
if int(h) == h: if int(h) == h:
line += str(int(h)) line += str(int(h))
l = 0 total_time = 0
for i in range(1, sim_dur + 1): for i in range(1, sim_dur + 1):
tm = 0 tm = 0
while tm <= t[i]: while tm <= bounce_time[i]:
l += delta_t total_time += delta_t
if ( if (
abs(h - (0.5 * (-32) * tm**2 + v0 * coeff_rest ** (i - 1) * tm)) abs(h - (0.5 * (-32) * tm**2 + v0 * coeff_rest ** (i - 1) * tm))
<= 0.25 <= 0.25
): ):
line = print_at_tab(line, int(l / delta_t), "0") line = print_at_tab(line, int(total_time / delta_t), "0")
tm += delta_t tm += delta_t
tm = t[i + 1] / 2 tm = bounce_time[i + 1] / 2
if -16 * tm**2 + v0 * coeff_rest ** (i - 1) * tm < h: if -16 * tm**2 + v0 * coeff_rest ** (i - 1) * tm < h:
break break
print(line) print(line)
h = h - 0.5 h = h - 0.5
print("." * (int((l + 1) / delta_t) + 1)) print("." * (int((total_time + 1) / delta_t) + 1))
print print
line = " 0" line = " 0"
for i in range(1, int(l + 0.9995) + 1): for i in range(1, int(total_time + 0.9995) + 1):
line = print_at_tab(line, int(i / delta_t), str(i)) line = print_at_tab(line, int(i / delta_t), str(i))
print(line) print(line)
print() print()
print(print_at_tab("", int((l + 1) / (2 * delta_t) - 2), "SECONDS")) print(print_at_tab("", int((total_time + 1) / (2 * delta_t) - 2), "SECONDS"))
print() print()

View File

@@ -41,77 +41,77 @@ print_n_whitespaces(45)
print("ANYTHING") print("ANYTHING")
print() print()
M = 0 nb_winners = 0
R = 0 round = 0
W = {} winners = {}
for I in range(1, 11): for i in range(1, 11):
W[I] = 0 winners[i] = 0
S = {} total_score = {}
for I in range(1, 21): for i in range(1, 21):
S[I] = 0 total_score[i] = 0
N = int(input("HOW MANY PLAYERS? ")) nb_players = int(input("HOW MANY PLAYERS? "))
A = {} player_names = {}
for I in range(1, N + 1): for i in range(1, nb_players + 1):
Name = input("NAME OF PLAYER #") player_name = input("NAME OF PLAYER #")
A[I] = Name player_names[i] = player_name
while M == 0: while nb_winners == 0:
R = R + 1 round = round + 1
print() print()
print(f"ROUND {R}---------") print(f"ROUND {round}---------")
for I in range(1, N + 1): for i in range(1, nb_players + 1):
print() print()
while True: while True:
T = int(input(f"{A[I]}'S THROW? ")) throw = int(input(f"{player_names[i]}'S THROW? "))
if T < 1 or T > 3: if throw not in [1, 2, 3]:
print("INPUT 1, 2, OR 3!") print("INPUT 1, 2, OR 3!")
else: else:
break break
if T == 1: if throw == 1:
P1 = 0.65 P1 = 0.65
P2 = 0.55 P2 = 0.55
P3 = 0.5 P3 = 0.5
P4 = 0.5 P4 = 0.5
elif T == 2: elif throw == 2:
P1 = 0.99 P1 = 0.99
P2 = 0.77 P2 = 0.77
P3 = 0.43 P3 = 0.43
P4 = 0.01 P4 = 0.01
elif T == 3: elif throw == 3:
P1 = 0.95 P1 = 0.95
P2 = 0.75 P2 = 0.75
P3 = 0.45 P3 = 0.45
P4 = 0.05 P4 = 0.05
U = random.random() throwing_luck = random.random()
if U >= P1: if throwing_luck >= P1:
print("BULLSEYE!! 40 POINTS!") print("BULLSEYE!! 40 POINTS!")
B = 40 points = 40
elif U >= P2: elif throwing_luck >= P2:
print("30-POINT ZONE!") print("30-POINT ZONE!")
B = 30 points = 30
elif U >= P3: elif throwing_luck >= P3:
print("20-POINT ZONE") print("20-POINT ZONE")
B = 20 points = 20
elif U >= P4: elif throwing_luck >= P4:
print("WHEW! 10 POINTS.") print("WHEW! 10 POINTS.")
B = 10 points = 10
else: else:
print("MISSED THE TARGET! TOO BAD.") print("MISSED THE TARGET! TOO BAD.")
B = 0 points = 0
S[I] = S[I] + B total_score[i] = total_score[i] + points
print(f"TOTAL SCORE = {S[I]}") print(f"TOTAL SCORE = {total_score[i]}")
for I in range(1, N + 1): for player_index in range(1, nb_players + 1):
if S[I] > 200: if total_score[player_index] > 200:
M = M + 1 nb_winners = nb_winners + 1
W[M] = I winners[nb_winners] = player_index
print() print()
print("WE HAVE A WINNER!!") print("WE HAVE A WINNER!!")
print() print()
for I in range(1, M + 1): for i in range(1, nb_winners + 1):
print(f"{A[W[I]]} SCORED {S[W[I]]} POINTS.") print(f"{player_names[winners[i]]} SCORED {total_score[winners[i]]} POINTS.")
print() print()
print("THANKS FOR THE GAME.") print("THANKS FOR THE GAME.")

View File

@@ -96,7 +96,7 @@ while still_running:
try: try:
if response.upper()[0] != "Y": if response.upper()[0] != "Y":
still_running = False still_running = False
except: except Exception:
still_running = False still_running = False

View File

@@ -1,12 +1,21 @@
import math import math
import random from typing import List
def tab(n): def tab(n: int) -> str:
return " " * n return " " * n
battles = [ def get_choice(prompt: str, choices: List[str]) -> str:
while True:
choice = input(prompt)
if choice in choices:
break
return choice
def main():
battles = [
[ [
"JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET", "JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET",
"UNION FORCES WITH GEN. MCDOWELL IN A PREMATURE BATTLE AT", "UNION FORCES WITH GEN. MCDOWELL IN A PREMATURE BATTLE AT",
@@ -62,9 +71,9 @@ battles = [
"AUGUST, 1864. SHERMAN AND THREE VETERAN ARMIES CONVERGED", "AUGUST, 1864. SHERMAN AND THREE VETERAN ARMIES CONVERGED",
"ON ATLANTA AND DEALT THE DEATH BLOW TO THE CONFEDERACY.", "ON ATLANTA AND DEALT THE DEATH BLOW TO THE CONFEDERACY.",
], ],
] ]
historical_data = [ historical_data = [
[], [],
["BULL RUN", 18000, 18500, 1967, 2708, 1], ["BULL RUN", 18000, 18500, 1967, 2708, 1],
["SHILOH", 40000.0, 44894.0, 10699, 13047, 3], ["SHILOH", 40000.0, 44894.0, 10699, 13047, 3],
@@ -80,34 +89,32 @@ historical_data = [
["CHATTANOOGA", 37000.0, 60000.0, 36700.0, 5800, 2], ["CHATTANOOGA", 37000.0, 60000.0, 36700.0, 5800, 2],
["SPOTSYLVANIA", 62000.0, 110000.0, 17723, 18000, 2], ["SPOTSYLVANIA", 62000.0, 110000.0, 17723, 18000, 2],
["ATLANTA", 65000.0, 100000.0, 8500, 3700, 1], ["ATLANTA", 65000.0, 100000.0, 8500, 3700, 1],
] ]
sa = {} sa = {}
da = {} dollars_available = {}
fa = {} food_array = {}
ha = {} salaries = {}
ba = {} ammunition = {}
oa = {} oa = {}
print(tab(26) + "CIVIL WAR") print(tab(26) + "CIVIL WAR")
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
print() print()
print() print()
# Original game design: Cram, Goodie, Hibbard Lexington H.S. # Original game design: Cram, Goodie, Hibbard Lexington H.S.
# Modifications: G. Paul, R. Hess (Ties), 1973 # 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
sa[3] = 25 sa[3] = 25
sa[4] = 25 sa[4] = 25
d = -1 # number of players in the game party = -1 # number of players in the game
print() print()
while True: show_instructions = get_choice(
X = input("DO YOU WANT INSTRUCTIONS? ") "DO YOU WANT INSTRUCTIONS? YES OR NO -- ", ["YES", "NO"]
if X == "YES" or X == "NO": )
break
print("YES OR NO -- ")
if X == "YES": if show_instructions == "YES":
print() print()
print() print()
print() print()
@@ -134,62 +141,56 @@ if X == "YES":
print(" (4) ENCIRCLEMENT") print(" (4) ENCIRCLEMENT")
print("YOU MAY SURRENDER BY TYPING A '5' FOR YOUR STRATEGY.") print("YOU MAY SURRENDER BY TYPING A '5' FOR YOUR STRATEGY.")
print() print()
print() print()
print() print()
print("ARE THERE TWO GENERALS PRESENT ", end="") print("ARE THERE TWO GENERALS PRESENT ", end="")
while True: bs = get_choice("(ANSWER YES OR NO) ", ["YES", "NO"])
bs = input("(ANSWER YES OR NO) ")
if bs == "YES": if bs == "YES":
d = 2 party = 2
break
elif bs == "NO": elif bs == "NO":
d = 1 party = 1
print() print()
print("YOU ARE THE CONFEDERACY. GOOD LUCK!") print("YOU ARE THE CONFEDERACY. GOOD LUCK!")
print() print()
break
print("SELECT A BATTLE BY TYPING A NUMBER FROM 1 TO 14 ON") print("SELECT A BATTLE BY TYPING A NUMBER FROM 1 TO 14 ON")
print("REQUEST. TYPE ANY OTHER NUMBER TO END THE SIMULATION.") print("REQUEST. TYPE ANY OTHER NUMBER TO END THE SIMULATION.")
print("BUT '0' BRINGS BACK EXACT PREVIOUS BATTLE SITUATION") print("BUT '0' BRINGS BACK EXACT PREVIOUS BATTLE SITUATION")
print("ALLOWING YOU TO REPLAY IT") print("ALLOWING YOU TO REPLAY IT")
print() print()
print("NOTE: A NEGATIVE FOOD$ ENTRY CAUSES THE PROGRAM TO ") print("NOTE: A NEGATIVE FOOD$ ENTRY CAUSES THE PROGRAM TO ")
print("USE THE ENTRIES FROM THE PREVIOUS BATTLE") print("USE THE ENTRIES FROM THE PREVIOUS BATTLE")
print() print()
print("AFTER REQUESTING A BATTLE, DO YOU WISH ", end="") print("AFTER REQUESTING A BATTLE, DO YOU WISH ", end="")
print("BATTLE DESCRIPTIONS ", end="") print("BATTLE DESCRIPTIONS ", end="")
while True: xs = get_choice("(ANSWER YES OR NO) ", ["YES", "NO"])
xs = input("(ANSWER YES OR NO) ") line = 0
if xs == "YES" or xs == "NO": w = 0
break r1 = 0
l = 0 q1 = 0
w = 0 m3 = 0
r1 = 0 m4 = 0
q1 = 0 p1 = 0
m3 = 0 p2 = 0
m4 = 0 t1 = 0
p1 = 0 t2 = 0
p2 = 0 for i in range(1, 3):
t1 = 0 dollars_available[i] = 0
t2 = 0 food_array[i] = 0
for i in range(1, 3): salaries[i] = 0
da[i] = 0 ammunition[i] = 0
fa[i] = 0
ha[i] = 0
ba[i] = 0
oa[i] = 0 oa[i] = 0
r2 = 0 r2 = 0
q2 = 0 q2 = 0
c6 = 0 c6 = 0
f = 0 food = 0
w0 = 0 w0 = 0
y = 0 strategy_index = 0
y2 = 0 union_strategy_index = 0
u = 0 u = 0
u2 = 0 u2 = 0
while True: while True:
print() print()
print() print()
print() print()
@@ -205,15 +206,15 @@ while True:
m = historical_data[a][5] m = historical_data[a][5]
u = 0 u = 0
# Inflation calc # Inflation calc
i1 = 10 + (l - w) * 2 i1 = 10 + (line - w) * 2
i2 = 10 + (w - l) * 2 i2 = 10 + (w - line) * 2
# Money available # Money available
da[1] = 100 * math.floor( dollars_available[1] = 100 * math.floor(
(m1 * (100 - i1) / 2000) * (1 + (r1 - q1) / (r1 + 1)) + 0.5 (m1 * (100 - i1) / 2000) * (1 + (r1 - q1) / (r1 + 1)) + 0.5
) )
da[2] = 100 * math.floor(m2 * (100 - i2) / 2000 + 0.5) dollars_available[2] = 100 * math.floor(m2 * (100 - i2) / 2000 + 0.5)
if bs == "YES": if bs == "YES":
da[2] = 100 * math.floor( dollars_available[2] = 100 * math.floor(
(m2 * (100 - i2) / 2000) * (1 + (r2 - q2) / (r2 + 1)) + 0.5 (m2 * (100 - i2) / 2000) * (1 + (r2 - q2) / (r2 + 1)) + 0.5
) )
# Men available # Men available
@@ -235,38 +236,38 @@ while True:
print() print()
print(" \tCONFEDERACY\t UNION") print(" \tCONFEDERACY\t UNION")
print(f"MEN\t {m5}\t\t {m6}") print(f"MEN\t {m5}\t\t {m6}")
print(f"MONEY\t ${da[1]}\t\t${da[2]}") print(f"MONEY\t ${dollars_available[1]}\t\t${dollars_available[2]}")
print(f"INFLATION\t {i1 + 15}%\t {i2}%") print(f"INFLATION\t {i1 + 15}%\t {i2}%")
print() print()
# ONLY IN PRINTOUT IS CONFED INFLATION = I1 + 15 % # ONLY IN PRINTOUT IS CONFED INFLATION = I1 + 15 %
# IF TWO GENERALS, INPUT CONFED, FIRST # IF TWO GENERALS, INPUT CONFED, FIRST
for i in range(1, d + 1): for i in range(1, party + 1):
if bs == "YES" and i == 1: if bs == "YES" and i == 1:
print("CONFEDERATE GENERAL---", end="") print("CONFEDERATE GENERAL---", end="")
print("HOW MUCH DO YOU WISH TO SPEND FOR") print("HOW MUCH DO YOU WISH TO SPEND FOR")
while True: while True:
f = int(input(" - FOOD...... ? ")) food = int(input(" - FOOD...... ? "))
if f < 0: if food < 0:
if r1 == 0: if r1 == 0:
print("NO PREVIOUS ENTRIES") print("NO PREVIOUS ENTRIES")
continue continue
print("ASSUME YOU WANT TO KEEP SAME ALLOCATIONS") print("ASSUME YOU WANT TO KEEP SAME ALLOCATIONS")
print() print()
break break
fa[i] = f food_array[i] = food
while True: while True:
ha[i] = int(input(" - SALARIES.. ? ")) salaries[i] = int(input(" - SALARIES.. ? "))
if ha[i] >= 0: if salaries[i] >= 0:
break break
print("NEGATIVE VALUES NOT ALLOWED.") print("NEGATIVE VALUES NOT ALLOWED.")
while True: while True:
ba[i] = int(input(" - AMMUNITION ? ")) ammunition[i] = int(input(" - AMMUNITION ? "))
if ba[i] >= 0: if ammunition[i] >= 0:
break break
print("NEGATIVE VALUES NOT ALLOWED.") print("NEGATIVE VALUES NOT ALLOWED.")
print() print()
if fa[i] + ha[i] + ba[i] > da[i]: if food_array[i] + salaries[i] + ammunition[i] > dollars_available[i]:
print("THINK AGAIN! YOU HAVE ONLY $" + da[i]) print("THINK AGAIN! YOU HAVE ONLY $" + dollars_available[i])
else: else:
break break
@@ -274,14 +275,16 @@ while True:
break break
print("UNION GENERAL---", end="") print("UNION GENERAL---", end="")
for z in range(1, d + 1): for z in range(1, party + 1):
if bs == "YES": if bs == "YES":
if z == 1: if z == 1:
print("CONFEDERATE ", end="") print("CONFEDERATE ", end="")
else: else:
print(" UNION ", end="") print(" UNION ", end="")
# Find morale # Find morale
o = (2 * math.pow(fa[z], 2) + math.pow(ha[z], 2)) / math.pow(f1, 2) + 1 o = (2 * math.pow(food_array[z], 2) + math.pow(salaries[z], 2)) / math.pow(
f1, 2
) + 1
if o >= 10: if o >= 10:
print("MORALE IS HIGH") print("MORALE IS HIGH")
elif o >= 5: elif o >= 5:
@@ -307,18 +310,18 @@ while True:
# Choose strategies # Choose strategies
if bs != "YES": if bs != "YES":
while True: while True:
y = int(input("YOUR STRATEGY ")) strategy_index = int(input("YOUR STRATEGY "))
if abs(y - 3) < 3: if abs(strategy_index - 3) < 3:
break break
print(f"STRATEGY {y} NOT ALLOWED.") print(f"STRATEGY {strategy_index} NOT ALLOWED.")
if y == 5: if strategy_index == 5:
print("THE CONFEDERACY HAS SURRENDERED.") print("THE CONFEDERACY HAS SURRENDERED.")
break break
# Union strategy is computer chosen # Union strategy is computer chosen
if a == 0: if a == 0:
while True: while True:
y2 = int(input("UNION STRATEGY IS ")) union_strategy_index = int(input("UNION STRATEGY IS "))
if y2 > 0 and y2 < 5: if union_strategy_index > 0 and union_strategy_index < 5:
break break
print("ENTER 1, 2, 3, OR 4 (USUALLY PREVIOUS UNION STRATEGY)") print("ENTER 1, 2, 3, OR 4 (USUALLY PREVIOUS UNION STRATEGY)")
else: else:
@@ -330,29 +333,31 @@ while True:
# then r-100 is extra weight given to that strategy. # then r-100 is extra weight given to that strategy.
if r < s0: if r < s0:
break break
y2 = i union_strategy_index = i
print(y2) print(union_strategy_index)
else: else:
for i in range(1, 3): for i in range(1, 3):
if i == 1: if i == 1:
print("CONFEDERATE STRATEGY ? ", end="") print("CONFEDERATE STRATEGY ? ", end="")
while True: while True:
y = int(input()) strategy_index = int(input())
if abs(y - 3) < 3: if abs(strategy_index - 3) < 3:
break break
print(f"STRATEGY {y} NOT ALLOWED.") print(f"STRATEGY {strategy_index} NOT ALLOWED.")
print("YOUR STRATEGY ? ", end="") print("YOUR STRATEGY ? ", end="")
if i == 2: if i == 2:
y2 = y union_strategy_index = strategy_index
y = y1 strategy_index = previous_strategy
if y2 != 5: if union_strategy_index != 5:
break break
else: else:
y1 = y previous_strategy = strategy_index # noqa: F841
print("UNION STRATEGY ? ", end="") print("UNION STRATEGY ? ", end="")
# Simulated losses - North # Simulated losses - North
c6 = (2 * c2 / 5) * (1 + 1 / (2 * (abs(y2 - y) + 1))) c6 = (2 * c2 / 5) * (
c6 = c6 * (1.28 + (5 * m2 / 6) / (ba[2] + 1)) 1 + 1 / (2 * (abs(union_strategy_index - strategy_index) + 1))
)
c6 = c6 * (1.28 + (5 * m2 / 6) / (ammunition[2] + 1))
c6 = math.floor(c6 * (1 + 1 / o2) + 0.5) c6 = math.floor(c6 * (1 + 1 / o2) + 0.5)
# If loss > men present, rescale losses # If loss > men present, rescale losses
e2 = 100 / o2 e2 = 100 / o2
@@ -365,15 +370,17 @@ while True:
print() print()
print() print()
print("\t\tCONFEDERACY\tUNION") print("\t\tCONFEDERACY\tUNION")
c5 = (2 * c1 / 5) * (1 + 1 / (2 * (abs(y2 - y) + 1))) c5 = (2 * c1 / 5) * (
c5 = math.floor(c5 * (1 + 1 / o) * (1.28 + f1 / (ba[1] + 1)) + 0.5) 1 + 1 / (2 * (abs(union_strategy_index - strategy_index) + 1))
)
c5 = math.floor(c5 * (1 + 1 / o) * (1.28 + f1 / (ammunition[1] + 1)) + 0.5)
e = 100 / o e = 100 / o
if c5 + 100 / o >= m1 * (1 + (p1 - t1) / (m3 + 1)): if c5 + 100 / o >= m1 * (1 + (p1 - t1) / (m3 + 1)):
c5 = math.floor(13 * m1 / 20 * (1 + (p1 - t1) / (m3 + 1))) c5 = math.floor(13 * m1 / 20 * (1 + (p1 - t1) / (m3 + 1)))
e = 7 * c5 / 13 e = 7 * c5 / 13
u = 1 u = 1
if d == 1: if party == 1:
c6 = math.floor(17 * c2 * c1 / (c5 * 20)) c6 = math.floor(17 * c2 * c1 / (c5 * 20))
e2 = 5 * o e2 = 5 * o
@@ -401,7 +408,7 @@ while True:
elif u == 1 or (u != 1 and u2 != 1 and c5 + e > c6 + e2): elif u == 1 or (u != 1 and u2 != 1 and c5 + e > c6 + e2):
print("THE UNION WINS " + str(cs)) print("THE UNION WINS " + str(cs))
if a != 0: if a != 0:
l += 1 line += 1
else: else:
print("THE CONFEDERACY WINS " + str(cs)) print("THE CONFEDERACY WINS " + str(cs))
if a != 0: if a != 0:
@@ -413,8 +420,8 @@ while True:
t2 += c6 + e2 t2 += c6 + e2
p1 += c1 p1 += c1
p2 += c2 p2 += c2
q1 += fa[1] + ha[1] + ba[1] q1 += food_array[1] + salaries[1] + ammunition[1]
q2 += fa[2] + ha[2] + ba[2] q2 += food_array[2] + salaries[2] + ammunition[2]
r1 += m1 * (100 - i1) / 20 r1 += m1 * (100 - i1) / 20
r2 += m2 * (100 - i2) / 20 r2 += m2 * (100 - i2) / 20
m3 += m1 m3 += m1
@@ -429,27 +436,27 @@ while True:
continue continue
sa[i] -= 5 sa[i] -= 5
s0 += s s0 += s
sa[y] += s0 sa[strategy_index] += s0
u = 0 u = 0
u2 = 0 u2 = 0
print("---------------") print("---------------")
continue continue
print() print()
print() print()
print() print()
print() print()
print() print()
print() print()
print(f"THE CONFEDERACY HAS WON {w} BATTLES AND LOST {l}") print(f"THE CONFEDERACY HAS WON {w} BATTLES AND LOST {line}")
if y == 5 or (y2 != 5 and w <= l): if strategy_index == 5 or (union_strategy_index != 5 and w <= line):
print("THE UNION HAS WON THE WAR") print("THE UNION HAS WON THE WAR")
else: else:
print("THE CONFEDERACY HAS WON THE WAR") print("THE CONFEDERACY HAS WON THE WAR")
print() print()
if r1 > 0: if r1 > 0:
print(f"FOR THE {w + l + w0} BATTLES FOUGHT (EXCLUDING RERUNS)") print(f"FOR THE {w + line + w0} BATTLES FOUGHT (EXCLUDING RERUNS)")
print(" \t \t ") print(" \t \t ")
print("CONFEDERACY\t UNION") print("CONFEDERACY\t UNION")
print(f"HISTORICAL LOSSES\t{math.floor(p1 + 0.5)}\t{math.floor(p2 + 0.5)}") print(f"HISTORICAL LOSSES\t{math.floor(p1 + 0.5)}\t{math.floor(p2 + 0.5)}")
@@ -463,3 +470,7 @@ if r1 > 0:
print("UNION INTELLIGENCE SUGGEST THAT THE SOUTH USED") print("UNION INTELLIGENCE SUGGEST THAT THE SOUTH USED")
print("STRATEGIES 1, 2, 3, 4 IN THE FOLLOWING PERCENTAGES") print("STRATEGIES 1, 2, 3, 4 IN THE FOLLOWING PERCENTAGES")
print(f"{sa[1]} {sa[2]} {sa[3]} {sa[4]}") print(f"{sa[1]} {sa[2]} {sa[3]} {sa[4]}")
if __name__ == "__main__":
main()

View File

@@ -34,7 +34,7 @@ def read_10_numbers():
print("TEN NUMBERS, PLEASE ? ") print("TEN NUMBERS, PLEASE ? ")
numbers = [] numbers = []
for i in range(10): for _ in range(10):
valid_input = False valid_input = False
while not valid_input: while not valid_input:
try: try:
@@ -56,7 +56,21 @@ def read_continue_choice():
return False return False
if __name__ == "__main__": def print_summary_report(running_correct: int):
print()
if running_correct > 10:
print()
print("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.")
print("I WIN." + "\u0007")
elif running_correct < 10:
print("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.")
print("YOU BEAT ME. CONGRATULATIONS *****")
else:
print("I GUESSED EXACTLY 1/3 OF YOUR NUMBERS.")
print("IT'S A TIE GAME.")
def main():
print_intro() print_intro()
if read_instruction_choice(): if read_instruction_choice():
print_instructions() print_instructions()
@@ -65,9 +79,9 @@ if __name__ == "__main__":
b = 1 b = 1
c = 3 c = 3
m = [[1] * 3 for i in range(27)] m = [[1] * 3 for _ in range(27)]
k = [[9] * 3 for i in range(3)] k = [[9] * 3 for _ in range(3)]
l = [[3] * 3 for i in range(9)] l = [[3] * 3 for _ in range(9)] # noqa: E741
continue_game = True continue_game = True
while continue_game: while continue_game:
@@ -79,7 +93,7 @@ if __name__ == "__main__":
z2 = 2 z2 = 2
running_correct = 0 running_correct = 0
for t in range(1, 4): for round in range(1, 4):
valid_numbers = False valid_numbers = False
numbers = [] numbers = []
while not valid_numbers: while not valid_numbers:
@@ -132,19 +146,11 @@ if __name__ == "__main__":
z1 = z - (z / 9) * 9 z1 = z - (z / 9) * 9
z2 = number z2 = number
# print summary report print_summary_report(running_correct)
print()
if running_correct > 10:
print()
print("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.")
print("I WIN." + "\u0007")
elif running_correct < 10:
print("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.")
print("YOU BEAT ME. CONGRATULATIONS *****")
else:
print("I GUESSED EXACTLY 1/3 OF YOUR NUMBERS.")
print("IT'S A TIE GAME.")
continue_game = read_continue_choice() continue_game = read_continue_choice()
print("\nTHANKS FOR THE GAME.") print("\nTHANKS FOR THE GAME.")
if __name__ == "__main__":
main()

View File

@@ -90,7 +90,7 @@ def to_int(s):
try: try:
n = int(s) n = int(s)
return True, n return True, n
except: except Exception:
return False, 0 return False, 0

View File

@@ -61,7 +61,7 @@ def get_fort_choice():
# try to convert the player's string input into an integer # try to convert the player's string input into an integer
try: try:
result = int(player_choice) # string to integer result = int(player_choice) # string to integer
except: except Exception:
# Whatever the player typed, it could not be interpreted as a number # Whatever the player typed, it could not be interpreted as a number
pass pass
@@ -124,7 +124,7 @@ def get_furs_purchase():
try: try:
count = int(count_str) count = int(count_str)
results.append(count) results.append(count)
except: except Exception:
# invalid input, prompt again by re-looping # invalid input, prompt again by re-looping
i -= 1 i -= 1
return results return results

View File

@@ -1,16 +1,17 @@
import random import random
from typing import List, Tuple
def print_n_whitespaces(n: int): def print_n_whitespaces(n: int) -> None:
print(" " * n, end="") print(" " * n, end="")
def print_board(): def print_board():
"""PRINT THE BOARD""" """PRINT THE BOARD"""
for I in range(N): for i in range(n):
print(" ", end="") print(" ", end="")
for J in range(N): for j in range(n):
print(A[I][J], end="") print(A[i][j], end="")
print(" ", end="") print(" ", end="")
print() print()
@@ -21,106 +22,136 @@ def check_move(_I, _J, _N) -> bool: # 910
return True return True
print_n_whitespaces(33) def print_banner():
print("GOMOKU") print_n_whitespaces(33)
print_n_whitespaces(15) print("GOMOKU")
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print_n_whitespaces(15)
print() print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print() print()
print() print()
print("WELCOME TO THE ORIENTAL GAME OF GOMOKO.") print()
print() print("WELCOME TO THE ORIENTAL GAME OF GOMOKO.")
print("THE GAME IS PLAYED ON AN N BY N GRID OF A SIZE") print()
print("THAT YOU SPECIFY. DURING YOUR PLAY, YOU MAY COVER ONE GRID") print("THE GAME IS PLAYED ON AN N BY N GRID OF A SIZE")
print("INTERSECTION WITH A MARKER. THE OBJECT OF THE GAME IS TO GET") print("THAT YOU SPECIFY. DURING YOUR PLAY, YOU MAY COVER ONE GRID")
print("5 ADJACENT MARKERS IN A ROW -- HORIZONTALLY, VERTICALLY, OR") print("INTERSECTION WITH A MARKER. THE OBJECT OF THE GAME IS TO GET")
print("DIAGONALLY. ON THE BOARD DIAGRAM, YOUR MOVES ARE MARKED") print("5 ADJACENT MARKERS IN A ROW -- HORIZONTALLY, VERTICALLY, OR")
print("WITH A '1' AND THE COMPUTER MOVES WITH A '2'.") print("DIAGONALLY. ON THE BOARD DIAGRAM, YOUR MOVES ARE MARKED")
print() print("WITH A '1' AND THE COMPUTER MOVES WITH A '2'.")
print("THE COMPUTER DOES NOT KEEP TRACK OF WHO HAS WON.") print()
print("TO END THE GAME, TYPE -1,-1 FOR YOUR MOVE.") print("THE COMPUTER DOES NOT KEEP TRACK OF WHO HAS WON.")
print() print("TO END THE GAME, TYPE -1,-1 FOR YOUR MOVE.")
print()
while True:
N = 0 def get_board_dimensions() -> int:
n = 0
while True: while True:
N = input("WHAT IS YOUR BOARD SIZE (MIN 7/ MAX 19)? ") n = input("WHAT IS YOUR BOARD SIZE (MIN 7/ MAX 19)? ")
N = int(N) n = int(n)
if N < 7 or N > 19: if n < 7 or n > 19:
print("I SAID, THE MINIMUM IS 7, THE MAXIMUM IS 19.") print("I SAID, THE MINIMUM IS 7, THE MAXIMUM IS 19.")
print() print()
else: else:
break break
return n
def get_move() -> Tuple[int, int]:
while True:
xy = input("YOUR PLAY (I,J)? ")
print()
x, y = xy.split(",")
try:
x = int(x)
y = int(y)
except Exception:
print("ILLEGAL MOVE. TRY AGAIN...")
continue
return x, y
def initialize_board(n: int) -> List[List[int]]:
# Initialize the board # Initialize the board
A = [] board = []
for I in range(N): for _x in range(n):
subA = [] subA = []
for J in range(N): for _y in range(n):
subA.append(0) subA.append(0)
A.append(subA) board.append(subA)
return board
def main():
print_banner()
while True:
n = get_board_dimensions()
board = initialize_board(n)
print() print()
print() print()
print("WE ALTERNATE MOVES. YOU GO FIRST...") print("WE ALTERNATE MOVES. YOU GO FIRST...")
print() print()
while True: while True:
IJ = input("YOUR PLAY (I,J)? ") x, y = get_move()
print() if x == -1:
I, J = IJ.split(",")
try:
I = int(I)
J = int(J)
except:
print("ILLEGAL MOVE. TRY AGAIN...")
continue
if I == -1:
break break
elif not check_move(I, J, N): elif not check_move(x, y, n):
print("ILLEGAL MOVE. TRY AGAIN...") print("ILLEGAL MOVE. TRY AGAIN...")
else: else:
if A[I - 1][J - 1] != 0: if board[x - 1][y - 1] != 0:
print("SQUARE OCCUPIED. TRY AGAIN...") print("SQUARE OCCUPIED. TRY AGAIN...")
else: else:
A[I - 1][J - 1] = 1 board[x - 1][y - 1] = 1
# COMPUTER TRIES AN INTELLIGENT MOVE # COMPUTER TRIES AN INTELLIGENT MOVE
SkipEFLoop = False skip_ef_loop = False
for E in range(-1, 2): for E in range(-1, 2):
for F in range(-1, 2): for F in range(-1, 2):
if E + F - E * F == 0 or SkipEFLoop: if E + F - E * F == 0 or skip_ef_loop:
continue continue
X = I + F X = x + F
Y = J + F Y = y + F
if not check_move(X, Y, N): if not check_move(X, Y, n):
continue continue
if A[X - 1][Y - 1] == 1: if board[X - 1][Y - 1] == 1:
SkipEFLoop = True skip_ef_loop = True
X = I - E X = x - E
Y = J - F Y = y - F
if not check_move(X, Y, N): # 750 if not check_move(X, Y, n): # 750
while True: # 610 while True: # 610
X = random.randint(1, N) X = random.randint(1, n)
Y = random.randint(1, N) Y = random.randint(1, n)
if check_move(X, Y, N) and A[X - 1][Y - 1] == 0: if (
A[X - 1][Y - 1] = 2 check_move(X, Y, n)
and board[X - 1][Y - 1] == 0
):
board[X - 1][Y - 1] = 2
print_board() print_board()
break break
else: else:
if A[X - 1][Y - 1] != 0: if board[X - 1][Y - 1] != 0:
while True: while True:
X = random.randint(1, N) X = random.randint(1, n)
Y = random.randint(1, N) Y = random.randint(1, n)
if check_move(X, Y, N) and A[X - 1][Y - 1] == 0: if (
A[X - 1][Y - 1] = 2 check_move(X, Y, n)
and board[X - 1][Y - 1] == 0
):
board[X - 1][Y - 1] = 2
print_board() print_board()
break break
else: else:
A[X - 1][Y - 1] = 2 board[X - 1][Y - 1] = 2
print_board() print_board()
print() print()
print("THANKS FOR THE GAME!!") print("THANKS FOR THE GAME!!")
Repeat = input("PLAY AGAIN (1 FOR YES, 0 FOR NO)? ") repeat = input("PLAY AGAIN (1 FOR YES, 0 FOR NO)? ")
Repeat = int(Repeat) repeat = int(repeat)
if Repeat == 0: if repeat == 0:
break break
# print_board()
if __name__ == "__main__":
main()

View File

@@ -7,44 +7,46 @@ from random import random
def gunner(): def gunner():
R = int(40000 * random() + 20000) gun_range = int(40000 * random() + 20000)
print("\nMAXIMUM RANGE OF YOUR GUN IS", R, "YARDS.") print("\nMAXIMUM RANGE OF YOUR GUN IS", gun_range, "YARDS.")
Z = 0 killed_enemies = 0
S1 = 0 S1 = 0
while True: while True:
T = int(R * (0.1 + 0.8 * random())) target_distance = int(gun_range * (0.1 + 0.8 * random()))
S = 0 shots = 0
print("\nDISTANCE TO THE TARGET IS", T, "YARDS.") print("\nDISTANCE TO THE TARGET IS", target_distance, "YARDS.")
while True: while True:
B = float(input("\n\nELEVATION? ")) elevation = float(input("\n\nELEVATION? "))
if B > 89: if elevation > 89:
print("MAXIMUM ELEVATION IS 89 DEGREES.") print("MAXIMUM ELEVATION IS 89 DEGREES.")
continue continue
if B < 1: if elevation < 1:
print("MINIMUM ELEVATION IS ONE DEGREE.") print("MINIMUM ELEVATION IS ONE DEGREE.")
continue continue
S += 1 shots += 1
if S < 6: if shots < 6:
B2 = 2 * B / 57.3 B2 = 2 * elevation / 57.3
I = R * sin(B2) shot_impact = gun_range * sin(B2)
X = T - I shot_proximity = target_distance - shot_impact
E = int(X) shot_proximity_int = int(shot_proximity)
if abs(E) < 100: if abs(shot_proximity_int) < 100:
print( print(
"*** TARGET DESTROYED *** ", S, "ROUNDS OF AMMUNITION EXPENDED." "*** TARGET DESTROYED *** ",
shots,
"ROUNDS OF AMMUNITION EXPENDED.",
) )
S1 += S S1 += shots
if Z == 4: if killed_enemies == 4:
print("\n\nTOTAL ROUNDS EXPENDED WERE: ", S1) print("\n\nTOTAL ROUNDS EXPENDED WERE: ", S1)
if S1 > 18: if S1 > 18:
print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!") print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!")
@@ -53,16 +55,16 @@ def gunner():
print("NICE SHOOTING !!") print("NICE SHOOTING !!")
return return
else: else:
Z += 1 killed_enemies += 1
print( print(
"\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..." "\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..."
) )
break break
else: else:
if E > 100: if shot_proximity_int > 100:
print("SHORT OF TARGET BY", abs(E), "YARDS.") print("SHORT OF TARGET BY", abs(shot_proximity_int), "YARDS.")
else: else:
print("OVER TARGET BY", abs(E), "YARDS.") print("OVER TARGET BY", abs(shot_proximity_int), "YARDS.")
else: else:
print("\nBOOM !!!! YOU HAVE JUST BEEN DESTROYED BY THE ENEMY.\n\n\n") print("\nBOOM !!!! YOU HAVE JUST BEEN DESTROYED BY THE ENEMY.\n\n\n")
print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!") print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!")

View File

@@ -46,143 +46,165 @@ def main():
D1 = 0 D1 = 0
P1 = 0 P1 = 0
Z = 0 # year year = 0
P = 95 # population population = 95
S = 2800 # grain stores grain_stores = 2800
H = 3000 H = 3000
E = H - S # rats eaten eaten_rats = H - grain_stores
Y = 3 # yield (amount of production from land). Reused as price per acre bushels_per_acre = (
A = H / Y # acres of land 3 # yield (amount of production from land). Reused as price per acre
I = 5 # immigrants )
Q = 1 # boolean for plague, also input for buy/sell land acres = H / bushels_per_acre # acres of land
D = 0 # people immigrants = 5
plague = 1 # boolean for plague, also input for buy/sell land
people = 0
while Z < 11: # line 270. main loop. while the year is less than 11 while year < 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 year = year + 1 # year
print("IN YEAR", Z, ",", D, "PEOPLE STARVED,", I, "CAME TO THE CITY,") print(
P = P + I "IN YEAR",
year,
",",
people,
"PEOPLE STARVED,",
immigrants,
"CAME TO THE CITY,",
)
population = population + immigrants
if Q == 0: if plague == 0:
P = int(P / 2) population = int(population / 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", population)
print("THE CITY NOW OWNS", A, "ACRES.") print("THE CITY NOW OWNS", acres, "ACRES.")
print("YOU HARVESTED", Y, "BUSHELS PER ACRE.") print("YOU HARVESTED", bushels_per_acre, "BUSHELS PER ACRE.")
print("THE RATS ATE", E, "BUSHELS.") print("THE RATS ATE", eaten_rats, "BUSHELS.")
print("YOU NOW HAVE ", S, "BUSHELS IN STORE.\n") print("YOU NOW HAVE ", grain_stores, "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 bushels_per_acre = C + 17
print("LAND IS TRADING AT", Y, "BUSHELS PER ACRE.") print("LAND IS TRADING AT", bushels_per_acre, "BUSHELS PER ACRE.")
Q = -99 # dummy value to track status plague = -99 # dummy value to track status
while Q == -99: # always run the loop once while plague == -99: # always run the loop once
Q = b_input("HOW MANY ACRES DO YOU WISH TO BUY? ") plague = b_input("HOW MANY ACRES DO YOU WISH TO BUY? ")
if Q < 0: if plague < 0:
Q = -1 # to avoid the corner case of Q=-99 plague = -1 # to avoid the corner case of Q=-99
bad_input_850() bad_input_850()
Z = 99 # jump out of main loop and exit year = 99 # jump out of main loop and exit
elif Y * Q > S: # can't afford it elif bushels_per_acre * plague > grain_stores: # can't afford it
bad_input_710(S) bad_input_710(grain_stores)
Q = -99 # give'm a second change to get it right plague = -99 # give'm a second change to get it right
elif Y * Q <= S: # normal case, can afford it elif (
A = A + Q # increase the number of acres by Q bushels_per_acre * plague <= grain_stores
S = S - Y * Q # decrease the amount of grain in store to pay for it ): # normal case, can afford it
acres = acres + plague # increase the number of acres by Q
grain_stores = (
grain_stores - bushels_per_acre * plague
) # 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? if plague == 0 and year != 99: # maybe you want to sell some land?
Q = -99 plague = -99
while Q == -99: while plague == -99:
Q = b_input("HOW MANY ACRES DO YOU WISH TO SELL? ") plague = b_input("HOW MANY ACRES DO YOU WISH TO SELL? ")
if Q < 0: if plague < 0:
bad_input_850() bad_input_850()
Z = 99 # jump out of main loop and exit year = 99 # jump out of main loop and exit
elif Q <= A: # normal case elif plague <= acres: # normal case
A = A - Q # reduce the acres acres = acres - plague # reduce the acres
S = S + Y * Q # add to grain stores grain_stores = (
grain_stores + bushels_per_acre * plague
) # add to grain stores
C = 0 # still don't know what C is for C = 0 # still don't know what C is for
else: # Q>A error! else: # Q>A error!
bad_input_720(A) bad_input_720(acres)
Q = -99 # reloop plague = -99 # reloop
print("\n") print("\n")
Q = -99 plague = -99
while Q == -99 and Z != 99: while plague == -99 and year != 99:
Q = b_input("HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? ") plague = b_input("HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? ")
if Q < 0: if plague < 0:
bad_input_850() bad_input_850()
Z = 99 # jump out of main loop and exit year = 99 # jump out of main loop and exit
# REM *** TRYING TO USE MORE GRAIN THAN IS IN SILOS? # REM *** TRYING TO USE MORE GRAIN THAN IS IN SILOS?
elif Q > S: elif plague > grain_stores:
bad_input_710(S) bad_input_710(grain_stores)
Q = -99 # try again! plague = -99 # try again!
else: # we're good. do the transaction else: # we're good. do the transaction
S = S - Q # remove the grain from the stores grain_stores = grain_stores - plague # remove the grain from the stores
C = 1 # set the speed of light to 1. jk C = 1 # set the speed of light to 1. jk
print("\n") print("\n")
D = -99 # dummy value to force at least one loop people = -99 # dummy value to force at least one loop
while D == -99 and Z != 99: while people == -99 and year != 99:
D = b_input("HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? ") people = b_input("HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? ")
if D < 0: if people < 0:
bad_input_850() bad_input_850()
Z = 99 # jump out of main loop and exit year = 99 # jump out of main loop and exit
elif D > 0: elif people > 0:
if D > A: if people > acres:
# REM *** TRYING TO PLANT MORE ACRES THAN YOU OWN? # REM *** TRYING TO PLANT MORE ACRES THAN YOU OWN?
bad_input_720(A) bad_input_720(acres)
D = -99 people = -99
elif int(D / 2) > S: elif int(people / 2) > grain_stores:
# REM *** ENOUGH GRAIN FOR SEED? # REM *** ENOUGH GRAIN FOR SEED?
bad_input_710(S) bad_input_710(grain_stores)
D = -99 people = -99
elif D > 10 * P: elif people > 10 * population:
# REM *** ENOUGH PEOPLE TO TEND THE CROPS? # REM *** ENOUGH PEOPLE TO TEND THE CROPS?
print( print(
"BUT YOU HAVE ONLY", P, "PEOPLE TO TEND THE FIELDS! NOW THEN," "BUT YOU HAVE ONLY",
population,
"PEOPLE TO TEND THE FIELDS! NOW THEN,",
) )
D = -99 people = -99
else: # we're good. decrement the grain store else: # we're good. decrement the grain store
S = S - int(D / 2) grain_stores = grain_stores - int(people / 2)
C = gen_random() C = gen_random()
# REM *** A BOUNTIFUL HARVEST! # REM *** A BOUNTIFUL HARVEST!
Y = C bushels_per_acre = C
H = D * Y H = people * bushels_per_acre
E = 0 eaten_rats = 0
C = gen_random() C = gen_random()
if int(C / 2) == C / 2: # even number. 50/50 chance if int(C / 2) == C / 2: # even number. 50/50 chance
# REM *** RATS ARE RUNNING WILD!! # REM *** RATS ARE RUNNING WILD!!
E = int(S / C) # calc losses due to rats, based on previous random number eaten_rats = int(
grain_stores / C
) # calc losses due to rats, based on previous random number
S = S - E + H # deduct losses from stores grain_stores = grain_stores - eaten_rats + H # deduct losses from stores
C = gen_random() C = gen_random()
# REM *** LET'S HAVE SOME BABIES # REM *** LET'S HAVE SOME BABIES
I = int(C * (20 * A + S) / P / 100 + 1) immigrants = int(C * (20 * acres + grain_stores) / population / 100 + 1)
# REM *** HOW MANY PEOPLE HAD FULL TUMMIES? # REM *** HOW MANY PEOPLE HAD FULL TUMMIES?
C = int(Q / 20) C = int(plague / 20)
# REM *** HORROS, A 15% CHANCE OF PLAGUE # REM *** HORROS, A 15% CHANCE OF PLAGUE
# yeah, should be HORRORS, but left it # yeah, should be HORRORS, but left it
Q = int(10 * (2 * random() - 0.3)) plague = int(10 * (2 * random() - 0.3))
if P >= C and Z != 99: # if there are some people without full bellies... if (
population >= C and year != 99
): # if there are some people without full bellies...
# REM *** STARVE ENOUGH FOR IMPEACHMENT? # REM *** STARVE ENOUGH FOR IMPEACHMENT?
D = P - C people = population - C
if D > 0.45 * P: if people > 0.45 * population:
print("\nYOU STARVED", D, "PEOPLE IN ONE YEAR!!!") print("\nYOU STARVED", people, "PEOPLE IN ONE YEAR!!!")
national_fink() national_fink()
Z = 99 # exit the loop year = 99 # exit the loop
P1 = ((Z - 1) * P1 + D * 100 / P) / Z P1 = ((year - 1) * P1 + people * 100 / population) / year
P = C population = C
D1 = D1 + D D1 = D1 + people
if Z != 99: if year != 99:
print("IN YOUR 10-YEAR TERM OF OFFICE,", P1, "PERCENT OF THE") 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("POPULATION STARVED PER YEAR ON THE AVERAGE, I.E. A TOTAL OF")
print(D1, "PEOPLE DIED!!") print(D1, "PEOPLE DIED!!")
L = A / P L = acres / population
print("YOU STARTED WITH 10 ACRES PER PERSON AND ENDED WITH") print("YOU STARTED WITH 10 ACRES PER PERSON AND ENDED WITH")
print(L, "ACRES PER PERSON.\n") print(L, "ACRES PER PERSON.\n")
if P1 > 33 or L < 7: if P1 > 33 or L < 7:
@@ -193,7 +215,11 @@ def main():
print("FRANKLY, HATE YOUR GUTS!!") print("FRANKLY, HATE YOUR GUTS!!")
elif P1 > 3 or L < 10: elif P1 > 3 or L < 10:
print("YOUR PERFORMANCE COULD HAVE BEEN SOMEWHAT BETTER, BUT") print("YOUR PERFORMANCE COULD HAVE BEEN SOMEWHAT BETTER, BUT")
print("REALLY WASN'T TOO BAD AT ALL. ", int(P * 0.8 * random()), "PEOPLE") print(
"REALLY WASN'T TOO BAD AT ALL. ",
int(population * 0.8 * random()),
"PEOPLE",
)
print("WOULD DEARLY LIKE TO SEE YOU ASSASSINATED BUT WE ALL HAVE OUR") print("WOULD DEARLY LIKE TO SEE YOU ASSASSINATED BUT WE ALL HAVE OUR")
print("TRIVIAL PROBLEMS.") print("TRIVIAL PROBLEMS.")
else: else:

View File

@@ -166,12 +166,12 @@ def print_race_state(total_distance, race_pos):
basic_print("XXXXSTARTXXXX") basic_print("XXXXSTARTXXXX")
# print all 28 lines/unit of the race course # print all 28 lines/unit of the race course
for l in range(28): for line in range(28):
# ensure we still have a horse to print and if so, check if the # ensure we still have a horse to print and if so, check if the
# next horse to print is not the current line # next horse to print is not the current line
# needs iteration, since multiple horses can share the same line # needs iteration, since multiple horses can share the same line
while next_pos is not None and l == total_distance[next_pos]: while next_pos is not None and line == total_distance[next_pos]:
basic_print(f"{next_pos} ", end="") basic_print(f"{next_pos} ", end="")
next_pos = next(race_pos_iter, None) next_pos = next(race_pos_iter, None)
else: else:
@@ -209,8 +209,8 @@ def simulate_race(odds):
# in the original implementation, race_pos is reset for each # in the original implementation, race_pos is reset for each
# simulation step, so we keep this behaviour here # simulation step, so we keep this behaviour here
race_pos = list(range(num_horses)) race_pos = list(range(num_horses))
for l in range(num_horses): for line in range(num_horses):
for i in range(num_horses - 1 - l): for i in range(num_horses - 1 - line):
if total_distance[race_pos[i]] < total_distance[race_pos[i + 1]]: if total_distance[race_pos[i]] < total_distance[race_pos[i + 1]]:
continue continue
race_pos[i], race_pos[i + 1] = race_pos[i + 1], race_pos[i] race_pos[i], race_pos[i + 1] = race_pos[i + 1], race_pos[i]

View File

@@ -65,7 +65,7 @@ def query_bets():
while betCount <= 0: while betCount <= 0:
try: try:
betCount = int(input("HOW MANY BETS? ")) betCount = int(input("HOW MANY BETS? "))
except: except Exception:
... ...
bet_IDs = [-1] * betCount bet_IDs = [-1] * betCount
@@ -87,7 +87,7 @@ def query_bets():
if id > 0 and id <= 50 and val >= 5 and val <= 500: if id > 0 and id <= 50 and val >= 5 and val <= 500:
bet_IDs[i] = id bet_IDs[i] = id
bet_Values[i] = val bet_Values[i] = val
except: except Exception:
... ...
return bet_IDs, bet_Values return bet_IDs, bet_Values

View File

@@ -86,7 +86,7 @@ class Stock_Market:
for stock in self.data.keys(): for stock in self.data.keys():
try: try:
new_holdings.append(int(input(f"{stock}? "))) new_holdings.append(int(input(f"{stock}? ")))
except: except Exception:
print("\nINVALID ENTRY, TRY AGAIN\n") print("\nINVALID ENTRY, TRY AGAIN\n")
break break
if len(new_holdings) == 5: if len(new_holdings) == 5:

View File

@@ -324,6 +324,10 @@ def long_range_scan():
return return
print(f"LONG RANGE SCAN FOR QUADRANT {q1 + 1} , {q2 + 1}") print(f"LONG RANGE SCAN FOR QUADRANT {q1 + 1} , {q2 + 1}")
print_scan_results(q1, q2)
def print_scan_results(q1: int, q2: int) -> None:
sep = "-------------------" sep = "-------------------"
print(sep) print(sep)
for i in (q1 - 1, q1, q1 + 1): for i in (q1 - 1, q1, q1 + 1):
@@ -335,11 +339,11 @@ def long_range_scan():
z[i][j] = g[i][j] z[i][j] = g[i][j]
line = ": " line = ": "
for l in range(3): for line_index in range(3):
if n[l] < 0: if n[line_index] < 0:
line += "*** : " line += "*** : "
else: else:
line += str(n[l] + 1000).rjust(4, " ")[-3:] + " : " line += str(n[line_index] + 1000).rjust(4, " ")[-3:] + " : "
print(line) print(line)
print(sep) print(sep)
@@ -364,9 +368,9 @@ def phaser_control():
x = 0 x = 0
while True: while True:
while True: while True:
xs = input("NUMBER OF UNITS TO FIRE? ") units_to_fire = input("NUMBER OF UNITS TO FIRE? ")
if len(xs) > 0: if len(units_to_fire) > 0:
x = int(xs) x = int(units_to_fire)
break break
if x <= 0: if x <= 0:
return return
@@ -422,9 +426,9 @@ def photon_torpedoes():
return return
while True: while True:
c1s = input("PHOTON TORPEDO COURSE (1-9)? ") torpedo_course = input("PHOTON TORPEDO COURSE (1-9)? ")
if len(c1s) > 0: if len(torpedo_course) > 0:
c1 = float(c1s) c1 = float(torpedo_course)
break break
if c1 == 9: if c1 == 9:
c1 = 1 c1 = 1
@@ -530,9 +534,11 @@ def shield_control():
return return
while True: while True:
xs = input(f"ENERGY AVAILABLE = {e + s} NUMBER OF UNITS TO SHIELDS? ") energy_to_shield = input(
if len(xs) > 0: f"ENERGY AVAILABLE = {e + s} NUMBER OF UNITS TO SHIELDS? "
x = int(xs) )
if len(energy_to_shield) > 0:
x = int(energy_to_shield)
break break
if x < 0 or s == x: if x < 0 or s == x:
@@ -577,7 +583,7 @@ def damage_control():
d3 = 0.9 d3 = 0.9
print("\nTECHNICIANS STANDING BY TO EFFECT REPAIRS TO YOUR SHIP;") print("\nTECHNICIANS STANDING BY TO EFFECT REPAIRS TO YOUR SHIP;")
print("ESTIMATED TIME TO REPAIR: " f"{round(0.01 * int(100 * d3), 2)} STARDATES") print("ESTIMATED TIME TO REPAIR: " f"{round(0.01 * int(100 * d3), 2)} STARDATES")
if input("WILL YOU AUTHORIZE THE " "REPAIR ORDER (Y/N)? ").upper().strip() != "Y": if input("WILL YOU AUTHORIZE THE REPAIR ORDER (Y/N)? ").upper().strip() != "Y":
return return
for i in range(8): for i in range(8):
@@ -595,11 +601,11 @@ def computer():
return return
while True: while True:
coms = input("COMPUTER ACTIVE AND AWAITING COMMAND? ") command = input("COMPUTER ACTIVE AND AWAITING COMMAND? ")
if len(coms) == 0: if len(command) == 0:
com = 6 com = 6
else: else:
com = int(coms) com = int(command)
if com < 0: if com < 0:
return return
@@ -691,15 +697,15 @@ def computer():
print(f"YOU ARE AT QUADRANT {q1+1} , {q2+1} SECTOR " f"{s1+1} , {s2+1}") print(f"YOU ARE AT QUADRANT {q1+1} , {q2+1} SECTOR " f"{s1+1} , {s2+1}")
print("PLEASE ENTER") print("PLEASE ENTER")
while True: while True:
ins = input(" INITIAL COORDINATES (X,Y)? ").split(",") coordinates = input(" INITIAL COORDINATES (X,Y)? ").split(",")
if len(ins) == 2: if len(coordinates) == 2:
from1, from2 = int(ins[0]) - 1, int(ins[1]) - 1 from1, from2 = int(coordinates[0]) - 1, int(coordinates[1]) - 1
if 0 <= from1 <= 7 and 0 <= from2 <= 7: if 0 <= from1 <= 7 and 0 <= from2 <= 7:
break break
while True: while True:
ins = input(" FINAL COORDINATES (X,Y)? ").split(",") coordinates = input(" FINAL COORDINATES (X,Y)? ").split(",")
if len(ins) == 2: if len(coordinates) == 2:
to1, to2 = int(ins[0]) - 1, int(ins[1]) - 1 to1, to2 = int(coordinates[0]) - 1, int(coordinates[1]) - 1
if 0 <= to1 <= 7 and 0 <= to2 <= 7: if 0 <= to1 <= 7 and 0 <= to2 <= 7:
break break
print_direction(from1, from2, to1, to2) print_direction(from1, from2, to1, to2)

View File

@@ -4,11 +4,11 @@
# #
# Converted from BASIC to Python by Trevor Hobson # Converted from BASIC to Python by Trevor Hobson
import math from math import exp, floor, sqrt
def equation(input): def equation(x: float) -> float:
return 30 * math.exp(-input * input / 100) return 30 * exp(-x * x / 100)
print(" " * 32 + "3D PLOT") print(" " * 32 + "3D PLOT")
@@ -16,13 +16,13 @@ print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n\n")
for x in range(-300, 315, 15): for x in range(-300, 315, 15):
x1 = x / 10 x1 = x / 10
l = 0 max_column = 0
y1 = 5 * math.floor(math.sqrt(900 - x1 * x1) / 5) y1 = 5 * floor(sqrt(900 - x1 * x1) / 5)
yPlot = [" "] * 80 y_plot = [" "] * 80
for y in range(y1, -(y1 + 5), -5): for y in range(y1, -(y1 + 5), -5):
z = math.floor(25 + equation(math.sqrt(x1 * x1 + y * y)) - 0.7 * y) column = floor(25 + equation(sqrt(x1 * x1 + y * y)) - 0.7 * y)
if z > l: if column > max_column:
l = z max_column = column
yPlot[z] = "*" y_plot[column] = "*"
print("".join(yPlot)) print("".join(y_plot))

View File

@@ -99,7 +99,7 @@ class Game:
while which is None: while which is None:
try: try:
which = self.which_disk() which = self.which_disk()
except: except Exception:
print("ILLEGAL ENTRY... YOU MAY ONLY TYPE 3,5,7,9,11,13, OR 15.\n") print("ILLEGAL ENTRY... YOU MAY ONLY TYPE 3,5,7,9,11,13, OR 15.\n")
valids = [t for t in self.__towers if t.top() and t.top().size() == which] valids = [t for t in self.__towers if t.top() and t.top().size() == which]
@@ -115,7 +115,7 @@ class Game:
try: try:
needle = int(input("PLACE DISK ON WHICH NEEDLE\n")) needle = int(input("PLACE DISK ON WHICH NEEDLE\n"))
tower = self.__towers[needle - 1] tower = self.__towers[needle - 1]
except: except Exception:
print( print(
"I'LL ASSUME YOU HIT THE WRONG KEY THIS TIME. BUT WATCH IT,\nI ONLY ALLOW ONE MISTAKE.\n" "I'LL ASSUME YOU HIT THE WRONG KEY THIS TIME. BUT WATCH IT,\nI ONLY ALLOW ONE MISTAKE.\n"
) )