mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-26 12:51:29 -08:00
Merge branch 'coding-horror:main' into main
This commit is contained in:
441
27_Civil_War/python/Civilwar.py
Normal file
441
27_Civil_War/python/Civilwar.py
Normal file
@@ -0,0 +1,441 @@
|
||||
import math
|
||||
import random
|
||||
|
||||
|
||||
def tab(n):
|
||||
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."]]
|
||||
|
||||
historical_data = [
|
||||
[],
|
||||
["BULL RUN", 18000, 18500, 1967, 2708, 1],
|
||||
["SHILOH", 40000., 44894., 10699, 13047, 3],
|
||||
["SEVEN DAYS", 95000., 115000., 20614, 15849, 3],
|
||||
["SECOND BULL RUN", 54000., 63000., 10000, 14000, 2],
|
||||
["ANTIETAM", 40000., 50000., 10000, 12000, 3],
|
||||
["FREDERICKSBURG", 75000., 120000., 5377, 12653, 1],
|
||||
["MURFREESBORO", 38000., 45000., 11000, 12000, 1],
|
||||
["CHANCELLORSVILLE", 32000, 90000., 13000, 17197, 2],
|
||||
["VICKSBURG", 50000., 70000., 12000, 19000, 1],
|
||||
["GETTYSBURG", 72500., 85000., 20000, 23000, 3],
|
||||
["CHICKAMAUGA", 66000., 60000., 18000, 16000, 2],
|
||||
["CHATTANOOGA", 37000., 60000., 36700., 5800, 2],
|
||||
["SPOTSYLVANIA", 62000., 110000., 17723, 18000, 2],
|
||||
["ATLANTA", 65000., 100000., 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.")
|
||||
|
||||
print()
|
||||
print()
|
||||
print()
|
||||
print("ARE THERE TWO GENERALS PRESENT ", end="")
|
||||
while True:
|
||||
bs = input("(ANSWER YES OR NO) ")
|
||||
if bs == "YES":
|
||||
d = 2
|
||||
break
|
||||
elif bs == "NO":
|
||||
d = 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()
|
||||
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
|
||||
|
||||
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"):
|
||||
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]}")
|
||||
@@ -1,3 +1,3 @@
|
||||
Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html)
|
||||
|
||||
Conversion to [Ruby](https://www.ruby-lang.org/en/)
|
||||
Conversion to [Ruby](https://www.ruby-lang.org/en/) by [R.T. Lechow](https://github.com/rtlechow)
|
||||
|
||||
59
47_Hi-Lo/ruby/hi_lo.rb
Normal file
59
47_Hi-Lo/ruby/hi_lo.rb
Normal file
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env ruby
|
||||
MAX_TRIES = 6
|
||||
RANGE = (1..100)
|
||||
|
||||
def intro
|
||||
puts <<~END_OF_INTRO
|
||||
#{'HI LO'.center(74)}
|
||||
#{"CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n".center(76)}
|
||||
THIS IS THE GAME OF HI LO.\n
|
||||
YOU WILL HAVE #{MAX_TRIES} TRIES TO GUESS THE AMOUNT OF MONEY IN THE
|
||||
HI LO JACKPOT, WHICH IS BETWEEN #{RANGE.min} AND #{RANGE.max} DOLLARS. IF YOU
|
||||
GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!
|
||||
THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,
|
||||
IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.\n\n
|
||||
END_OF_INTRO
|
||||
end
|
||||
|
||||
def make_guess
|
||||
puts 'YOUR GUESS?'
|
||||
@guess = gets.to_i
|
||||
end
|
||||
|
||||
def check_guess
|
||||
if @guess == @number
|
||||
@guessed_correctly = true
|
||||
@total_winnings += @number
|
||||
puts <<~END_OF_WIN_TEXT
|
||||
GOT IT!!!!!!!!!! YOU WIN #{@number} DOLLARS.
|
||||
YOUR TOTAL WINNINGS ARE NOW #{@total_winnings} DOLLARS.
|
||||
END_OF_WIN_TEXT
|
||||
else
|
||||
puts "YOUR GUESS IS TOO #{@guess > @number ? 'HIGH' : 'LOW'}.\n\n"
|
||||
end
|
||||
end
|
||||
|
||||
def blew_it
|
||||
@total_winnings = 0
|
||||
puts "YOU BLEW IT...TOO BAD...THE NUMBER WAS #{@number}"
|
||||
end
|
||||
|
||||
def outro
|
||||
puts "\nSO LONG. HOPE YOU ENJOYED YOURSELF!!!"
|
||||
end
|
||||
|
||||
intro
|
||||
@total_winnings = 0
|
||||
loop do
|
||||
@guessed_correctly = false
|
||||
@number = rand(RANGE)
|
||||
MAX_TRIES.times do
|
||||
make_guess
|
||||
check_guess
|
||||
break if @guessed_correctly
|
||||
end
|
||||
blew_it unless @guessed_correctly
|
||||
puts "\nPLAY AGAIN (YES OR NO)?"
|
||||
break if gets.start_with?(/n/i)
|
||||
end
|
||||
outro
|
||||
12
59_Lunar_LEM_Rocket/rust/README.md
Normal file
12
59_Lunar_LEM_Rocket/rust/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
README.md
|
||||
|
||||
Original source downloaded from Vintage Basic
|
||||
|
||||
This folder for chapter #59 contains three different games. Three folders here contain the three games:
|
||||
|
||||
- Rocket
|
||||
- LEM
|
||||
- lunar
|
||||
|
||||
Conversion to [Rust](https://www.rust-lang.org)
|
||||
|
||||
10
59_Lunar_LEM_Rocket/rust/rocket/Cargo.toml
Normal file
10
59_Lunar_LEM_Rocket/rust/rocket/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "rocket"
|
||||
version = "1.0.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
text_io = "0.1.10"
|
||||
num-integer = "0.1"
|
||||
107
59_Lunar_LEM_Rocket/rust/rocket/src/main.rs
Normal file
107
59_Lunar_LEM_Rocket/rust/rocket/src/main.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
//Goal of this port is to keep Basic lang idioms where possible. Gotta have those single letter capital variables!
|
||||
use num_integer::{sqrt};
|
||||
use std::io::{self, Write};
|
||||
use text_io::{read, try_read};
|
||||
#[allow(non_snake_case)]
|
||||
fn main() {
|
||||
println!("{:>30}", "ROCKET");
|
||||
println!("{:>15}", "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
|
||||
println!();println!();println!();
|
||||
println!("LUNAR LANDING SIMULATION");
|
||||
println!("----- ------- ----------");println!();
|
||||
let A= input("DO YOU WANT INSTRUCTIONS (YES OR NO) ");
|
||||
if !(A=="NO") {
|
||||
println!();
|
||||
println!("YOU ARE LANDING ON THE MOON AND AND HAVE TAKEN OVER MANUAL");
|
||||
println!("CONTROL 1000 FEET ABOVE A GOOD LANDING SPOT. YOU HAVE A DOWN-");
|
||||
println!("WARD VELOCITY OF 50 FEET/SEC. 150 UNITS OF FUEL REMAIN.");
|
||||
println!();
|
||||
println!("HERE ARE THE RULES THAT GOVERN YOUR APOLLO SPACE-CRAFT:"); println!();
|
||||
println!("(1) AFTER EACH SECOND THE HEIGHT, VELOCITY, AND REMAINING FUEL");
|
||||
println!(" WILL BE REPORTED VIA DIGBY YOUR ON-BOARD COMPUTER.");
|
||||
println!("(2) AFTER THE REPORT A '?' WILL APPEAR. ENTER THE NUMBER");
|
||||
println!(" OF UNITS OF FUEL YOU WISH TO BURN DURING THE NEXT");
|
||||
println!(" SECOND. EACH UNIT OF FUEL WILL SLOW YOUR DESCENT BY");
|
||||
println!(" 1 FOOT/SEC.");
|
||||
println!("(3) THE MAXIMUM THRUST OF YOUR ENGINE IS 30 FEET/SEC/SEC");
|
||||
println!(" OR 30 UNITS OF FUEL PER SECOND.");
|
||||
println!("(4) WHEN YOU CONTACT THE LUNAR SURFACE. YOUR DESCENT ENGINE");
|
||||
println!(" WILL AUTOMATICALLY SHUT DOWN AND YOU WILL BE GIVEN A");
|
||||
println!(" REPORT OF YOUR LANDING SPEED AND REMAINING FUEL.");
|
||||
println!("(5) IF YOU RUN OUT OF FUEL THE '?' WILL NO LONGER APPEAR");
|
||||
println!(" BUT YOUR SECOND BY SECOND REPORT WILL CONTINUE UNTIL");
|
||||
println!(" YOU CONTACT THE LUNAR SURFACE.");println!();
|
||||
}
|
||||
loop {
|
||||
println!("BEGINNING LANDING PROCEDURE..........");println!();
|
||||
println!("G O O D L U C K ! ! !");
|
||||
println!();println!();
|
||||
println!("SEC FEET SPEED FUEL PLOT OF DISTANCE");
|
||||
println!();
|
||||
let mut T=0;let mut H:i32=1000;let mut V=50;let mut F=150;
|
||||
let D:i32; let mut V1:i32; let mut B:i32;
|
||||
'falling: loop {
|
||||
println!(" {:<4}{:<11}{:<10}{:<8}I{capsule:>high$}", T,H,V,F,high=(H/15) as usize,capsule="*");
|
||||
B = input_int("");
|
||||
if B<0 { B=0 }
|
||||
else { if B>30 { B=30 } }
|
||||
if B>F { B=F }
|
||||
'nofuel: loop {
|
||||
V1=V-B+5;
|
||||
F=F-B;
|
||||
H=H- (V+V1)/2;
|
||||
if H<=0 { break 'falling}
|
||||
T=T+1;
|
||||
V=V1;
|
||||
if F>0 { break 'nofuel }
|
||||
if B!=0 {
|
||||
println!("**** OUT OF FUEL ****");
|
||||
}
|
||||
println!(" {:<4}{:<11}{:<10}{:<8}I{capsule:>high$}", T,H,V,F,high=(H/12+29) as usize,capsule="*");
|
||||
B=0;
|
||||
}
|
||||
}
|
||||
H=H+ (V1+V)/2;
|
||||
if B==5 {
|
||||
D=H/V;
|
||||
} else {
|
||||
D=(-V+sqrt(V*V+H*(10-2*B)))/(5-B);
|
||||
V1=V+(5-B)*D;
|
||||
}
|
||||
println!("***** CONTACT *****");
|
||||
println!("TOUCHDOWN AT {} SECONDS.",T+D);
|
||||
println!("LANDING VELOCITY={} FEET/SEC.",V1);
|
||||
println!("{} UNITS OF FUEL REMAINING.", F);
|
||||
if V1==0 {
|
||||
println!("CONGRATULATIONS! A PERFECT LANDING!!");
|
||||
println!("YOUR LICENSE WILL BE RENEWED.......LATER.");
|
||||
}
|
||||
if V1.abs()>=2 {
|
||||
println!("***** SORRY, BUT YOU BLEW IT!!!!");
|
||||
println!("APPROPRIATE CONDOLENCES WILL BE SENT TO YOUR NEXT OF KIN.");
|
||||
}
|
||||
println!();println!();println!();
|
||||
let A = input("ANOTHER MISSION");
|
||||
if !(A=="YES") { break };
|
||||
}
|
||||
println!();println!( "CONTROL OUT.");println!();
|
||||
}
|
||||
|
||||
|
||||
fn input(prompt:&str) -> String {
|
||||
loop {
|
||||
print!("{} ? ",prompt);io::stdout().flush().unwrap();
|
||||
let innn:String=read!("{}\n");
|
||||
let out:String = innn.trim().to_string();
|
||||
if out!="" {return out}
|
||||
}
|
||||
}
|
||||
fn input_int(prompt:&str) -> i32 {
|
||||
loop {
|
||||
print!("{} ? ",prompt);io::stdout().flush().unwrap();
|
||||
match try_read!() {
|
||||
Ok(n) => return n,
|
||||
Err(_) => println!("Enter a number 0-30"),
|
||||
}
|
||||
}
|
||||
}
|
||||
165
79_Slalom/python/slalom.py
Normal file
165
79_Slalom/python/slalom.py
Normal file
@@ -0,0 +1,165 @@
|
||||
from random import random
|
||||
|
||||
print("Slalom".rjust(39))
|
||||
print("Creative Computing Morristown, New Jersey\n\n\n".rjust(57))
|
||||
|
||||
medals = {
|
||||
"gold": 0,
|
||||
"silver": 0,
|
||||
"bronze": 0,
|
||||
}
|
||||
max_speeds = [14,18,26,29,18,25,28,32,29,20,29,29,25,21,26,29,20,21,20,18,26,25,33,31,22]
|
||||
|
||||
def ask(question):
|
||||
print(question, end="? ")
|
||||
return input().upper()
|
||||
|
||||
def ask_int(question):
|
||||
reply = ask(question)
|
||||
return int(reply) if reply.isnumeric() else -1
|
||||
|
||||
def pre_run():
|
||||
print("\nType \"INS\" for instructions")
|
||||
print("Type \"MAX\" for approximate maximum speeds")
|
||||
print("Type \"RUN\" for the beginning of the race")
|
||||
cmd = ask("Command--")
|
||||
while cmd != "RUN":
|
||||
if cmd == "INS":
|
||||
print("\n*** Slalom: This is the 1976 Winter Olypic Giant Slalom. You are")
|
||||
print(" the American team's only hope for a gold medal.\n")
|
||||
print(" 0 -- Type this if you want to see how long you've taken.")
|
||||
print(" 1 -- Type this if you want to speed up a lot.")
|
||||
print(" 2 -- Type this if you want to speed up a little.")
|
||||
print(" 3 -- Type this if you want to speed up a teensy.")
|
||||
print(" 4 -- Type this if you want to keep going the same speed.")
|
||||
print(" 5 -- Type this if you want to check a teensy.")
|
||||
print(" 6 -- Type this if you want to check a little.")
|
||||
print(" 7 -- Type this if you want to check a lot.")
|
||||
print(" 8 -- Type this if you want to cheat and try to skip a gate.\n")
|
||||
print(" The place to use these options is when the Computer asks:\n")
|
||||
print("Option?\n")
|
||||
print(" Good Luck!\n")
|
||||
cmd = ask("Command--")
|
||||
elif cmd == "MAX":
|
||||
print("Gate Max")
|
||||
print(" # M.P.H.")
|
||||
print("----------")
|
||||
for i in range(0, gates):
|
||||
print(f" {i + 1} {max_speeds[i]}")
|
||||
cmd = ask("Command--")
|
||||
else:
|
||||
cmd = ask(f"\"{cmd}\" is an illegal command--Retry")
|
||||
|
||||
def run():
|
||||
global medals
|
||||
print("The starter counts down...5...4...3...2...1...Go!")
|
||||
time = 0
|
||||
speed = int(random() * (18 - 9) + 9)
|
||||
print("You're off")
|
||||
for i in range(0, gates):
|
||||
while True:
|
||||
print(f"\nHere comes gate #{i + 1}:")
|
||||
print(f" {int(speed)} M.P.H.")
|
||||
old_speed = speed
|
||||
opt = ask_int("Option")
|
||||
while opt < 1 or opt > 8:
|
||||
if(opt == 0):
|
||||
print(f"You've taken {int(time)} seconds.")
|
||||
else:
|
||||
print("What?")
|
||||
opt = ask_int("Option")
|
||||
|
||||
if opt == 8:
|
||||
print("***Cheat")
|
||||
if random() < .7:
|
||||
print("An official caught you!")
|
||||
print(f"You took {int(time + random())} seconds.")
|
||||
return
|
||||
else:
|
||||
print("You made it!")
|
||||
time += 1.5
|
||||
else:
|
||||
match opt:
|
||||
case 1:
|
||||
speed += int(random() * (10 - 5) + 5)
|
||||
|
||||
case 2:
|
||||
speed += int(random() * (5 - 3) + 3)
|
||||
|
||||
case 3:
|
||||
speed += int(random() * (4 - 1) + 1)
|
||||
|
||||
case 5:
|
||||
speed -= int(random() * (4 - 1) + 1)
|
||||
|
||||
case 6:
|
||||
speed -= int(random() * (5 - 3) + 3)
|
||||
|
||||
case 7:
|
||||
speed -= int(random() * (10 - 5) + 5)
|
||||
print(f" {int(speed)} M.P.H.")
|
||||
if speed > max_speeds[i]:
|
||||
if random() < ((speed - max_speeds[i]) * .1) + .2:
|
||||
print(f"You went over the maximum speed and {'snagged a flag' if random() < .5 else 'wiped out'}!")
|
||||
print(f"You took {int(time + random())} seconds")
|
||||
return
|
||||
else:
|
||||
print("You went over the maximum speed and made it!")
|
||||
if speed > max_speeds[i] - 1:
|
||||
print("Close one!")
|
||||
if speed < 7:
|
||||
print("Let's be realistic, ok? Let's go back and try again...")
|
||||
speed = old_speed
|
||||
else:
|
||||
time += max_speeds[i] - speed + 1
|
||||
if speed > max_speeds[i]:
|
||||
time += .5
|
||||
break
|
||||
print(f"\nYou took {int(time + random())} seconds.")
|
||||
avg = time / gates
|
||||
if avg < 1.5 - (lvl * .1):
|
||||
print("Yout won a gold medal!")
|
||||
medals["gold"] += 1
|
||||
elif avg < 2.9 - (lvl * .1):
|
||||
print("You won a silver medal!")
|
||||
medals["silver"] += 1
|
||||
elif avg < 4.4 - (lvl * .01):
|
||||
print("You won a bronze medal!")
|
||||
medals["bronze"] += 1
|
||||
|
||||
while True:
|
||||
gates = ask_int("How many gates does this course have (1 to 25)")
|
||||
if gates < 1:
|
||||
print("Try again,")
|
||||
else:
|
||||
if(gates > 25):
|
||||
print("25 is the limit.")
|
||||
break
|
||||
|
||||
pre_run()
|
||||
|
||||
while True:
|
||||
lvl = ask_int("Rate yourself as a skier, (1=Worst, 3=Best)")
|
||||
if lvl < 1 or lvl > 3:
|
||||
print("The bounds are 1-3.")
|
||||
else:
|
||||
break
|
||||
|
||||
while True:
|
||||
run()
|
||||
while True:
|
||||
answer = ask("Do you want to play again?")
|
||||
if answer == "YES" or answer == "NO":
|
||||
break
|
||||
else:
|
||||
print("Please type \"YES\" or \"NO\"")
|
||||
if answer == "NO":
|
||||
break
|
||||
|
||||
print("Thanks for the race")
|
||||
if medals["gold"] > 0:
|
||||
print(f"Gold medals: {medals['gold']}")
|
||||
if medals["silver"] > 0:
|
||||
print(f"Silver medals: {medals['silver']}")
|
||||
if medals["bronze"] > 0:
|
||||
print(f"Bronze medals: {medals['bronze']}")
|
||||
@@ -33,13 +33,15 @@ while(true) {
|
||||
d = move(c + 3);
|
||||
computerMoves(d);
|
||||
s = readYourMove();
|
||||
if (s != move(d + 4)) {
|
||||
if (s == move(d + 4)) {
|
||||
e = move(d + 6);
|
||||
computerMoves(e);
|
||||
Console.WriteLine("THE GAME IS A DRAW.");
|
||||
} else {
|
||||
e = move(d + 4);
|
||||
computerMoves(e);
|
||||
Console.WriteLine("AND WINS ********");
|
||||
}
|
||||
e = move(d + 6);
|
||||
computerMoves(e);
|
||||
Console.WriteLine("THE GAME IS A DRAW.");
|
||||
} else {
|
||||
d = move(c + 7);
|
||||
computerMoves(d);
|
||||
|
||||
3
89_Tic-Tac-Toe/go/README.md
Normal file
3
89_Tic-Tac-Toe/go/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html)
|
||||
|
||||
Conversion to [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language))
|
||||
88
89_Tic-Tac-Toe/go/src/tictactoe1.go
Normal file
88
89_Tic-Tac-Toe/go/src/tictactoe1.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Printf("Hello, World!\n")
|
||||
// Print text on the screen with 30 spaces before text
|
||||
fmt.Printf("%30s\n", "TIC TAC TOE")
|
||||
// Print text on screen with 15 spaces before text
|
||||
// And print three lines break on screen
|
||||
fmt.Printf("%15s\n\n\n\n", "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
// THIS PROGRAM PLAYS TIC TAC TOE
|
||||
// THE MACHINE GOES FIRST
|
||||
fmt.Printf("THE GAME BOARD IS NUMBERED:\n\n")
|
||||
fmt.Println("1 2 3")
|
||||
fmt.Println("8 9 4")
|
||||
fmt.Println("7 6 5")
|
||||
|
||||
// Main program
|
||||
for {
|
||||
var (
|
||||
a, b, c, d, e int
|
||||
p, q, r, s int
|
||||
)
|
||||
a = 9
|
||||
fmt.Printf("\n\n")
|
||||
computerMoves(a)
|
||||
p = readYourMove()
|
||||
b = move(p + 1)
|
||||
computerMoves(b)
|
||||
q = readYourMove()
|
||||
if q == move(b+4) {
|
||||
c = move(b + 2)
|
||||
computerMoves(c)
|
||||
r = readYourMove()
|
||||
if r == move(c+4) {
|
||||
if p%2 != 0 {
|
||||
d = move(c + 3)
|
||||
computerMoves(d)
|
||||
s = readYourMove()
|
||||
if s == move(d+4) {
|
||||
e = move(d + 6)
|
||||
computerMoves(e)
|
||||
fmt.Println("THE GAME IS A DRAW.")
|
||||
} else {
|
||||
e = move(d + 4)
|
||||
computerMoves(e)
|
||||
fmt.Println("AND WINS ********")
|
||||
}
|
||||
} else {
|
||||
d = move(c + 7)
|
||||
computerMoves(d)
|
||||
fmt.Println("AND WINS ********")
|
||||
}
|
||||
} else {
|
||||
d = move(c + 4)
|
||||
computerMoves(d)
|
||||
fmt.Println("AND WINS ********")
|
||||
}
|
||||
} else {
|
||||
c = move(b + 4)
|
||||
computerMoves(c)
|
||||
fmt.Println("AND WINS ********")
|
||||
}
|
||||
}
|
||||
}
|
||||
func computerMoves(move int) {
|
||||
fmt.Printf("COMPUTER MOVES %v\n", move)
|
||||
}
|
||||
|
||||
func readYourMove() int {
|
||||
for {
|
||||
fmt.Printf("YOUR MOVE?")
|
||||
var input string
|
||||
fmt.Scan(&input)
|
||||
number, err := strconv.Atoi(input)
|
||||
if err == nil {
|
||||
return number
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func move(number int) int {
|
||||
return number - 8*(int)((number-1)/8)
|
||||
}
|
||||
103
89_Tic-Tac-Toe/pascal/tictactoe1.pas
Normal file
103
89_Tic-Tac-Toe/pascal/tictactoe1.pas
Normal file
@@ -0,0 +1,103 @@
|
||||
program tictactoe1;
|
||||
var
|
||||
a, b, c, d, e: integer;
|
||||
p, q, r, s: integer;
|
||||
procedure computerMoves(m: integer);
|
||||
begin
|
||||
write('COMPUTER MOVES ');
|
||||
writeln(m);
|
||||
end;
|
||||
|
||||
function readYourMove() : integer;
|
||||
var number: integer;
|
||||
begin
|
||||
write('YOUR MOVE?');
|
||||
readln(number);
|
||||
readYourMove := number;
|
||||
end;
|
||||
|
||||
function move(number: integer): integer;
|
||||
begin
|
||||
move := number - 8 * trunc((number - 1) / 8);
|
||||
end;
|
||||
|
||||
function padLeft(m: string; n: integer): string;
|
||||
var tmp: string;
|
||||
begin
|
||||
tmp := '';
|
||||
repeat
|
||||
tmp := tmp + ' ';
|
||||
n := n - 1;
|
||||
until n = 0;
|
||||
tmp := tmp + m;
|
||||
padLeft := tmp;
|
||||
end;
|
||||
|
||||
begin
|
||||
writeln(padLeft('TIC TAC TOE', 30));
|
||||
writeln(padLeft('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY', 15));
|
||||
writeln('');
|
||||
writeln('');
|
||||
writeln('');
|
||||
writeln('THE GAME BOARD IS NUMBERED:');
|
||||
writeln('');
|
||||
writeln('1 2 3');
|
||||
writeln('8 9 4');
|
||||
writeln('7 6 5');
|
||||
while(true) do
|
||||
begin
|
||||
writeln('');
|
||||
writeln('');
|
||||
a := 9;
|
||||
computerMoves(a);
|
||||
p := readYourMove();
|
||||
b := move(p + 1);
|
||||
computerMoves(b);
|
||||
q := readYourMove();
|
||||
if (q = move(b + 4)) then
|
||||
begin
|
||||
c := move(b + 2);
|
||||
computerMoves(c);
|
||||
r := readYourMove();
|
||||
if (r = move(c + 4)) then
|
||||
begin
|
||||
if (p mod 2 <> 0) then
|
||||
begin
|
||||
d := move(c + 3);
|
||||
computerMoves(d);
|
||||
s := readYourMove();
|
||||
if (s = move(d + 4)) then
|
||||
begin
|
||||
e := move(d + 6);
|
||||
computerMoves(e);
|
||||
writeln('THE GAME IS A DRAW.');
|
||||
end
|
||||
else
|
||||
begin
|
||||
e := move(d + 4);
|
||||
computerMoves(e);
|
||||
writeln('AND WINS ********');
|
||||
end
|
||||
end
|
||||
else
|
||||
begin
|
||||
d := move(c + 7);
|
||||
computerMoves(d);
|
||||
writeln('AND WINS ********');
|
||||
end
|
||||
end
|
||||
else
|
||||
begin
|
||||
d := move(c + 4);
|
||||
computerMoves(d);
|
||||
writeln('AND WINS ********');
|
||||
end
|
||||
end
|
||||
else
|
||||
begin
|
||||
c := move(b + 4);
|
||||
computerMoves(c);
|
||||
writeln('AND WINS ********');
|
||||
end;
|
||||
end;
|
||||
end.
|
||||
Reference in New Issue
Block a user