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
- name: Test with flake8
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="")
try:
self.shot = int(input())
except:
except Exception:
continue
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):
t = [0] * 20 # time of each bounce
bounce_time = [0] * 20 # time of each bounce
print("FEET")
print()
sim_dur = int(70 / (v0 / (16 * delta_t)))
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
h = int(-16 * (v0 / 32) ** 2 + v0**2 / 32 + 0.5)
@@ -66,32 +66,32 @@ def run_simulation(delta_t, v0, coeff_rest):
line = ""
if int(h) == h:
line += str(int(h))
l = 0
total_time = 0
for i in range(1, sim_dur + 1):
tm = 0
while tm <= t[i]:
l += delta_t
while tm <= bounce_time[i]:
total_time += delta_t
if (
abs(h - (0.5 * (-32) * tm**2 + v0 * coeff_rest ** (i - 1) * tm))
<= 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 = t[i + 1] / 2
tm = bounce_time[i + 1] / 2
if -16 * tm**2 + v0 * coeff_rest ** (i - 1) * tm < h:
break
print(line)
h = h - 0.5
print("." * (int((l + 1) / delta_t) + 1))
print("." * (int((total_time + 1) / delta_t) + 1))
print
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))
print(line)
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()

View File

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

View File

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

View File

@@ -1,465 +1,476 @@
import math
import random
from typing import List
def tab(n):
def tab(n: int) -> str:
return " " * n
battles = [
[
"JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET",
"UNION FORCES WITH GEN. MCDOWELL IN A PREMATURE BATTLE AT",
"BULL RUN. GEN. JACKSON HELPED PUSH BACK THE UNION ATTACK.",
],
[
"APRIL 6-7, 1862. THE CONFEDERATE SURPRISE ATTACK AT",
"SHILOH FAILED DUE TO POOR ORGANIZATION.",
],
[
"JUNE 25-JULY 1, 1862. GENERAL LEE (CSA) UPHELD THE",
"OFFENSIVE THROUGHOUT THE BATTLE AND FORCED GEN. MCCLELLAN",
"AND THE UNION FORCES AWAY FROM RICHMOND.",
],
[
"AUG 29-30, 1862. THE COMBINED CONFEDERATE FORCES UNDER LEE",
"AND JACKSON DROVE THE UNION FORCES BACK INTO WASHINGTON.",
],
[
"SEPT 17, 1862. THE SOUTH FAILED TO INCORPORATE MARYLAND",
"INTO THE CONFEDERACY.",
],
[
"DEC 13, 1862. THE CONFEDERACY UNDER LEE SUCCESSFULLY",
"REPULSED AN ATTACK BY THE UNION UNDER GEN. BURNSIDE.",
],
["DEC 31, 1862. THE SOUTH UNDER GEN. BRAGG WON A CLOSE BATTLE."],
[
"MAY 1-6, 1863. THE SOUTH HAD A COSTLY VICTORY AND LOST",
"ONE OF THEIR OUTSTANDING GENERALS, 'STONEWALL' JACKSON.",
],
[
"JULY 4, 1863. VICKSBURG WAS A COSTLY DEFEAT FOR THE SOUTH",
"BECAUSE IT GAVE THE UNION ACCESS TO THE MISSISSIPPI.",
],
[
"JULY 1-3, 1863. A SOUTHERN MISTAKE BY GEN. LEE AT GETTYSBURG",
"COST THEM ONE OF THE MOST CRUCIAL BATTLES OF THE WAR.",
],
[
"SEPT. 15, 1863. CONFUSION IN A FOREST NEAR CHICKAMAUGA LED",
"TO A COSTLY SOUTHERN VICTORY.",
],
[
"NOV. 25, 1863. AFTER THE SOUTH HAD SIEGED GEN. ROSENCRANS'",
"ARMY FOR THREE MONTHS, GEN. GRANT BROKE THE SIEGE.",
],
[
"MAY 5, 1864. GRANT'S PLAN TO KEEP LEE ISOLATED BEGAN TO",
"FAIL HERE, AND CONTINUED AT COLD HARBOR AND PETERSBURG.",
],
[
"AUGUST, 1864. SHERMAN AND THREE VETERAN ARMIES CONVERGED",
"ON ATLANTA AND DEALT THE DEATH BLOW TO THE CONFEDERACY.",
],
]
def get_choice(prompt: str, choices: List[str]) -> str:
while True:
choice = input(prompt)
if choice in choices:
break
return choice
historical_data = [
[],
["BULL RUN", 18000, 18500, 1967, 2708, 1],
["SHILOH", 40000.0, 44894.0, 10699, 13047, 3],
["SEVEN DAYS", 95000.0, 115000.0, 20614, 15849, 3],
["SECOND BULL RUN", 54000.0, 63000.0, 10000, 14000, 2],
["ANTIETAM", 40000.0, 50000.0, 10000, 12000, 3],
["FREDERICKSBURG", 75000.0, 120000.0, 5377, 12653, 1],
["MURFREESBORO", 38000.0, 45000.0, 11000, 12000, 1],
["CHANCELLORSVILLE", 32000, 90000.0, 13000, 17197, 2],
["VICKSBURG", 50000.0, 70000.0, 12000, 19000, 1],
["GETTYSBURG", 72500.0, 85000.0, 20000, 23000, 3],
["CHICKAMAUGA", 66000.0, 60000.0, 18000, 16000, 2],
["CHATTANOOGA", 37000.0, 60000.0, 36700.0, 5800, 2],
["SPOTSYLVANIA", 62000.0, 110000.0, 17723, 18000, 2],
["ATLANTA", 65000.0, 100000.0, 8500, 3700, 1],
]
sa = {}
da = {}
fa = {}
ha = {}
ba = {}
oa = {}
print(tab(26) + "CIVIL WAR")
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
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
sa[1] = 25
sa[2] = 25
sa[3] = 25
sa[4] = 25
d = -1 # number of players in the game
print()
while True:
X = input("DO YOU WANT INSTRUCTIONS? ")
if X == "YES" or X == "NO":
break
print("YES OR NO -- ")
if X == "YES":
print()
print()
print()
print()
print("THIS IS A CIVIL WAR SIMULATION.")
print("TO PLAY TYPE A RESPONSE WHEN THE COMPUTER ASKS.")
print("REMEMBER THAT ALL FACTORS ARE INTERRELATED AND THAT YOUR")
print("RESPONSES COULD CHANGE HISTORY. FACTS AND FIGURES USED ARE")
print("BASED ON THE ACTUAL OCCURRENCE. MOST BATTLES TEND TO RESULT")
print("AS THEY DID IN THE CIVIL WAR, BUT IT ALL DEPENDS ON YOU!!")
print()
print("THE OBJECT OF THE GAME IS TO WIN AS MANY BATTLES AS ")
print("POSSIBLE.")
print()
print("YOUR CHOICES FOR DEFENSIVE STRATEGY ARE:")
print(" (1) ARTILLERY ATTACK")
print(" (2) FORTIFICATION AGAINST FRONTAL ATTACK")
print(" (3) FORTIFICATION AGAINST FLANKING MANEUVERS")
print(" (4) FALLING BACK")
print(" YOUR CHOICES FOR OFFENSIVE STRATEGY ARE:")
print(" (1) ARTILLERY ATTACK")
print(" (2) FRONTAL ATTACK")
print(" (3) FLANKING MANEUVERS")
print(" (4) ENCIRCLEMENT")
print("YOU MAY SURRENDER BY TYPING A '5' FOR YOUR STRATEGY.")
def main():
battles = [
[
"JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET",
"UNION FORCES WITH GEN. MCDOWELL IN A PREMATURE BATTLE AT",
"BULL RUN. GEN. JACKSON HELPED PUSH BACK THE UNION ATTACK.",
],
[
"APRIL 6-7, 1862. THE CONFEDERATE SURPRISE ATTACK AT",
"SHILOH FAILED DUE TO POOR ORGANIZATION.",
],
[
"JUNE 25-JULY 1, 1862. GENERAL LEE (CSA) UPHELD THE",
"OFFENSIVE THROUGHOUT THE BATTLE AND FORCED GEN. MCCLELLAN",
"AND THE UNION FORCES AWAY FROM RICHMOND.",
],
[
"AUG 29-30, 1862. THE COMBINED CONFEDERATE FORCES UNDER LEE",
"AND JACKSON DROVE THE UNION FORCES BACK INTO WASHINGTON.",
],
[
"SEPT 17, 1862. THE SOUTH FAILED TO INCORPORATE MARYLAND",
"INTO THE CONFEDERACY.",
],
[
"DEC 13, 1862. THE CONFEDERACY UNDER LEE SUCCESSFULLY",
"REPULSED AN ATTACK BY THE UNION UNDER GEN. BURNSIDE.",
],
["DEC 31, 1862. THE SOUTH UNDER GEN. BRAGG WON A CLOSE BATTLE."],
[
"MAY 1-6, 1863. THE SOUTH HAD A COSTLY VICTORY AND LOST",
"ONE OF THEIR OUTSTANDING GENERALS, 'STONEWALL' JACKSON.",
],
[
"JULY 4, 1863. VICKSBURG WAS A COSTLY DEFEAT FOR THE SOUTH",
"BECAUSE IT GAVE THE UNION ACCESS TO THE MISSISSIPPI.",
],
[
"JULY 1-3, 1863. A SOUTHERN MISTAKE BY GEN. LEE AT GETTYSBURG",
"COST THEM ONE OF THE MOST CRUCIAL BATTLES OF THE WAR.",
],
[
"SEPT. 15, 1863. CONFUSION IN A FOREST NEAR CHICKAMAUGA LED",
"TO A COSTLY SOUTHERN VICTORY.",
],
[
"NOV. 25, 1863. AFTER THE SOUTH HAD SIEGED GEN. ROSENCRANS'",
"ARMY FOR THREE MONTHS, GEN. GRANT BROKE THE SIEGE.",
],
[
"MAY 5, 1864. GRANT'S PLAN TO KEEP LEE ISOLATED BEGAN TO",
"FAIL HERE, AND CONTINUED AT COLD HARBOR AND PETERSBURG.",
],
[
"AUGUST, 1864. SHERMAN AND THREE VETERAN ARMIES CONVERGED",
"ON ATLANTA AND DEALT THE DEATH BLOW TO THE CONFEDERACY.",
],
]
print()
print()
print()
print("ARE THERE TWO GENERALS PRESENT ", end="")
while True:
bs = input("(ANSWER YES OR NO) ")
historical_data = [
[],
["BULL RUN", 18000, 18500, 1967, 2708, 1],
["SHILOH", 40000.0, 44894.0, 10699, 13047, 3],
["SEVEN DAYS", 95000.0, 115000.0, 20614, 15849, 3],
["SECOND BULL RUN", 54000.0, 63000.0, 10000, 14000, 2],
["ANTIETAM", 40000.0, 50000.0, 10000, 12000, 3],
["FREDERICKSBURG", 75000.0, 120000.0, 5377, 12653, 1],
["MURFREESBORO", 38000.0, 45000.0, 11000, 12000, 1],
["CHANCELLORSVILLE", 32000, 90000.0, 13000, 17197, 2],
["VICKSBURG", 50000.0, 70000.0, 12000, 19000, 1],
["GETTYSBURG", 72500.0, 85000.0, 20000, 23000, 3],
["CHICKAMAUGA", 66000.0, 60000.0, 18000, 16000, 2],
["CHATTANOOGA", 37000.0, 60000.0, 36700.0, 5800, 2],
["SPOTSYLVANIA", 62000.0, 110000.0, 17723, 18000, 2],
["ATLANTA", 65000.0, 100000.0, 8500, 3700, 1],
]
sa = {}
dollars_available = {}
food_array = {}
salaries = {}
ammunition = {}
oa = {}
print(tab(26) + "CIVIL WAR")
print(tab(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
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
sa[1] = 25
sa[2] = 25
sa[3] = 25
sa[4] = 25
party = -1 # number of players in the game
print()
show_instructions = get_choice(
"DO YOU WANT INSTRUCTIONS? YES OR NO -- ", ["YES", "NO"]
)
if show_instructions == "YES":
print()
print()
print()
print()
print("THIS IS A CIVIL WAR SIMULATION.")
print("TO PLAY TYPE A RESPONSE WHEN THE COMPUTER ASKS.")
print("REMEMBER THAT ALL FACTORS ARE INTERRELATED AND THAT YOUR")
print("RESPONSES COULD CHANGE HISTORY. FACTS AND FIGURES USED ARE")
print("BASED ON THE ACTUAL OCCURRENCE. MOST BATTLES TEND TO RESULT")
print("AS THEY DID IN THE CIVIL WAR, BUT IT ALL DEPENDS ON YOU!!")
print()
print("THE OBJECT OF THE GAME IS TO WIN AS MANY BATTLES AS ")
print("POSSIBLE.")
print()
print("YOUR CHOICES FOR DEFENSIVE STRATEGY ARE:")
print(" (1) ARTILLERY ATTACK")
print(" (2) FORTIFICATION AGAINST FRONTAL ATTACK")
print(" (3) FORTIFICATION AGAINST FLANKING MANEUVERS")
print(" (4) FALLING BACK")
print(" YOUR CHOICES FOR OFFENSIVE STRATEGY ARE:")
print(" (1) ARTILLERY ATTACK")
print(" (2) FRONTAL ATTACK")
print(" (3) FLANKING MANEUVERS")
print(" (4) ENCIRCLEMENT")
print("YOU MAY SURRENDER BY TYPING A '5' FOR YOUR STRATEGY.")
print()
print()
print()
print("ARE THERE TWO GENERALS PRESENT ", end="")
bs = get_choice("(ANSWER YES OR NO) ", ["YES", "NO"])
if bs == "YES":
d = 2
break
party = 2
elif bs == "NO":
d = 1
party = 1
print()
print("YOU ARE THE CONFEDERACY. GOOD LUCK!")
print()
break
print("SELECT A BATTLE BY TYPING A NUMBER FROM 1 TO 14 ON")
print("REQUEST. TYPE ANY OTHER NUMBER TO END THE SIMULATION.")
print("BUT '0' BRINGS BACK EXACT PREVIOUS BATTLE SITUATION")
print("ALLOWING YOU TO REPLAY IT")
print()
print("NOTE: A NEGATIVE FOOD$ ENTRY CAUSES THE PROGRAM TO ")
print("USE THE ENTRIES FROM THE PREVIOUS BATTLE")
print()
print("AFTER REQUESTING A BATTLE, DO YOU WISH ", end="")
print("BATTLE DESCRIPTIONS ", end="")
while True:
xs = input("(ANSWER YES OR NO) ")
if xs == "YES" or xs == "NO":
break
l = 0
w = 0
r1 = 0
q1 = 0
m3 = 0
m4 = 0
p1 = 0
p2 = 0
t1 = 0
t2 = 0
for i in range(1, 3):
da[i] = 0
fa[i] = 0
ha[i] = 0
ba[i] = 0
oa[i] = 0
r2 = 0
q2 = 0
c6 = 0
f = 0
w0 = 0
y = 0
y2 = 0
u = 0
u2 = 0
while True:
print("SELECT A BATTLE BY TYPING A NUMBER FROM 1 TO 14 ON")
print("REQUEST. TYPE ANY OTHER NUMBER TO END THE SIMULATION.")
print("BUT '0' BRINGS BACK EXACT PREVIOUS BATTLE SITUATION")
print("ALLOWING YOU TO REPLAY IT")
print()
print("NOTE: A NEGATIVE FOOD$ ENTRY CAUSES THE PROGRAM TO ")
print("USE THE ENTRIES FROM THE PREVIOUS BATTLE")
print()
print()
a = int(input("WHICH BATTLE DO YOU WISH TO SIMULATE? "))
if a < 1 or a > 14:
break
if a != 0 or r == 0:
cs = historical_data[a][0]
m1 = historical_data[a][1]
m2 = historical_data[a][2]
c1 = historical_data[a][3]
c2 = historical_data[a][4]
m = historical_data[a][5]
u = 0
# Inflation calc
i1 = 10 + (l - w) * 2
i2 = 10 + (w - l) * 2
# Money available
da[1] = 100 * math.floor(
(m1 * (100 - i1) / 2000) * (1 + (r1 - q1) / (r1 + 1)) + 0.5
)
da[2] = 100 * math.floor(m2 * (100 - i2) / 2000 + 0.5)
if bs == "YES":
da[2] = 100 * math.floor(
(m2 * (100 - i2) / 2000) * (1 + (r2 - q2) / (r2 + 1)) + 0.5
)
# Men available
m5 = math.floor(m1 * (1 + (p1 - t1) / (m3 + 1)))
m6 = math.floor(m2 * (1 + (p2 - t2) / (m4 + 1)))
f1 = 5 * m1 / 6
print()
print()
print()
print()
print()
print(f"THIS IS THE BATTLE OF {cs}")
if xs != "NO":
print("\n".join(battles[a - 1]))
else:
print(cs + " INSTANT REPLAY")
print()
print(" \tCONFEDERACY\t UNION")
print(f"MEN\t {m5}\t\t {m6}")
print(f"MONEY\t ${da[1]}\t\t${da[2]}")
print(f"INFLATION\t {i1 + 15}%\t {i2}%")
print()
# ONLY IN PRINTOUT IS CONFED INFLATION = I1 + 15 %
# IF TWO GENERALS, INPUT CONFED, FIRST
for i in range(1, d + 1):
if bs == "YES" and i == 1:
print("CONFEDERATE GENERAL---", end="")
print("HOW MUCH DO YOU WISH TO SPEND FOR")
while True:
f = int(input(" - FOOD...... ? "))
if f < 0:
if r1 == 0:
print("NO PREVIOUS ENTRIES")
continue
print("ASSUME YOU WANT TO KEEP SAME ALLOCATIONS")
print()
break
fa[i] = f
while True:
ha[i] = int(input(" - SALARIES.. ? "))
if ha[i] >= 0:
break
print("NEGATIVE VALUES NOT ALLOWED.")
while True:
ba[i] = int(input(" - AMMUNITION ? "))
if ba[i] >= 0:
break
print("NEGATIVE VALUES NOT ALLOWED.")
print()
if fa[i] + ha[i] + ba[i] > da[i]:
print("THINK AGAIN! YOU HAVE ONLY $" + da[i])
else:
break
if bs != "YES" or i == 2:
break
print("UNION GENERAL---", end="")
for z in range(1, d + 1):
if bs == "YES":
if z == 1:
print("CONFEDERATE ", end="")
else:
print(" UNION ", end="")
# Find morale
o = (2 * math.pow(fa[z], 2) + math.pow(ha[z], 2)) / math.pow(f1, 2) + 1
if o >= 10:
print("MORALE IS HIGH")
elif o >= 5:
print("MORALE IS FAIR")
else:
print("MORALE IS POOR")
if bs != "YES":
break
oa[z] = o
o2 = oa[2]
o = oa[1]
print("CONFEDERATE GENERAL---")
# Actual off/def battle situation
if m == 3:
print("YOU ARE ON THE OFFENSIVE")
elif m == 1:
print("YOU ARE ON THE DEFENSIVE")
else:
print("BOTH SIDES ARE ON THE OFFENSIVE")
print()
# Choose strategies
if bs != "YES":
while True:
y = int(input("YOUR STRATEGY "))
if abs(y - 3) < 3:
break
print(f"STRATEGY {y} NOT ALLOWED.")
if y == 5:
print("THE CONFEDERACY HAS SURRENDERED.")
break
# Union strategy is computer chosen
if a == 0:
while True:
y2 = int(input("UNION STRATEGY IS "))
if y2 > 0 and y2 < 5:
break
print("ENTER 1, 2, 3, OR 4 (USUALLY PREVIOUS UNION STRATEGY)")
else:
s0 = 0
r = math.random() * 100
for i in range(1, 5):
s0 += sa[i]
# If actual strategy info is in program data statements
# then r-100 is extra weight given to that strategy.
if r < s0:
break
y2 = i
print(y2)
else:
for i in range(1, 3):
if i == 1:
print("CONFEDERATE STRATEGY ? ", end="")
while True:
y = int(input())
if abs(y - 3) < 3:
break
print(f"STRATEGY {y} NOT ALLOWED.")
print("YOUR STRATEGY ? ", end="")
if i == 2:
y2 = y
y = y1
if y2 != 5:
break
else:
y1 = y
print("UNION STRATEGY ? ", end="")
# Simulated losses - North
c6 = (2 * c2 / 5) * (1 + 1 / (2 * (abs(y2 - y) + 1)))
c6 = c6 * (1.28 + (5 * m2 / 6) / (ba[2] + 1))
c6 = math.floor(c6 * (1 + 1 / o2) + 0.5)
# If loss > men present, rescale losses
e2 = 100 / o2
if math.floor(c6 + e2) >= m6:
c6 = math.floor(13 * m6 / 20)
e2 = 7 * c6 / 13
u2 = 1
# Calculate simulated losses
print()
print()
print()
print("\t\tCONFEDERACY\tUNION")
c5 = (2 * c1 / 5) * (1 + 1 / (2 * (abs(y2 - y) + 1)))
c5 = math.floor(c5 * (1 + 1 / o) * (1.28 + f1 / (ba[1] + 1)) + 0.5)
e = 100 / o
if c5 + 100 / o >= m1 * (1 + (p1 - t1) / (m3 + 1)):
c5 = math.floor(13 * m1 / 20 * (1 + (p1 - t1) / (m3 + 1)))
e = 7 * c5 / 13
u = 1
if d == 1:
c6 = math.floor(17 * c2 * c1 / (c5 * 20))
e2 = 5 * o
print("CASUALTIES\t" + str(c5) + "\t\t" + str(c6))
print("DESERTIONS\t" + str(math.floor(e)) + "\t\t" + str(math.floor(e2)))
print()
if bs == "YES":
print("COMPARED TO THE ACTUAL CASUALTIES AT " + str(cs))
print(
"CONFEDERATE: "
+ str(math.floor(100 * (c5 / c1) + 0.5))
+ "% OF THE ORIGINAL"
)
print(
"UNION: "
+ str(math.floor(100 * (c6 / c2) + 0.5))
+ "% OF THE ORIGINAL"
)
print()
# Find who won
if u == 1 and u2 == 1 or (u != 1 and u2 != 1 and c5 + e == c6 + e2):
print("BATTLE OUTCOME UNRESOLVED")
w0 += 1
elif u == 1 or (u != 1 and u2 != 1 and c5 + e > c6 + e2):
print("THE UNION WINS " + str(cs))
if a != 0:
l += 1
else:
print("THE CONFEDERACY WINS " + str(cs))
if a != 0:
w += 1
# Lines 2530 to 2590 from original are unreachable.
if a != 0:
t1 += c5 + e
t2 += c6 + e2
p1 += c1
p2 += c2
q1 += fa[1] + ha[1] + ba[1]
q2 += fa[2] + ha[2] + ba[2]
r1 += m1 * (100 - i1) / 20
r2 += m2 * (100 - i2) / 20
m3 += m1
m4 += m2
# Learn present strategy, start forgetting old ones
# present startegy of south gains 3*s, others lose s
# probability points, unless a strategy falls below 5 % .
s = 3
s0 = 0
for i in range(1, 5):
if sa[i] <= 5:
continue
sa[i] -= 5
s0 += s
sa[y] += s0
print("AFTER REQUESTING A BATTLE, DO YOU WISH ", end="")
print("BATTLE DESCRIPTIONS ", end="")
xs = get_choice("(ANSWER YES OR NO) ", ["YES", "NO"])
line = 0
w = 0
r1 = 0
q1 = 0
m3 = 0
m4 = 0
p1 = 0
p2 = 0
t1 = 0
t2 = 0
for i in range(1, 3):
dollars_available[i] = 0
food_array[i] = 0
salaries[i] = 0
ammunition[i] = 0
oa[i] = 0
r2 = 0
q2 = 0
c6 = 0
food = 0
w0 = 0
strategy_index = 0
union_strategy_index = 0
u = 0
u2 = 0
print("---------------")
continue
print()
print()
print()
print()
print()
print()
print(f"THE CONFEDERACY HAS WON {w} BATTLES AND LOST {l}")
if y == 5 or (y2 != 5 and w <= l):
print("THE UNION HAS WON THE WAR")
else:
print("THE CONFEDERACY HAS WON THE WAR")
print()
if r1 > 0:
print(f"FOR THE {w + l + w0} BATTLES FOUGHT (EXCLUDING RERUNS)")
print(" \t \t ")
print("CONFEDERACY\t UNION")
print(f"HISTORICAL LOSSES\t{math.floor(p1 + 0.5)}\t{math.floor(p2 + 0.5)}")
print(f"SIMULATED LOSSES\t{math.floor(t1 + 0.5)}\t{math.floor(t2 + 0.5)}")
print()
print(
f" % OF ORIGINAL\t{math.floor(100 * (t1 / p1) + 0.5)}\t{math.floor(100 * (t2 / p2) + 0.5)}"
)
if bs != "YES":
while True:
print()
print("UNION INTELLIGENCE SUGGEST THAT THE SOUTH USED")
print("STRATEGIES 1, 2, 3, 4 IN THE FOLLOWING PERCENTAGES")
print(f"{sa[1]} {sa[2]} {sa[3]} {sa[4]}")
print()
print()
a = int(input("WHICH BATTLE DO YOU WISH TO SIMULATE? "))
if a < 1 or a > 14:
break
if a != 0 or r == 0:
cs = historical_data[a][0]
m1 = historical_data[a][1]
m2 = historical_data[a][2]
c1 = historical_data[a][3]
c2 = historical_data[a][4]
m = historical_data[a][5]
u = 0
# Inflation calc
i1 = 10 + (line - w) * 2
i2 = 10 + (w - line) * 2
# Money available
dollars_available[1] = 100 * math.floor(
(m1 * (100 - i1) / 2000) * (1 + (r1 - q1) / (r1 + 1)) + 0.5
)
dollars_available[2] = 100 * math.floor(m2 * (100 - i2) / 2000 + 0.5)
if bs == "YES":
dollars_available[2] = 100 * math.floor(
(m2 * (100 - i2) / 2000) * (1 + (r2 - q2) / (r2 + 1)) + 0.5
)
# Men available
m5 = math.floor(m1 * (1 + (p1 - t1) / (m3 + 1)))
m6 = math.floor(m2 * (1 + (p2 - t2) / (m4 + 1)))
f1 = 5 * m1 / 6
print()
print()
print()
print()
print()
print(f"THIS IS THE BATTLE OF {cs}")
if xs != "NO":
print("\n".join(battles[a - 1]))
else:
print(cs + " INSTANT REPLAY")
print()
print(" \tCONFEDERACY\t UNION")
print(f"MEN\t {m5}\t\t {m6}")
print(f"MONEY\t ${dollars_available[1]}\t\t${dollars_available[2]}")
print(f"INFLATION\t {i1 + 15}%\t {i2}%")
print()
# ONLY IN PRINTOUT IS CONFED INFLATION = I1 + 15 %
# IF TWO GENERALS, INPUT CONFED, FIRST
for i in range(1, party + 1):
if bs == "YES" and i == 1:
print("CONFEDERATE GENERAL---", end="")
print("HOW MUCH DO YOU WISH TO SPEND FOR")
while True:
food = int(input(" - FOOD...... ? "))
if food < 0:
if r1 == 0:
print("NO PREVIOUS ENTRIES")
continue
print("ASSUME YOU WANT TO KEEP SAME ALLOCATIONS")
print()
break
food_array[i] = food
while True:
salaries[i] = int(input(" - SALARIES.. ? "))
if salaries[i] >= 0:
break
print("NEGATIVE VALUES NOT ALLOWED.")
while True:
ammunition[i] = int(input(" - AMMUNITION ? "))
if ammunition[i] >= 0:
break
print("NEGATIVE VALUES NOT ALLOWED.")
print()
if food_array[i] + salaries[i] + ammunition[i] > dollars_available[i]:
print("THINK AGAIN! YOU HAVE ONLY $" + dollars_available[i])
else:
break
if bs != "YES" or i == 2:
break
print("UNION GENERAL---", end="")
for z in range(1, party + 1):
if bs == "YES":
if z == 1:
print("CONFEDERATE ", end="")
else:
print(" UNION ", end="")
# Find morale
o = (2 * math.pow(food_array[z], 2) + math.pow(salaries[z], 2)) / math.pow(
f1, 2
) + 1
if o >= 10:
print("MORALE IS HIGH")
elif o >= 5:
print("MORALE IS FAIR")
else:
print("MORALE IS POOR")
if bs != "YES":
break
oa[z] = o
o2 = oa[2]
o = oa[1]
print("CONFEDERATE GENERAL---")
# Actual off/def battle situation
if m == 3:
print("YOU ARE ON THE OFFENSIVE")
elif m == 1:
print("YOU ARE ON THE DEFENSIVE")
else:
print("BOTH SIDES ARE ON THE OFFENSIVE")
print()
# Choose strategies
if bs != "YES":
while True:
strategy_index = int(input("YOUR STRATEGY "))
if abs(strategy_index - 3) < 3:
break
print(f"STRATEGY {strategy_index} NOT ALLOWED.")
if strategy_index == 5:
print("THE CONFEDERACY HAS SURRENDERED.")
break
# Union strategy is computer chosen
if a == 0:
while True:
union_strategy_index = int(input("UNION STRATEGY IS "))
if union_strategy_index > 0 and union_strategy_index < 5:
break
print("ENTER 1, 2, 3, OR 4 (USUALLY PREVIOUS UNION STRATEGY)")
else:
s0 = 0
r = math.random() * 100
for i in range(1, 5):
s0 += sa[i]
# If actual strategy info is in program data statements
# then r-100 is extra weight given to that strategy.
if r < s0:
break
union_strategy_index = i
print(union_strategy_index)
else:
for i in range(1, 3):
if i == 1:
print("CONFEDERATE STRATEGY ? ", end="")
while True:
strategy_index = int(input())
if abs(strategy_index - 3) < 3:
break
print(f"STRATEGY {strategy_index} NOT ALLOWED.")
print("YOUR STRATEGY ? ", end="")
if i == 2:
union_strategy_index = strategy_index
strategy_index = previous_strategy
if union_strategy_index != 5:
break
else:
previous_strategy = strategy_index # noqa: F841
print("UNION STRATEGY ? ", end="")
# Simulated losses - North
c6 = (2 * c2 / 5) * (
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)
# If loss > men present, rescale losses
e2 = 100 / o2
if math.floor(c6 + e2) >= m6:
c6 = math.floor(13 * m6 / 20)
e2 = 7 * c6 / 13
u2 = 1
# Calculate simulated losses
print()
print()
print()
print("\t\tCONFEDERACY\tUNION")
c5 = (2 * c1 / 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
if c5 + 100 / o >= m1 * (1 + (p1 - t1) / (m3 + 1)):
c5 = math.floor(13 * m1 / 20 * (1 + (p1 - t1) / (m3 + 1)))
e = 7 * c5 / 13
u = 1
if party == 1:
c6 = math.floor(17 * c2 * c1 / (c5 * 20))
e2 = 5 * o
print("CASUALTIES\t" + str(c5) + "\t\t" + str(c6))
print("DESERTIONS\t" + str(math.floor(e)) + "\t\t" + str(math.floor(e2)))
print()
if bs == "YES":
print("COMPARED TO THE ACTUAL CASUALTIES AT " + str(cs))
print(
"CONFEDERATE: "
+ str(math.floor(100 * (c5 / c1) + 0.5))
+ "% OF THE ORIGINAL"
)
print(
"UNION: "
+ str(math.floor(100 * (c6 / c2) + 0.5))
+ "% OF THE ORIGINAL"
)
print()
# Find who won
if u == 1 and u2 == 1 or (u != 1 and u2 != 1 and c5 + e == c6 + e2):
print("BATTLE OUTCOME UNRESOLVED")
w0 += 1
elif u == 1 or (u != 1 and u2 != 1 and c5 + e > c6 + e2):
print("THE UNION WINS " + str(cs))
if a != 0:
line += 1
else:
print("THE CONFEDERACY WINS " + str(cs))
if a != 0:
w += 1
# Lines 2530 to 2590 from original are unreachable.
if a != 0:
t1 += c5 + e
t2 += c6 + e2
p1 += c1
p2 += c2
q1 += food_array[1] + salaries[1] + ammunition[1]
q2 += food_array[2] + salaries[2] + ammunition[2]
r1 += m1 * (100 - i1) / 20
r2 += m2 * (100 - i2) / 20
m3 += m1
m4 += m2
# Learn present strategy, start forgetting old ones
# present startegy of south gains 3*s, others lose s
# probability points, unless a strategy falls below 5 % .
s = 3
s0 = 0
for i in range(1, 5):
if sa[i] <= 5:
continue
sa[i] -= 5
s0 += s
sa[strategy_index] += s0
u = 0
u2 = 0
print("---------------")
continue
print()
print()
print()
print()
print()
print()
print(f"THE CONFEDERACY HAS WON {w} BATTLES AND LOST {line}")
if strategy_index == 5 or (union_strategy_index != 5 and w <= line):
print("THE UNION HAS WON THE WAR")
else:
print("THE CONFEDERACY HAS WON THE WAR")
print()
if r1 > 0:
print(f"FOR THE {w + line + w0} BATTLES FOUGHT (EXCLUDING RERUNS)")
print(" \t \t ")
print("CONFEDERACY\t UNION")
print(f"HISTORICAL LOSSES\t{math.floor(p1 + 0.5)}\t{math.floor(p2 + 0.5)}")
print(f"SIMULATED LOSSES\t{math.floor(t1 + 0.5)}\t{math.floor(t2 + 0.5)}")
print()
print(
f" % OF ORIGINAL\t{math.floor(100 * (t1 / p1) + 0.5)}\t{math.floor(100 * (t2 / p2) + 0.5)}"
)
if bs != "YES":
print()
print("UNION INTELLIGENCE SUGGEST THAT THE SOUTH USED")
print("STRATEGIES 1, 2, 3, 4 IN THE FOLLOWING PERCENTAGES")
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 ? ")
numbers = []
for i in range(10):
for _ in range(10):
valid_input = False
while not valid_input:
try:
@@ -56,7 +56,21 @@ def read_continue_choice():
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()
if read_instruction_choice():
print_instructions()
@@ -65,9 +79,9 @@ if __name__ == "__main__":
b = 1
c = 3
m = [[1] * 3 for i in range(27)]
k = [[9] * 3 for i in range(3)]
l = [[3] * 3 for i in range(9)]
m = [[1] * 3 for _ in range(27)]
k = [[9] * 3 for _ in range(3)]
l = [[3] * 3 for _ in range(9)] # noqa: E741
continue_game = True
while continue_game:
@@ -79,7 +93,7 @@ if __name__ == "__main__":
z2 = 2
running_correct = 0
for t in range(1, 4):
for round in range(1, 4):
valid_numbers = False
numbers = []
while not valid_numbers:
@@ -132,19 +146,11 @@ if __name__ == "__main__":
z1 = z - (z / 9) * 9
z2 = number
# print summary report
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.")
print_summary_report(running_correct)
continue_game = read_continue_choice()
print("\nTHANKS FOR THE GAME.")
if __name__ == "__main__":
main()

View File

@@ -90,7 +90,7 @@ def to_int(s):
try:
n = int(s)
return True, n
except:
except Exception:
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:
result = int(player_choice) # string to integer
except:
except Exception:
# Whatever the player typed, it could not be interpreted as a number
pass
@@ -124,7 +124,7 @@ def get_furs_purchase():
try:
count = int(count_str)
results.append(count)
except:
except Exception:
# invalid input, prompt again by re-looping
i -= 1
return results

View File

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

View File

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

View File

@@ -46,143 +46,165 @@ def main():
D1 = 0
P1 = 0
Z = 0 # year
P = 95 # population
S = 2800 # grain stores
year = 0
population = 95
grain_stores = 2800
H = 3000
E = H - S # rats eaten
Y = 3 # yield (amount of production from land). Reused as price per acre
A = H / Y # acres of land
I = 5 # immigrants
Q = 1 # boolean for plague, also input for buy/sell land
D = 0 # people
eaten_rats = H - grain_stores
bushels_per_acre = (
3 # yield (amount of production from land). Reused as price per acre
)
acres = H / bushels_per_acre # acres of land
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")
Z = Z + 1 # year
print("IN YEAR", Z, ",", D, "PEOPLE STARVED,", I, "CAME TO THE CITY,")
P = P + I
year = year + 1 # year
print(
"IN YEAR",
year,
",",
people,
"PEOPLE STARVED,",
immigrants,
"CAME TO THE CITY,",
)
population = population + immigrants
if Q == 0:
P = int(P / 2)
if plague == 0:
population = int(population / 2)
print("A HORRIBLE PLAGUE STRUCK! HALF THE PEOPLE DIED.")
print("POPULATION IS NOW", P)
print("THE CITY NOW OWNS", A, "ACRES.")
print("YOU HARVESTED", Y, "BUSHELS PER ACRE.")
print("THE RATS ATE", E, "BUSHELS.")
print("YOU NOW HAVE ", S, "BUSHELS IN STORE.\n")
print("POPULATION IS NOW", population)
print("THE CITY NOW OWNS", acres, "ACRES.")
print("YOU HARVESTED", bushels_per_acre, "BUSHELS PER ACRE.")
print("THE RATS ATE", eaten_rats, "BUSHELS.")
print("YOU NOW HAVE ", grain_stores, "BUSHELS IN STORE.\n")
C = int(10 * random()) # random number between 1 and 10
Y = C + 17
print("LAND IS TRADING AT", Y, "BUSHELS PER ACRE.")
bushels_per_acre = C + 17
print("LAND IS TRADING AT", bushels_per_acre, "BUSHELS PER ACRE.")
Q = -99 # dummy value to track status
while Q == -99: # always run the loop once
Q = b_input("HOW MANY ACRES DO YOU WISH TO BUY? ")
if Q < 0:
Q = -1 # to avoid the corner case of Q=-99
plague = -99 # dummy value to track status
while plague == -99: # always run the loop once
plague = b_input("HOW MANY ACRES DO YOU WISH TO BUY? ")
if plague < 0:
plague = -1 # to avoid the corner case of Q=-99
bad_input_850()
Z = 99 # jump out of main loop and exit
elif Y * Q > S: # can't afford it
bad_input_710(S)
Q = -99 # give'm a second change to get it right
elif Y * Q <= S: # normal case, can afford it
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
year = 99 # jump out of main loop and exit
elif bushels_per_acre * plague > grain_stores: # can't afford it
bad_input_710(grain_stores)
plague = -99 # give'm a second change to get it right
elif (
bushels_per_acre * plague <= grain_stores
): # 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?
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:
if plague == 0 and year != 99: # maybe you want to sell some land?
plague = -99
while plague == -99:
plague = b_input("HOW MANY ACRES DO YOU WISH TO SELL? ")
if plague < 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
year = 99 # jump out of main loop and exit
elif plague <= acres: # normal case
acres = acres - plague # reduce the acres
grain_stores = (
grain_stores + bushels_per_acre * plague
) # 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
bad_input_720(acres)
plague = -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:
plague = -99
while plague == -99 and year != 99:
plague = b_input("HOW MANY BUSHELS DO YOU WISH TO FEED YOUR PEOPLE? ")
if plague < 0:
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?
elif Q > S:
bad_input_710(S)
Q = -99 # try again!
elif plague > grain_stores:
bad_input_710(grain_stores)
plague = -99 # try again!
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
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:
people = -99 # dummy value to force at least one loop
while people == -99 and year != 99:
people = b_input("HOW MANY ACRES DO YOU WISH TO PLANT WITH SEED? ")
if people < 0:
bad_input_850()
Z = 99 # jump out of main loop and exit
elif D > 0:
if D > A:
year = 99 # jump out of main loop and exit
elif people > 0:
if people > acres:
# REM *** TRYING TO PLANT MORE ACRES THAN YOU OWN?
bad_input_720(A)
D = -99
elif int(D / 2) > S:
bad_input_720(acres)
people = -99
elif int(people / 2) > grain_stores:
# REM *** ENOUGH GRAIN FOR SEED?
bad_input_710(S)
D = -99
elif D > 10 * P:
bad_input_710(grain_stores)
people = -99
elif people > 10 * population:
# REM *** ENOUGH PEOPLE TO TEND THE CROPS?
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
S = S - int(D / 2)
grain_stores = grain_stores - int(people / 2)
C = gen_random()
# REM *** A BOUNTIFUL HARVEST!
Y = C
H = D * Y
E = 0
bushels_per_acre = C
H = people * bushels_per_acre
eaten_rats = 0
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
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()
# 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?
C = int(Q / 20)
C = int(plague / 20)
# REM *** HORROS, A 15% CHANCE OF PLAGUE
# yeah, should be HORRORS, but left it
Q = int(10 * (2 * random() - 0.3))
if P >= C and Z != 99: # if there are some people without full bellies...
plague = int(10 * (2 * random() - 0.3))
if (
population >= C and year != 99
): # if there are some people without full bellies...
# REM *** STARVE ENOUGH FOR IMPEACHMENT?
D = P - C
if D > 0.45 * P:
print("\nYOU STARVED", D, "PEOPLE IN ONE YEAR!!!")
people = population - C
if people > 0.45 * population:
print("\nYOU STARVED", people, "PEOPLE IN ONE YEAR!!!")
national_fink()
Z = 99 # exit the loop
P1 = ((Z - 1) * P1 + D * 100 / P) / Z
P = C
D1 = D1 + D
year = 99 # exit the loop
P1 = ((year - 1) * P1 + people * 100 / population) / year
population = C
D1 = D1 + people
if Z != 99:
if year != 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
L = acres / population
print("YOU STARTED WITH 10 ACRES PER PERSON AND ENDED WITH")
print(L, "ACRES PER PERSON.\n")
if P1 > 33 or L < 7:
@@ -193,7 +215,11 @@ def main():
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(
"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("TRIVIAL PROBLEMS.")
else:

View File

@@ -166,12 +166,12 @@ def print_race_state(total_distance, race_pos):
basic_print("XXXXSTARTXXXX")
# 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
# next horse to print is not the current 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="")
next_pos = next(race_pos_iter, None)
else:
@@ -209,8 +209,8 @@ def simulate_race(odds):
# in the original implementation, race_pos is reset for each
# simulation step, so we keep this behaviour here
race_pos = list(range(num_horses))
for l in range(num_horses):
for i in range(num_horses - 1 - l):
for line in range(num_horses):
for i in range(num_horses - 1 - line):
if total_distance[race_pos[i]] < total_distance[race_pos[i + 1]]:
continue
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:
try:
betCount = int(input("HOW MANY BETS? "))
except:
except Exception:
...
bet_IDs = [-1] * betCount
@@ -87,7 +87,7 @@ def query_bets():
if id > 0 and id <= 50 and val >= 5 and val <= 500:
bet_IDs[i] = id
bet_Values[i] = val
except:
except Exception:
...
return bet_IDs, bet_Values

View File

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

View File

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

View File

@@ -4,11 +4,11 @@
#
# Converted from BASIC to Python by Trevor Hobson
import math
from math import exp, floor, sqrt
def equation(input):
return 30 * math.exp(-input * input / 100)
def equation(x: float) -> float:
return 30 * exp(-x * x / 100)
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):
x1 = x / 10
l = 0
y1 = 5 * math.floor(math.sqrt(900 - x1 * x1) / 5)
yPlot = [" "] * 80
max_column = 0
y1 = 5 * floor(sqrt(900 - x1 * x1) / 5)
y_plot = [" "] * 80
for y in range(y1, -(y1 + 5), -5):
z = math.floor(25 + equation(math.sqrt(x1 * x1 + y * y)) - 0.7 * y)
if z > l:
l = z
yPlot[z] = "*"
print("".join(yPlot))
column = floor(25 + equation(sqrt(x1 * x1 + y * y)) - 0.7 * y)
if column > max_column:
max_column = column
y_plot[column] = "*"
print("".join(y_plot))

View File

@@ -99,7 +99,7 @@ class Game:
while which is None:
try:
which = self.which_disk()
except:
except Exception:
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]
@@ -115,7 +115,7 @@ class Game:
try:
needle = int(input("PLACE DISK ON WHICH NEEDLE\n"))
tower = self.__towers[needle - 1]
except:
except Exception:
print(
"I'LL ASSUME YOU HIT THE WRONG KEY THIS TIME. BUT WATCH IT,\nI ONLY ALLOW ONE MISTAKE.\n"
)