mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-21 14:50:54 -08:00
MAINT: Apply pre-commit
Remove byte-order-marker pre-commit check as there would be many adjustments necessary
This commit is contained in:
@@ -4,7 +4,6 @@ repos:
|
||||
rev: v4.1.0
|
||||
hooks:
|
||||
- id: check-ast
|
||||
- id: check-byte-order-marker
|
||||
- id: check-case-conflict
|
||||
- id: check-docstring-first
|
||||
- id: check-executables-have-shebangs
|
||||
|
||||
@@ -375,6 +375,3 @@ sub SMARPLIT {
|
||||
if ($Text) { push @Parts, &TRIM($Text); }
|
||||
return @Parts;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -57,4 +57,3 @@ foreach my $Dir (@Dirs) {
|
||||
printf("%$Tab\s", "$Per");
|
||||
}
|
||||
print "\n";
|
||||
|
||||
|
||||
@@ -16,4 +16,3 @@ begin
|
||||
Acey_Ducey:= TGame.Create;
|
||||
Acey_Ducey.Run;
|
||||
end.
|
||||
|
||||
|
||||
@@ -108,4 +108,3 @@ begin
|
||||
end;
|
||||
|
||||
end.
|
||||
|
||||
|
||||
@@ -133,4 +133,3 @@ begin
|
||||
end;
|
||||
|
||||
end.
|
||||
|
||||
|
||||
@@ -149,4 +149,3 @@ begin
|
||||
until not TryAgain;
|
||||
WriteLN('O.K., HOPE YOU HAD FUN!');
|
||||
end.
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#
|
||||
######################################################
|
||||
|
||||
|
||||
class Card:
|
||||
def __init__(self, suit, rank):
|
||||
self.suit = suit
|
||||
@@ -19,14 +20,14 @@ class Card:
|
||||
def __str__(self):
|
||||
r = self.rank
|
||||
if r == 11:
|
||||
r = 'J'
|
||||
r = "J"
|
||||
elif r == 12:
|
||||
r = 'Q'
|
||||
r = "Q"
|
||||
elif r == 13:
|
||||
r = 'K'
|
||||
r = "K"
|
||||
elif r == 14:
|
||||
r = 'A'
|
||||
return f'{r}{self.suit}'
|
||||
r = "A"
|
||||
return f"{r}{self.suit}"
|
||||
|
||||
|
||||
class Deck:
|
||||
@@ -35,12 +36,13 @@ class Deck:
|
||||
self.build()
|
||||
|
||||
def build(self):
|
||||
for suit in ['\u2665', '\u2666', '\u2663', '\u2660']:
|
||||
for suit in ["\u2665", "\u2666", "\u2663", "\u2660"]:
|
||||
for rank in range(2, 15):
|
||||
self.cards.append(Card(suit, rank))
|
||||
|
||||
def shuffle(self):
|
||||
import random
|
||||
|
||||
random.shuffle(self.cards)
|
||||
|
||||
def deal(self):
|
||||
@@ -69,34 +71,34 @@ class Game:
|
||||
self.card_b = self.deck.deal()
|
||||
card_b = self.card_b
|
||||
|
||||
print(f'You have:\t ${self.money} ')
|
||||
print(f'Your cards:\t {card_a} {card_b}')
|
||||
print(f"You have:\t ${self.money} ")
|
||||
print(f"Your cards:\t {card_a} {card_b}")
|
||||
|
||||
bet = int(input('What is your bet? '))
|
||||
bet = int(input("What is your bet? "))
|
||||
player_card = self.deck.deal()
|
||||
if 0 < bet <= self.money:
|
||||
|
||||
print(f'Your deal:\t {player_card}')
|
||||
print(f"Your deal:\t {player_card}")
|
||||
if card_a.rank < player_card.rank < card_b.rank:
|
||||
print('You Win!')
|
||||
print("You Win!")
|
||||
self.money += bet
|
||||
else:
|
||||
print('You Lose!')
|
||||
print("You Lose!")
|
||||
self.money -= bet
|
||||
self.not_done = False
|
||||
else:
|
||||
print('Chicken!')
|
||||
print(f'Your deal should have been: {player_card}')
|
||||
print("Chicken!")
|
||||
print(f"Your deal should have been: {player_card}")
|
||||
if card_a.rank < player_card.rank < card_b.rank:
|
||||
print(f'You could have won!')
|
||||
print(f"You could have won!")
|
||||
else:
|
||||
print(f'You would lose, so it was wise of you to chicken out!')
|
||||
print(f"You would lose, so it was wise of you to chicken out!")
|
||||
|
||||
self.not_done = False
|
||||
break
|
||||
|
||||
if len(self.deck.cards) <= 3:
|
||||
print('You ran out of cards. Game over.')
|
||||
print("You ran out of cards. Game over.")
|
||||
self.not_done = False
|
||||
break
|
||||
|
||||
@@ -107,22 +109,24 @@ class Game:
|
||||
self.not_done = False
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('''
|
||||
if __name__ == "__main__":
|
||||
print(
|
||||
"""
|
||||
Acey Ducey is a card game where you play against the computer.
|
||||
The Dealer(computer) will deal two cards facing up.
|
||||
You have an option to bet or not bet depending on whether or not you
|
||||
feel the card will have a value between the first two.
|
||||
If you do not want to bet input a 0
|
||||
''')
|
||||
"""
|
||||
)
|
||||
GAME_OVER = False
|
||||
|
||||
while not GAME_OVER:
|
||||
game = Game()
|
||||
game.play()
|
||||
print(f'You have ${game.money} left')
|
||||
print('Would you like to play again? (y/n)')
|
||||
if input() == 'n':
|
||||
print(f"You have ${game.money} left")
|
||||
print("Would you like to play again? (y/n)")
|
||||
if input() == "n":
|
||||
GAME_OVER = True
|
||||
|
||||
print('\nThanks for playing!')
|
||||
print("\nThanks for playing!")
|
||||
|
||||
@@ -14,4 +14,3 @@ begin
|
||||
AmazingApp:= TAmazingApplication.Create;
|
||||
AmazingApp.Run;
|
||||
end.
|
||||
|
||||
|
||||
@@ -101,4 +101,3 @@ begin
|
||||
end;
|
||||
|
||||
end.
|
||||
|
||||
|
||||
@@ -277,4 +277,3 @@ begin
|
||||
end;
|
||||
|
||||
end.
|
||||
|
||||
|
||||
@@ -68,4 +68,3 @@ begin
|
||||
end;
|
||||
|
||||
end.
|
||||
|
||||
|
||||
@@ -281,4 +281,3 @@ begin
|
||||
//DebugWalls;
|
||||
PrintMaze;
|
||||
end.
|
||||
|
||||
|
||||
@@ -2,19 +2,19 @@ import random
|
||||
|
||||
# Python translation by Frank Palazzolo - 2/2021
|
||||
|
||||
print(' '*28+'AMAZING PROGRAM')
|
||||
print(' '*15+'CREATIVE COMPUTING MORRISTOWN, NEW JERSEY')
|
||||
print(" " * 28 + "AMAZING PROGRAM")
|
||||
print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
print()
|
||||
print()
|
||||
print()
|
||||
|
||||
while True:
|
||||
width, length = input('What are your width and length?').split(',')
|
||||
width, length = input("What are your width and length?").split(",")
|
||||
width = int(width)
|
||||
length = int(length)
|
||||
if width != 1 and length != 1:
|
||||
break
|
||||
print('Meaningless dimensions. Try again.')
|
||||
print("Meaningless dimensions. Try again.")
|
||||
|
||||
# Build two 2D arrays
|
||||
#
|
||||
@@ -98,24 +98,21 @@ walls[row][col]=walls[row][col]+1
|
||||
# Print the maze
|
||||
for col in range(width):
|
||||
if col == enter_col:
|
||||
print('. ',end='')
|
||||
print(". ", end="")
|
||||
else:
|
||||
print('.--',end='')
|
||||
print('.')
|
||||
print(".--", end="")
|
||||
print(".")
|
||||
for row in range(length):
|
||||
print('I',end='')
|
||||
print("I", end="")
|
||||
for col in range(width):
|
||||
if walls[row][col] < 2:
|
||||
print(' I',end='')
|
||||
print(" I", end="")
|
||||
else:
|
||||
print(' ',end='')
|
||||
print(" ", end="")
|
||||
print()
|
||||
for col in range(width):
|
||||
if walls[row][col] == 0 or walls[row][col] == 2:
|
||||
print(':--',end='')
|
||||
print(":--", end="")
|
||||
else:
|
||||
print(': ',end='')
|
||||
print('.')
|
||||
|
||||
|
||||
|
||||
print(": ", end="")
|
||||
print(".")
|
||||
|
||||
@@ -244,4 +244,3 @@ public class Animal {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -52,4 +52,3 @@ class AnimalJavaTest : ConsoleTest() {
|
||||
THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT.
|
||||
"""
|
||||
}
|
||||
|
||||
|
||||
@@ -52,4 +52,3 @@ class AnimalKtTest : ConsoleTest() {
|
||||
THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT.
|
||||
"""
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ class Node:
|
||||
# we replace the animal with a new question
|
||||
self.text = new_question
|
||||
|
||||
if answer_new_ques == 'y':
|
||||
if answer_new_ques == "y":
|
||||
self.yes_node = Node(new_animal, None, None)
|
||||
self.no_node = Node(old_animal, None, None)
|
||||
else:
|
||||
@@ -79,7 +79,7 @@ def list_known_animals(root_node):
|
||||
return
|
||||
|
||||
if root_node.is_leaf():
|
||||
print(root_node.text, end=' '*11)
|
||||
print(root_node.text, end=" " * 11)
|
||||
return
|
||||
|
||||
if root_node.yes_node:
|
||||
@@ -96,13 +96,13 @@ def parse_input(message, check_list, root_node):
|
||||
try:
|
||||
inp = input(message)
|
||||
|
||||
if check_list and inp.lower() == 'list':
|
||||
print('Animals I already know are:')
|
||||
if check_list and inp.lower() == "list":
|
||||
print("Animals I already know are:")
|
||||
list_known_animals(root_node)
|
||||
print('\n')
|
||||
print("\n")
|
||||
|
||||
token = inp[0].lower()
|
||||
if token == 'y' or token == 'n':
|
||||
if token == "y" or token == "n":
|
||||
correct_input = True
|
||||
except IndexError:
|
||||
pass
|
||||
@@ -111,28 +111,27 @@ def parse_input(message, check_list, root_node):
|
||||
|
||||
|
||||
def avoid_void_input(message):
|
||||
answer = ''
|
||||
while answer == '':
|
||||
answer = ""
|
||||
while answer == "":
|
||||
answer = input(message)
|
||||
return answer
|
||||
|
||||
|
||||
def initial_message():
|
||||
print(' '*32 + 'Animal')
|
||||
print(' '*15 + 'Creative Computing Morristown, New Jersey\n')
|
||||
print('Play ´Guess the Animal´')
|
||||
print('Think of an animal and the computer will try to guess it.\n')
|
||||
print(" " * 32 + "Animal")
|
||||
print(" " * 15 + "Creative Computing Morristown, New Jersey\n")
|
||||
print("Play ´Guess the Animal´")
|
||||
print("Think of an animal and the computer will try to guess it.\n")
|
||||
|
||||
|
||||
# Initial tree
|
||||
yes_child = Node('Fish', None, None)
|
||||
no_child = Node('Bird', None, None)
|
||||
root = Node('Does it swim?', yes_child, no_child)
|
||||
yes_child = Node("Fish", None, None)
|
||||
no_child = Node("Bird", None, None)
|
||||
root = Node("Does it swim?", yes_child, no_child)
|
||||
|
||||
# Main loop of game
|
||||
initial_message()
|
||||
keep_playing = parse_input(
|
||||
'Are you thinking of an animal? ', True, root) == 'y'
|
||||
keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y"
|
||||
while keep_playing:
|
||||
keep_asking = True
|
||||
# Start traversing the tree by the root
|
||||
@@ -144,33 +143,37 @@ while keep_playing:
|
||||
# we have to keep asking i.e. traversing nodes
|
||||
answer = parse_input(actual_node.text, False, None)
|
||||
|
||||
if answer == 'y':
|
||||
if answer == "y":
|
||||
actual_node = actual_node.yes_node
|
||||
else:
|
||||
actual_node = actual_node.no_node
|
||||
else:
|
||||
# we have reached a possible answer
|
||||
answer = parse_input('Is it a {}? '.format(
|
||||
actual_node.text), False, None)
|
||||
if answer == 'n':
|
||||
answer = parse_input(f"Is it a {actual_node.text}? ", False, None)
|
||||
if answer == "n":
|
||||
# add the new animal to the tree
|
||||
new_animal = avoid_void_input(
|
||||
'The animal you were thinking of was a ? ')
|
||||
"The animal you were thinking of was a ? "
|
||||
)
|
||||
new_question = avoid_void_input(
|
||||
'Please type in a question that would distinguish a {} from a {}: '.format(new_animal, actual_node.text))
|
||||
"Please type in a question that would distinguish a {} from a {}: ".format(
|
||||
new_animal, actual_node.text
|
||||
)
|
||||
)
|
||||
answer_new_question = parse_input(
|
||||
'for a {} the answer would be: '.format(new_animal), False, None)
|
||||
f"for a {new_animal} the answer would be: ", False, None
|
||||
)
|
||||
|
||||
actual_node.update_node(
|
||||
new_question+'?', answer_new_question, new_animal)
|
||||
new_question + "?", answer_new_question, new_animal
|
||||
)
|
||||
|
||||
else:
|
||||
print("Why not try another animal?")
|
||||
|
||||
keep_asking = False
|
||||
|
||||
keep_playing = parse_input(
|
||||
'Are you thinking of an animal? ', True, root) == 'y'
|
||||
keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y"
|
||||
|
||||
|
||||
########################################################
|
||||
|
||||
@@ -128,6 +128,3 @@ public class Bagels {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ import random
|
||||
MAX_GUESSES = 20
|
||||
|
||||
|
||||
|
||||
def print_rules():
|
||||
print("\nI am thinking of a three-digit number. Try to guess")
|
||||
print("my number and I will give you clues as follows:")
|
||||
@@ -46,7 +45,6 @@ def print_rules():
|
||||
print(" BAGELS - No digits correct")
|
||||
|
||||
|
||||
|
||||
def pick_number():
|
||||
# Note that this returns a list of individual digits
|
||||
# as separate strings, not a single integer or string
|
||||
@@ -57,7 +55,6 @@ def pick_number():
|
||||
return num
|
||||
|
||||
|
||||
|
||||
def get_valid_guess():
|
||||
valid = False
|
||||
while not valid:
|
||||
@@ -71,8 +68,9 @@ def get_valid_guess():
|
||||
if len(set(guess)) == 3:
|
||||
valid = True
|
||||
else:
|
||||
print("Oh, I forgot to tell you that " +
|
||||
"the number I have in mind")
|
||||
print(
|
||||
"Oh, I forgot to tell you that " + "the number I have in mind"
|
||||
)
|
||||
print("has no two digits the same.")
|
||||
else:
|
||||
print("What?")
|
||||
@@ -82,7 +80,6 @@ def get_valid_guess():
|
||||
return guess
|
||||
|
||||
|
||||
|
||||
def build_result_string(num, guess):
|
||||
|
||||
result = ""
|
||||
@@ -110,8 +107,6 @@ def build_result_string(num, guess):
|
||||
return result
|
||||
|
||||
|
||||
|
||||
|
||||
######################################################################
|
||||
|
||||
|
||||
@@ -123,7 +118,7 @@ print("\n\n")
|
||||
# Anything other than N* will show the rules
|
||||
response = input("Would you like the rules (Yes or No)? ")
|
||||
if len(response) > 0:
|
||||
if response.upper()[0] != 'N':
|
||||
if response.upper()[0] != "N":
|
||||
print_rules()
|
||||
else:
|
||||
print_rules()
|
||||
@@ -134,7 +129,7 @@ while still_running:
|
||||
|
||||
# New round
|
||||
num = pick_number()
|
||||
num_str = ''.join(num)
|
||||
num_str = "".join(num)
|
||||
guesses = 1
|
||||
|
||||
print("\nO.K. I have a number in mind.")
|
||||
@@ -152,11 +147,9 @@ while still_running:
|
||||
guesses += 1
|
||||
if guesses > MAX_GUESSES:
|
||||
print("Oh well")
|
||||
print(f"That's {MAX_GUESSES} guesses. " +
|
||||
"My number was " + num_str)
|
||||
print(f"That's {MAX_GUESSES} guesses. " + "My number was " + num_str)
|
||||
guessing = False
|
||||
|
||||
|
||||
valid_response = False
|
||||
while not valid_response:
|
||||
response = input("Play again (Yes or No)? ")
|
||||
@@ -172,7 +165,6 @@ if games_won > 0:
|
||||
print("Hope you had fun. Bye.\n")
|
||||
|
||||
|
||||
|
||||
######################################################################
|
||||
#
|
||||
# Porting Notes
|
||||
@@ -192,10 +184,3 @@ print("Hope you had fun. Bye.\n")
|
||||
# that creates the "result" string?
|
||||
#
|
||||
######################################################################
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -77,8 +77,7 @@ def print_banner():
|
||||
g1 = 0
|
||||
if input("Centered ").lower().startswith("y"):
|
||||
g1 = 1
|
||||
mStr = input(
|
||||
"Character (type 'ALL' if you want character being printed) ").upper()
|
||||
mStr = input("Character (type 'ALL' if you want character being printed) ").upper()
|
||||
aStr = input("Statement ")
|
||||
# This means to prepare printer, just press Enter
|
||||
oStr = input("Set page ")
|
||||
|
||||
@@ -463,7 +463,3 @@ public class Basketball {
|
||||
Basketball new_game = new Basketball();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import random
|
||||
# You are able to choose your shot types as well as defensive formations
|
||||
|
||||
|
||||
class Basketball():
|
||||
class Basketball:
|
||||
def __init__(self):
|
||||
self.time = 0
|
||||
self.score = [0, 0] # first value is opponents score, second is home
|
||||
@@ -22,12 +22,14 @@ class Basketball():
|
||||
print("This is Dartmouth College basketball. ")
|
||||
print("Υou will be Dartmouth captain and playmaker.")
|
||||
print("Call shots as follows:")
|
||||
print("1. Long (30ft.) Jump Shot; 2. Short (15 ft.) Jump Shot; "
|
||||
+ "3. Lay up; 4. Set Shot")
|
||||
print(
|
||||
"1. Long (30ft.) Jump Shot; 2. Short (15 ft.) Jump Shot; "
|
||||
+ "3. Lay up; 4. Set Shot"
|
||||
)
|
||||
print("Both teams will use the same defense. Call Defense as follows:")
|
||||
print("6. Press; 6.5 Man-to-Man; 7. Zone; 7.5 None.")
|
||||
print("To change defense, just type 0 as your next shot.")
|
||||
print("Your starting defense will be? ", end='')
|
||||
print("Your starting defense will be? ", end="")
|
||||
|
||||
# takes input for a defense
|
||||
try:
|
||||
@@ -38,7 +40,7 @@ class Basketball():
|
||||
|
||||
# if the input wasn't a valid defense, takes input again
|
||||
while self.defense not in self.defense_choices:
|
||||
print("Your new defensive allignment is? ", end='')
|
||||
print("Your new defensive allignment is? ", end="")
|
||||
try:
|
||||
self.defense = float(input())
|
||||
|
||||
@@ -46,7 +48,7 @@ class Basketball():
|
||||
continue
|
||||
|
||||
# takes input for opponent's name
|
||||
print("\nChoose your opponent? ", end='')
|
||||
print("\nChoose your opponent? ", end="")
|
||||
|
||||
self.opponent = input()
|
||||
self.start_of_period()
|
||||
@@ -58,7 +60,7 @@ class Basketball():
|
||||
self.print_score()
|
||||
|
||||
def ball_passed_back(self):
|
||||
print("Ball passed back to you. ", end='')
|
||||
print("Ball passed back to you. ", end="")
|
||||
self.dartmouth_ball()
|
||||
|
||||
# change defense, called when the user enters 0 for their shot
|
||||
@@ -77,8 +79,8 @@ class Basketball():
|
||||
# simulates two foul shots for a player and adds the points
|
||||
def foul_shots(self, team):
|
||||
print("Shooter fouled. Two shots.")
|
||||
if random.random() > .49:
|
||||
if random.random() > .75:
|
||||
if random.random() > 0.49:
|
||||
if random.random() > 0.75:
|
||||
print("Both shots missed.")
|
||||
else:
|
||||
print("Shooter makes one shot and misses one.")
|
||||
@@ -97,13 +99,12 @@ class Basketball():
|
||||
|
||||
# prints the current score
|
||||
def print_score(self):
|
||||
print("Score: " + str(self.score[1])
|
||||
+ " to " + str(self.score[0]) + "\n")
|
||||
print("Score: " + str(self.score[1]) + " to " + str(self.score[0]) + "\n")
|
||||
|
||||
# simulates a center jump for posession at the beginning of a period
|
||||
def start_of_period(self):
|
||||
print("Center jump")
|
||||
if random.random() > .6:
|
||||
if random.random() > 0.6:
|
||||
print("Dartmouth controls the tap.\n")
|
||||
self.dartmouth_ball()
|
||||
else:
|
||||
@@ -123,10 +124,10 @@ class Basketball():
|
||||
self.two_minute_warning()
|
||||
print("Jump Shot.")
|
||||
# simulates chances of different possible outcomes
|
||||
if random.random() > .341 * self.defense / 8:
|
||||
if random.random() > .682 * self.defense / 8:
|
||||
if random.random() > .782 * self.defense / 8:
|
||||
if random.random() > .843 * self.defense / 8:
|
||||
if random.random() > 0.341 * self.defense / 8:
|
||||
if random.random() > 0.682 * self.defense / 8:
|
||||
if random.random() > 0.782 * self.defense / 8:
|
||||
if random.random() > 0.843 * self.defense / 8:
|
||||
print("Charging foul. Dartmouth loses ball.\n")
|
||||
self.opponent_ball()
|
||||
else:
|
||||
@@ -134,24 +135,26 @@ class Basketball():
|
||||
self.foul_shots(1)
|
||||
self.opponent_ball()
|
||||
else:
|
||||
if random.random() > .5:
|
||||
print("Shot is blocked. Ball controlled by " +
|
||||
self.opponent + ".\n")
|
||||
if random.random() > 0.5:
|
||||
print(
|
||||
"Shot is blocked. Ball controlled by "
|
||||
+ self.opponent
|
||||
+ ".\n"
|
||||
)
|
||||
self.opponent_ball()
|
||||
else:
|
||||
print("Shot is blocked. Ball controlled by Dartmouth.")
|
||||
self.dartmouth_ball()
|
||||
else:
|
||||
print("Shot is off target.")
|
||||
if self.defense / 6 * random.random() > .45:
|
||||
if self.defense / 6 * random.random() > 0.45:
|
||||
print("Rebound to " + self.opponent + "\n")
|
||||
self.opponent_ball()
|
||||
else:
|
||||
print("Dartmouth controls the rebound.")
|
||||
if random.random() > .4:
|
||||
if self.defense == 6 and random.random() > .6:
|
||||
print("Pass stolen by " + self.opponent
|
||||
+ ", easy lay up")
|
||||
if random.random() > 0.4:
|
||||
if self.defense == 6 and random.random() > 0.6:
|
||||
print("Pass stolen by " + self.opponent + ", easy lay up")
|
||||
self.add_points(0, 2)
|
||||
self.dartmouth_ball()
|
||||
else:
|
||||
@@ -182,10 +185,10 @@ class Basketball():
|
||||
self.change_defense()
|
||||
|
||||
# simulates different outcomes after a lay up or set shot
|
||||
if 7/self.defense*random.random() > .4:
|
||||
if 7/self.defense*random.random() > .7:
|
||||
if 7/self.defense*random.random() > .875:
|
||||
if 7/self.defense*random.random() > .925:
|
||||
if 7 / self.defense * random.random() > 0.4:
|
||||
if 7 / self.defense * random.random() > 0.7:
|
||||
if 7 / self.defense * random.random() > 0.875:
|
||||
if 7 / self.defense * random.random() > 0.925:
|
||||
print("Charging foul. Dartmouth loses the ball.\n")
|
||||
self.opponent_ball()
|
||||
else:
|
||||
@@ -198,7 +201,7 @@ class Basketball():
|
||||
print("Shot is off the rim.")
|
||||
if random.random() > 2 / 3:
|
||||
print("Dartmouth controls the rebound.")
|
||||
if random.random() > .4:
|
||||
if random.random() > 0.4:
|
||||
print("Ball passed back to you.\n")
|
||||
self.dartmouth_ball()
|
||||
else:
|
||||
@@ -213,7 +216,7 @@ class Basketball():
|
||||
|
||||
# plays out a Dartmouth posession, starting with your choice of shot
|
||||
def dartmouth_ball(self):
|
||||
print("Your shot? ", end='')
|
||||
print("Your shot? ", end="")
|
||||
self.shot = None
|
||||
try:
|
||||
self.shot = int(input())
|
||||
@@ -221,13 +224,13 @@ class Basketball():
|
||||
self.shot = None
|
||||
|
||||
while self.shot not in self.shot_choices:
|
||||
print("Incorrect answer. Retype it. Your shot? ", end='')
|
||||
print("Incorrect answer. Retype it. Your shot? ", end="")
|
||||
try:
|
||||
self.shot = int(input())
|
||||
except:
|
||||
continue
|
||||
|
||||
if self.time < 100 or random.random() < .5:
|
||||
if self.time < 100 or random.random() < 0.5:
|
||||
if self.shot == 1 or self.shot == 2:
|
||||
self.dartmouth_jump_shot()
|
||||
else:
|
||||
@@ -235,13 +238,25 @@ class Basketball():
|
||||
else:
|
||||
if self.score[0] != self.score[1]:
|
||||
print("\n ***** End Of Game *****")
|
||||
print("Final Score: Dartmouth: " + str(self.score[1]) + " "
|
||||
+ self.opponent + ": " + str(self.score[0]))
|
||||
print(
|
||||
"Final Score: Dartmouth: "
|
||||
+ str(self.score[1])
|
||||
+ " "
|
||||
+ self.opponent
|
||||
+ ": "
|
||||
+ str(self.score[0])
|
||||
)
|
||||
else:
|
||||
print("\n ***** End Of Second Half *****")
|
||||
print("Score at end of regulation time:")
|
||||
print(" Dartmouth: " + str(self.score[1]) + " " +
|
||||
self.opponent + ": " + str(self.score[0]))
|
||||
print(
|
||||
" Dartmouth: "
|
||||
+ str(self.score[1])
|
||||
+ " "
|
||||
+ self.opponent
|
||||
+ ": "
|
||||
+ str(self.score[0])
|
||||
)
|
||||
print("Begin two minute overtime period")
|
||||
self.time = 93
|
||||
self.start_of_period()
|
||||
@@ -249,9 +264,9 @@ class Basketball():
|
||||
# simulates the opponents jumpshot
|
||||
def opponent_jumpshot(self):
|
||||
print("Jump Shot.")
|
||||
if 8/self.defense*random.random() > .35:
|
||||
if 8/self.defense*random.random() > .75:
|
||||
if 8/self.defense*random.random() > .9:
|
||||
if 8 / self.defense * random.random() > 0.35:
|
||||
if 8 / self.defense * random.random() > 0.75:
|
||||
if 8 / self.defense * random.random() > 0.9:
|
||||
print("Offensive foul. Dartmouth's ball.\n")
|
||||
self.dartmouth_ball()
|
||||
else:
|
||||
@@ -259,27 +274,25 @@ class Basketball():
|
||||
self.dartmouth_ball()
|
||||
else:
|
||||
print("Shot is off the rim.")
|
||||
if self.defense/6*random.random() > .5:
|
||||
if self.defense / 6 * random.random() > 0.5:
|
||||
print(self.opponent + " controls the rebound.")
|
||||
if self.defense == 6:
|
||||
if random.random() > .75:
|
||||
if random.random() > 0.75:
|
||||
print("Ball stolen. Easy lay up for Dartmouth.")
|
||||
self.add_points(1, 2)
|
||||
self.opponent_ball()
|
||||
else:
|
||||
if random.random() > .5:
|
||||
if random.random() > 0.5:
|
||||
print("")
|
||||
self.opponent_non_jumpshot()
|
||||
else:
|
||||
print("Pass back to " + self.opponent +
|
||||
" guard.\n")
|
||||
print("Pass back to " + self.opponent + " guard.\n")
|
||||
self.opponent_ball()
|
||||
else:
|
||||
if random.random() > .5:
|
||||
if random.random() > 0.5:
|
||||
self.opponent_non_jumpshot()
|
||||
else:
|
||||
print("Pass back to " + self.opponent +
|
||||
" guard.\n")
|
||||
print("Pass back to " + self.opponent + " guard.\n")
|
||||
self.opponent_ball()
|
||||
else:
|
||||
print("Dartmouth controls the rebound.\n")
|
||||
@@ -295,25 +308,24 @@ class Basketball():
|
||||
print("Set shot.")
|
||||
else:
|
||||
print("Lay up")
|
||||
if 7/self.defense*random.random() > .413:
|
||||
if 7 / self.defense * random.random() > 0.413:
|
||||
print("Shot is missed.")
|
||||
if self.defense/6*random.random() > .5:
|
||||
if self.defense / 6 * random.random() > 0.5:
|
||||
print(self.opponent + " controls the rebound.")
|
||||
if self.defense == 6:
|
||||
if random.random() > .75:
|
||||
if random.random() > 0.75:
|
||||
print("Ball stolen. Easy lay up for Dartmouth.")
|
||||
self.add_points(1, 2)
|
||||
self.opponent_ball()
|
||||
else:
|
||||
if random.random() > .5:
|
||||
if random.random() > 0.5:
|
||||
print("")
|
||||
self.opponent_non_jumpshot()
|
||||
else:
|
||||
print("Pass back to " + self.opponent +
|
||||
" guard.\n")
|
||||
print("Pass back to " + self.opponent + " guard.\n")
|
||||
self.opponent_ball()
|
||||
else:
|
||||
if random.random() > .5:
|
||||
if random.random() > 0.5:
|
||||
print("")
|
||||
self.opponent_non_jumpshot()
|
||||
else:
|
||||
|
||||
@@ -27,4 +27,3 @@ while (true)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -8,4 +8,3 @@ Functional changes from Original
|
||||
- handle edge condition for end game where the minimum draw amount is greater than the number of items remaining in the pile
|
||||
- Takes into account the width of the console
|
||||
- Mulilingual Support (English/French currently)
|
||||
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class WinOptions(Enum):
|
||||
Undefined = 0
|
||||
TakeLast = 1
|
||||
AvoidLast = 2
|
||||
|
||||
|
||||
class StartOptions(Enum):
|
||||
Undefined = 0
|
||||
ComputerFirst = 1
|
||||
PlayerFirst = 2
|
||||
|
||||
|
||||
def PrintIntro():
|
||||
'''Prints out the introduction and rules for the game.'''
|
||||
print("BATNUM".rjust(33, ' '))
|
||||
print("CREATIVE COMPUTING MORRISSTOWN, NEW JERSEY".rjust(15, ' '))
|
||||
"""Prints out the introduction and rules for the game."""
|
||||
print("BATNUM".rjust(33, " "))
|
||||
print("CREATIVE COMPUTING MORRISSTOWN, NEW JERSEY".rjust(15, " "))
|
||||
print()
|
||||
print()
|
||||
print()
|
||||
@@ -29,8 +32,9 @@ def PrintIntro():
|
||||
print()
|
||||
return
|
||||
|
||||
|
||||
def GetParams():
|
||||
'''This requests the necessary parameters to play the game.
|
||||
"""This requests the necessary parameters to play the game.
|
||||
|
||||
Returns a set with the five game parameters:
|
||||
pileSize - the starting size of the object pile
|
||||
@@ -40,7 +44,7 @@ def GetParams():
|
||||
or 2 if the player is first
|
||||
winOption - 1 if the goal is to take the last object
|
||||
or 2 if the goal is to not take the last object
|
||||
'''
|
||||
"""
|
||||
pileSize = 0
|
||||
winOption = WinOptions.Undefined
|
||||
minSelect = 0
|
||||
@@ -52,17 +56,20 @@ def GetParams():
|
||||
while winOption == WinOptions.Undefined:
|
||||
winOption = int(input("ENTER WIN OPTION - 1 TO TAKE LAST, 2 TO AVOID LAST: "))
|
||||
while minSelect < 1 or maxSelect < 1 or minSelect > maxSelect:
|
||||
(minSelect, maxSelect) = [int(x) for x in input("ENTER MIN AND MAX ").split(' ')]
|
||||
(minSelect, maxSelect) = (
|
||||
int(x) for x in input("ENTER MIN AND MAX ").split(" ")
|
||||
)
|
||||
while startOption == StartOptions.Undefined:
|
||||
startOption = int(input("ENTER START OPTION - 1 COMPUTER FIRST, 2 YOU FIRST "))
|
||||
return (pileSize, minSelect, maxSelect, startOption, winOption)
|
||||
|
||||
|
||||
def PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
'''This handles the player's turn - asking the player how many objects
|
||||
"""This handles the player's turn - asking the player how many objects
|
||||
to take and doing some basic validation around that input. Then it
|
||||
checks for any win conditions.
|
||||
|
||||
Returns a boolean indicating whether the game is over and the new pileSize.'''
|
||||
Returns a boolean indicating whether the game is over and the new pileSize."""
|
||||
playerDone = False
|
||||
while not playerDone:
|
||||
playerMove = int(input("YOUR MOVE "))
|
||||
@@ -82,10 +89,11 @@ def PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
return (True, pileSize)
|
||||
return (False, pileSize)
|
||||
|
||||
|
||||
def ComputerPick(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
'''This handles the logic to determine how many objects the computer
|
||||
"""This handles the logic to determine how many objects the computer
|
||||
will select on its turn.
|
||||
'''
|
||||
"""
|
||||
q = pileSize - 1 if winOption == WinOptions.AvoidLast else pileSize
|
||||
c = minSelect + maxSelect
|
||||
computerPick = q - (c * int(q / c))
|
||||
@@ -95,12 +103,13 @@ def ComputerPick(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
computerPick = maxSelect
|
||||
return computerPick
|
||||
|
||||
|
||||
def ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
'''This handles the computer's turn - first checking for the various
|
||||
"""This handles the computer's turn - first checking for the various
|
||||
win/lose conditions and then calculating how many objects
|
||||
the computer will take.
|
||||
|
||||
Returns a boolean indicating whether the game is over and the new pileSize.'''
|
||||
Returns a boolean indicating whether the game is over and the new pileSize."""
|
||||
# First, check for win conditions on this move
|
||||
# In this case, we win by taking the last object and
|
||||
# the remaining pile is less than max select
|
||||
@@ -121,10 +130,11 @@ def ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
print(f"COMPUTER TAKES {currSel} AND LEAVES {pileSize}")
|
||||
return (False, pileSize)
|
||||
|
||||
|
||||
def PlayGame(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
'''This is the main game loop - repeating each turn until one
|
||||
"""This is the main game loop - repeating each turn until one
|
||||
of the win/lose conditions is met.
|
||||
'''
|
||||
"""
|
||||
gameOver = False
|
||||
# playersTurn is a boolean keeping track of whether it's the
|
||||
# player's or computer's turn
|
||||
@@ -132,16 +142,21 @@ def PlayGame(pileSize, minSelect, maxSelect, startOption, winOption):
|
||||
|
||||
while not gameOver:
|
||||
if playersTurn:
|
||||
(gameOver, pileSize) = PlayerMove(pileSize, minSelect, maxSelect, startOption, winOption)
|
||||
(gameOver, pileSize) = PlayerMove(
|
||||
pileSize, minSelect, maxSelect, startOption, winOption
|
||||
)
|
||||
playersTurn = False
|
||||
if gameOver:
|
||||
return
|
||||
if not playersTurn:
|
||||
(gameOver, pileSize) = ComputerMove(pileSize, minSelect, maxSelect, startOption, winOption)
|
||||
(gameOver, pileSize) = ComputerMove(
|
||||
pileSize, minSelect, maxSelect, startOption, winOption
|
||||
)
|
||||
playersTurn = True
|
||||
|
||||
return
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
pileSize = 0
|
||||
|
||||
@@ -40,8 +40,9 @@ def place_ship(sea: SeaType, size: int, code: int) -> None:
|
||||
point = add_vector(point, vector)
|
||||
points.append(point)
|
||||
|
||||
if (not all([is_within_sea(point, sea) for point in points]) or
|
||||
any([value_at(point, sea) for point in points])):
|
||||
if not all([is_within_sea(point, sea) for point in points]) or any(
|
||||
[value_at(point, sea) for point in points]
|
||||
):
|
||||
# ship out of bounds or crosses other ship, trying again
|
||||
continue
|
||||
|
||||
@@ -54,7 +55,7 @@ def place_ship(sea: SeaType, size: int, code: int) -> None:
|
||||
|
||||
def print_encoded_sea(sea: SeaType) -> None:
|
||||
for x in range(len(sea)):
|
||||
print(' '.join([str(sea[y][x]) for y in range(len(sea) - 1, -1, -1)]))
|
||||
print(" ".join([str(sea[y][x]) for y in range(len(sea) - 1, -1, -1)]))
|
||||
|
||||
|
||||
def is_within_sea(point: PointType, sea: SeaType) -> bool:
|
||||
@@ -80,8 +81,8 @@ def set_value_at(value: int, point: PointType, sea: SeaType) -> None:
|
||||
def get_next_target(sea: SeaType) -> PointType:
|
||||
while True:
|
||||
try:
|
||||
guess = input('? ')
|
||||
point = guess.split(',')
|
||||
guess = input("? ")
|
||||
point = guess.split(",")
|
||||
|
||||
if len(point) != 2:
|
||||
raise ValueError()
|
||||
@@ -93,7 +94,9 @@ def get_next_target(sea: SeaType) -> PointType:
|
||||
|
||||
return point
|
||||
except ValueError:
|
||||
print(f'INVALID. SPECIFY TWO NUMBERS FROM 1 TO {len(sea)}, SEPARATED BY A COMMA.')
|
||||
print(
|
||||
f"INVALID. SPECIFY TWO NUMBERS FROM 1 TO {len(sea)}, SEPARATED BY A COMMA."
|
||||
)
|
||||
|
||||
|
||||
def setup_ships(sea: SeaType):
|
||||
@@ -106,23 +109,27 @@ def setup_ships(sea: SeaType):
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sea = tuple(([0 for _ in range(SEA_WIDTH)] for _ in range(SEA_WIDTH)))
|
||||
sea = tuple([0 for _ in range(SEA_WIDTH)] for _ in range(SEA_WIDTH))
|
||||
setup_ships(sea)
|
||||
print(f'''
|
||||
print(
|
||||
f"""
|
||||
BATTLE
|
||||
CREATIVE COMPUTING MORRISTOWN, NEW JERSEY
|
||||
|
||||
THE FOLLOWING CODE OF THE BAD GUYS' FLEET DISPOSITION
|
||||
HAS BEEN CAPTURED BUT NOT DECODED:
|
||||
|
||||
''')
|
||||
"""
|
||||
)
|
||||
print_encoded_sea(sea)
|
||||
print('''
|
||||
print(
|
||||
"""
|
||||
|
||||
DE-CODE IT AND USE IT IF YOU CAN
|
||||
BUT KEEP THE DE-CODING METHOD A SECRET.
|
||||
|
||||
START GAME''')
|
||||
START GAME"""
|
||||
)
|
||||
splashes = 0
|
||||
hits = 0
|
||||
|
||||
@@ -131,33 +138,39 @@ START GAME''')
|
||||
target_value = value_at(target, sea)
|
||||
|
||||
if target_value < 0:
|
||||
print(f'YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT.')
|
||||
print(
|
||||
f"YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT."
|
||||
)
|
||||
|
||||
if target_value <= 0:
|
||||
print('SPLASH! TRY AGAIN.')
|
||||
print("SPLASH! TRY AGAIN.")
|
||||
splashes += 1
|
||||
continue
|
||||
|
||||
print(f'A DIRECT HIT ON SHIP NUMBER {target_value}')
|
||||
print(f"A DIRECT HIT ON SHIP NUMBER {target_value}")
|
||||
hits += 1
|
||||
set_value_at(-target_value, target, sea)
|
||||
|
||||
if not has_ship(sea, target_value):
|
||||
print('AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.')
|
||||
print('SO FAR, THE BAD GUYS HAVE LOST')
|
||||
print(f'{count_sunk(sea, 1, 2)} DESTROYER(S),',
|
||||
f'{count_sunk(sea, 3, 4)} CRUISER(S),',
|
||||
f'AND {count_sunk(sea, 5, 6)} AIRCRAFT CARRIER(S).')
|
||||
print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.")
|
||||
print("SO FAR, THE BAD GUYS HAVE LOST")
|
||||
print(
|
||||
f"{count_sunk(sea, 1, 2)} DESTROYER(S),",
|
||||
f"{count_sunk(sea, 3, 4)} CRUISER(S),",
|
||||
f"AND {count_sunk(sea, 5, 6)} AIRCRAFT CARRIER(S).",
|
||||
)
|
||||
|
||||
if any(has_ship(sea, code) for code in range(1, 7)):
|
||||
print(f'YOUR CURRENT SPLASH/HIT RATIO IS {splashes}/{hits}')
|
||||
print(f"YOUR CURRENT SPLASH/HIT RATIO IS {splashes}/{hits}")
|
||||
continue
|
||||
|
||||
print('YOU HAVE TOTALLY WIPED OUT THE BAD GUYS\' FLEET '
|
||||
f'WITH A FINAL SPLASH/HIT RATIO OF {splashes}/{hits}')
|
||||
print(
|
||||
"YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET "
|
||||
f"WITH A FINAL SPLASH/HIT RATIO OF {splashes}/{hits}"
|
||||
)
|
||||
|
||||
if not splashes:
|
||||
print('CONGRATULATIONS -- A DIRECT HIT EVERY TIME.')
|
||||
print("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.")
|
||||
|
||||
print("\n****************************")
|
||||
break
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
from dataclasses import dataclass
|
||||
from random import randrange
|
||||
|
||||
|
||||
DESTROYER_LENGTH = 2
|
||||
CRUISER_LENGTH = 3
|
||||
AIRCRAFT_CARRIER_LENGTH = 4
|
||||
@@ -14,10 +13,10 @@ class Point:
|
||||
y: int
|
||||
|
||||
@classmethod
|
||||
def random(cls, start: int, stop: int) -> 'Point':
|
||||
def random(cls, start: int, stop: int) -> "Point":
|
||||
return Point(randrange(start, stop), randrange(start, stop))
|
||||
|
||||
def __add__(self, vector: 'Vector') -> 'Point':
|
||||
def __add__(self, vector: "Vector") -> "Point":
|
||||
return Point(self.x + vector.x, self.y + vector.y)
|
||||
|
||||
|
||||
@@ -27,10 +26,10 @@ class Vector:
|
||||
y: int
|
||||
|
||||
@staticmethod
|
||||
def random() -> 'Vector':
|
||||
def random() -> "Vector":
|
||||
return Vector(randrange(-1, 2, 2), randrange(-1, 2, 2))
|
||||
|
||||
def __mul__(self, factor: int) -> 'Vector':
|
||||
def __mul__(self, factor: int) -> "Vector":
|
||||
return Vector(self.x * factor, self.y * factor)
|
||||
|
||||
|
||||
@@ -38,14 +37,14 @@ class Sea:
|
||||
WIDTH = 6
|
||||
|
||||
def __init__(self):
|
||||
self._graph = tuple(([0 for _ in range(self.WIDTH)] for _ in range(self.WIDTH)))
|
||||
self._graph = tuple([0 for _ in range(self.WIDTH)] for _ in range(self.WIDTH))
|
||||
|
||||
def _validate_item_indices(self, point: Point) -> None:
|
||||
if not isinstance(point, Point):
|
||||
raise ValueError(f'Sea indices must be Points, not {type(point).__name__}')
|
||||
raise ValueError(f"Sea indices must be Points, not {type(point).__name__}")
|
||||
|
||||
if not ((1 <= point.x <= self.WIDTH) and (1 <= point.y <= self.WIDTH)):
|
||||
raise IndexError('Sea index out of range')
|
||||
raise IndexError("Sea index out of range")
|
||||
|
||||
# Allows us to get the value using a point as a key, for example, `sea[Point(3,2)]`
|
||||
def __getitem__(self, point: Point) -> int:
|
||||
@@ -70,9 +69,14 @@ class Sea:
|
||||
# Redefines how python will render this object when asked as a str
|
||||
def __str__(self):
|
||||
# Display it encoded
|
||||
return "\n".join([' '.join([str(self._graph[y][x])
|
||||
for y in range(self.WIDTH - 1, -1, -1)])
|
||||
for x in range(self.WIDTH)])
|
||||
return "\n".join(
|
||||
[
|
||||
" ".join(
|
||||
[str(self._graph[y][x]) for y in range(self.WIDTH - 1, -1, -1)]
|
||||
)
|
||||
for x in range(self.WIDTH)
|
||||
]
|
||||
)
|
||||
|
||||
def has_ship(self, ship_code: int) -> bool:
|
||||
return any(ship_code in row for row in self._graph)
|
||||
@@ -96,8 +100,8 @@ class Battle:
|
||||
def _next_target(self) -> Point:
|
||||
while True:
|
||||
try:
|
||||
guess = input('? ')
|
||||
coordinates = guess.split(',')
|
||||
guess = input("? ")
|
||||
coordinates = guess.split(",")
|
||||
|
||||
if len(coordinates) != 2:
|
||||
raise ValueError()
|
||||
@@ -109,11 +113,13 @@ class Battle:
|
||||
|
||||
return point
|
||||
except ValueError:
|
||||
print(f'INVALID. SPECIFY TWO NUMBERS FROM 1 TO {Sea.WIDTH}, SEPARATED BY A COMMA.')
|
||||
print(
|
||||
f"INVALID. SPECIFY TWO NUMBERS FROM 1 TO {Sea.WIDTH}, SEPARATED BY A COMMA."
|
||||
)
|
||||
|
||||
@property
|
||||
def splash_hit_ratio(self) -> str:
|
||||
return f'{self.splashes}/{self.hits}'
|
||||
return f"{self.splashes}/{self.hits}"
|
||||
|
||||
@property
|
||||
def _is_finished(self) -> bool:
|
||||
@@ -126,8 +132,10 @@ class Battle:
|
||||
# Get potential ship points
|
||||
points = [start + vector * i for i in range(size)]
|
||||
|
||||
if not (all([point in self.sea for point in points]) and
|
||||
not any([self.sea[point] for point in points])):
|
||||
if not (
|
||||
all([point in self.sea for point in points])
|
||||
and not any([self.sea[point] for point in points])
|
||||
):
|
||||
# ship out of bounds or crosses other ship, trying again
|
||||
continue
|
||||
|
||||
@@ -137,53 +145,59 @@ class Battle:
|
||||
|
||||
break
|
||||
|
||||
|
||||
def loop(self):
|
||||
while True:
|
||||
target = self._next_target()
|
||||
target_value = self.sea[target]
|
||||
|
||||
if target_value < 0:
|
||||
print(f'YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT.')
|
||||
print(
|
||||
f"YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT."
|
||||
)
|
||||
|
||||
if target_value <= 0:
|
||||
print('SPLASH! TRY AGAIN.')
|
||||
print("SPLASH! TRY AGAIN.")
|
||||
self.splashes += 1
|
||||
continue
|
||||
|
||||
print(f'A DIRECT HIT ON SHIP NUMBER {target_value}')
|
||||
print(f"A DIRECT HIT ON SHIP NUMBER {target_value}")
|
||||
self.hits += 1
|
||||
self.sea[target] = -target_value
|
||||
|
||||
if not self.sea.has_ship(target_value):
|
||||
print('AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.')
|
||||
print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.")
|
||||
self._display_sunk_report()
|
||||
|
||||
if self._is_finished:
|
||||
self._display_game_end()
|
||||
break
|
||||
|
||||
print(f'YOUR CURRENT SPLASH/HIT RATIO IS {self.splash_hit_ratio}')
|
||||
print(f"YOUR CURRENT SPLASH/HIT RATIO IS {self.splash_hit_ratio}")
|
||||
|
||||
def _display_sunk_report(self):
|
||||
print('SO FAR, THE BAD GUYS HAVE LOST',
|
||||
f'{self.sea.count_sunk(1, 2)} DESTROYER(S),',
|
||||
f'{self.sea.count_sunk(3, 4)} CRUISER(S),',
|
||||
f'AND {self.sea.count_sunk(5, 6)} AIRCRAFT CARRIER(S).')
|
||||
print(
|
||||
"SO FAR, THE BAD GUYS HAVE LOST",
|
||||
f"{self.sea.count_sunk(1, 2)} DESTROYER(S),",
|
||||
f"{self.sea.count_sunk(3, 4)} CRUISER(S),",
|
||||
f"AND {self.sea.count_sunk(5, 6)} AIRCRAFT CARRIER(S).",
|
||||
)
|
||||
|
||||
def _display_game_end(self):
|
||||
print('YOU HAVE TOTALLY WIPED OUT THE BAD GUYS\' FLEET '
|
||||
f'WITH A FINAL SPLASH/HIT RATIO OF {self.splash_hit_ratio}')
|
||||
print(
|
||||
"YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET "
|
||||
f"WITH A FINAL SPLASH/HIT RATIO OF {self.splash_hit_ratio}"
|
||||
)
|
||||
|
||||
if not self.splashes:
|
||||
print('CONGRATULATIONS -- A DIRECT HIT EVERY TIME.')
|
||||
print("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.")
|
||||
|
||||
print("\n****************************")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
game = Battle()
|
||||
print(f'''
|
||||
print(
|
||||
f"""
|
||||
BATTLE
|
||||
CREATIVE COMPUTING MORRISTOWN, NEW JERSEY
|
||||
|
||||
@@ -195,7 +209,8 @@ HAS BEEN CAPTURED BUT NOT DECODED:
|
||||
DE-CODE IT AND USE IT IF YOU CAN
|
||||
BUT KEEP THE DE-CODING METHOD A SECRET.
|
||||
|
||||
START GAME''')
|
||||
START GAME"""
|
||||
)
|
||||
game.loop()
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import random
|
||||
from functools import partial
|
||||
|
||||
|
||||
def display_intro():
|
||||
print("" * 33 + "BOMBARDMENT")
|
||||
print("" * 15 + " CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
@@ -25,7 +26,7 @@ def display_intro():
|
||||
def display_field():
|
||||
for row in range(5):
|
||||
initial = row * 5 + 1
|
||||
print('\t'.join([str(initial + column) for column in range(5)]))
|
||||
print("\t".join([str(initial + column) for column in range(5)]))
|
||||
|
||||
print("\n" * 9)
|
||||
|
||||
@@ -49,13 +50,13 @@ def prompt_for_player_positions():
|
||||
|
||||
while True:
|
||||
raw_positions = input("WHAT ARE YOUR FOUR POSITIONS? ")
|
||||
positions = set(int(pos) for pos in raw_positions.split())
|
||||
positions = {int(pos) for pos in raw_positions.split()}
|
||||
# Verify user inputs (for example, if the player gives a
|
||||
# a position for 26, the enemy can never hit it)
|
||||
if (len(positions) != 4):
|
||||
if len(positions) != 4:
|
||||
print("PLEASE ENTER 4 UNIQUE POSITIONS\n")
|
||||
continue
|
||||
elif (any(not is_valid_position(pos) for pos in positions)):
|
||||
elif any(not is_valid_position(pos) for pos in positions):
|
||||
print("ALL POSITIONS MUST RANGE (1-25)\n")
|
||||
continue
|
||||
else:
|
||||
@@ -103,17 +104,15 @@ def init_enemy():
|
||||
|
||||
# Messages correspond to outposts remaining (3, 2, 1, 0)
|
||||
PLAYER_PROGRESS_MESSAGES = (
|
||||
"YOU GOT ME, I'M GOING FAST. BUT I'LL GET YOU WHEN\n"
|
||||
"MY TRANSISTO&S RECUP%RA*E!",
|
||||
"YOU GOT ME, I'M GOING FAST. BUT I'LL GET YOU WHEN\n" "MY TRANSISTO&S RECUP%RA*E!",
|
||||
"THREE DOWN, ONE TO GO.\n\n",
|
||||
"TWO DOWN, TWO TO GO.\n\n",
|
||||
"ONE DOWN, THREE TO GO.\n\n"
|
||||
"ONE DOWN, THREE TO GO.\n\n",
|
||||
)
|
||||
|
||||
|
||||
ENEMY_PROGRESS_MESSAGES = (
|
||||
"YOU'RE DEAD. YOUR LAST OUTPOST WAS AT {}. HA, HA, HA.\n"
|
||||
"BETTER LUCK NEXT TIME.",
|
||||
"YOU'RE DEAD. YOUR LAST OUTPOST WAS AT {}. HA, HA, HA.\n" "BETTER LUCK NEXT TIME.",
|
||||
"YOU HAVE ONLY ONE OUTPOST LEFT.\n\n",
|
||||
"YOU HAVE ONLY TWO OUTPOSTS LEFT.\n\n",
|
||||
"YOU HAVE ONLY THREE OUTPOSTS LEFT.\n\n",
|
||||
@@ -128,22 +127,28 @@ def play():
|
||||
player_positions = prompt_for_player_positions()
|
||||
|
||||
# Build partial functions only requiring the target as input
|
||||
player_attacks = partial(attack,
|
||||
player_attacks = partial(
|
||||
attack,
|
||||
positions=enemy_positions,
|
||||
hit_message="YOU GOT ONE OF MY OUTPOSTS!",
|
||||
miss_message="HA, HA YOU MISSED. MY TURN NOW:\n\n",
|
||||
progress_messages=PLAYER_PROGRESS_MESSAGES)
|
||||
progress_messages=PLAYER_PROGRESS_MESSAGES,
|
||||
)
|
||||
|
||||
enemy_attacks = partial(attack,
|
||||
enemy_attacks = partial(
|
||||
attack,
|
||||
positions=player_positions,
|
||||
hit_message="I GOT YOU. IT WON'T BE LONG NOW. POST {} WAS HIT.",
|
||||
miss_message="I MISSED YOU, YOU DIRTY RAT. I PICKED {}. YOUR TURN:\n\n",
|
||||
progress_messages=ENEMY_PROGRESS_MESSAGES)
|
||||
progress_messages=ENEMY_PROGRESS_MESSAGES,
|
||||
)
|
||||
|
||||
enemy_position_choice = init_enemy()
|
||||
|
||||
# Play as long as both player_attacks and enemy_attacks allow to continue
|
||||
while player_attacks(prompt_player_for_target()) and enemy_attacks(enemy_position_choice()):
|
||||
while player_attacks(prompt_player_for_target()) and enemy_attacks(
|
||||
enemy_position_choice()
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -23,4 +23,3 @@ bool UserWantsToPlayAgain(IUserInterface ui)
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ class Player:
|
||||
self.show(pins)
|
||||
pin_count = score - prev_score
|
||||
self.rolls.append(pin_count) # log the number of pins toppled this roll
|
||||
print(f'{pin_count} for {self.name}')
|
||||
print(f"{pin_count} for {self.name}")
|
||||
if score - prev_score == 0:
|
||||
print("GUTTER!!!")
|
||||
if ball == 0:
|
||||
@@ -63,7 +63,7 @@ class Player:
|
||||
|
||||
prev_score = score # remember previous pins to distinguish ...
|
||||
if frame == 9 and extra > 0:
|
||||
print(f'Extra rolls for {self.name}')
|
||||
print(f"Extra rolls for {self.name}")
|
||||
pins = [0] * 10 # reset the pins
|
||||
score = 0
|
||||
for ball in range(extra):
|
||||
@@ -74,48 +74,48 @@ class Player:
|
||||
self.rolls.append(score)
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.name}: {self.rolls}, total:{calculate_score(self.rolls)}'
|
||||
return f"{self.name}: {self.rolls}, total:{calculate_score(self.rolls)}"
|
||||
|
||||
def show(self, pins):
|
||||
pins_iter = iter(pins)
|
||||
print()
|
||||
for row in range(4):
|
||||
print(' ' * row, end='')
|
||||
print(" " * row, end="")
|
||||
for _ in range(4 - row):
|
||||
p = next(pins_iter)
|
||||
print('O ' if p else '+ ', end='')
|
||||
print("O " if p else "+ ", end="")
|
||||
print()
|
||||
|
||||
|
||||
def centreText(text, width):
|
||||
t = len(text)
|
||||
return (' ' * ((width - t) // 2)) + text
|
||||
return (" " * ((width - t) // 2)) + text
|
||||
|
||||
|
||||
def main():
|
||||
print(centreText('Bowl', 80))
|
||||
print(centreText('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY', 80))
|
||||
print(centreText("Bowl", 80))
|
||||
print(centreText("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY", 80))
|
||||
print()
|
||||
print('WELCOME TO THE ALLEY.')
|
||||
print('BRING YOUR FRIENDS.')
|
||||
print("WELCOME TO THE ALLEY.")
|
||||
print("BRING YOUR FRIENDS.")
|
||||
print("OKAY LET'S FIRST GET ACQUAINTED.")
|
||||
|
||||
while True:
|
||||
print()
|
||||
if input('THE INSTRUCTIONS (Y/N)? ') in 'yY':
|
||||
print('THE GAME OF BOWLING TAKES MIND AND SKILL. DURING THE GAME')
|
||||
print('THE COMPUTER WILL KEEP SCORE. YOU MAY COMPETE WITH')
|
||||
print('OTHER PLAYERS[UP TO FOUR]. YOU WILL BE PLAYING TEN FRAMES.')
|
||||
if input("THE INSTRUCTIONS (Y/N)? ") in "yY":
|
||||
print("THE GAME OF BOWLING TAKES MIND AND SKILL. DURING THE GAME")
|
||||
print("THE COMPUTER WILL KEEP SCORE. YOU MAY COMPETE WITH")
|
||||
print("OTHER PLAYERS[UP TO FOUR]. YOU WILL BE PLAYING TEN FRAMES.")
|
||||
print("ON THE PIN DIAGRAM 'O' MEANS THE PIN IS DOWN...'+' MEANS THE")
|
||||
print('PIN IS STANDING. AFTER THE GAME THE COMPUTER WILL SHOW YOUR')
|
||||
print('SCORES.')
|
||||
print("PIN IS STANDING. AFTER THE GAME THE COMPUTER WILL SHOW YOUR")
|
||||
print("SCORES.")
|
||||
|
||||
total_players = int(input('FIRST OF ALL...HOW MANY ARE PLAYING? '))
|
||||
total_players = int(input("FIRST OF ALL...HOW MANY ARE PLAYING? "))
|
||||
player_names = []
|
||||
print()
|
||||
print('VERY GOOD...')
|
||||
print("VERY GOOD...")
|
||||
for index in range(total_players):
|
||||
player_names.append(Player(input(f'Enter name for player {index + 1}: ')))
|
||||
player_names.append(Player(input(f"Enter name for player {index + 1}: ")))
|
||||
|
||||
for frame in range(10):
|
||||
for player in player_names:
|
||||
@@ -124,11 +124,11 @@ def main():
|
||||
for player in player_names:
|
||||
print(player)
|
||||
|
||||
if input('DO YOU WANT ANOTHER GAME? ') not in 'yY':
|
||||
if input("DO YOU WANT ANOTHER GAME? ") not in "yY":
|
||||
break
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
import random
|
||||
|
||||
QUESTION_PROMPT = '? '
|
||||
QUESTION_PROMPT = "? "
|
||||
|
||||
|
||||
def play():
|
||||
print('BOXING')
|
||||
print('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY')
|
||||
print('\n\n')
|
||||
print('BOXING OLYMPIC STYLE (3 ROUNDS -- 2 OUT OF 3 WINS)')
|
||||
print("BOXING")
|
||||
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
print("\n\n")
|
||||
print("BOXING OLYMPIC STYLE (3 ROUNDS -- 2 OUT OF 3 WINS)")
|
||||
|
||||
opponent_score = 0
|
||||
player_score = 0
|
||||
@@ -18,16 +19,16 @@ def play():
|
||||
opponent_knockedout = False
|
||||
player_knockedout = False
|
||||
|
||||
print('WHAT IS YOUR OPPONENT\'S NAME', end=QUESTION_PROMPT)
|
||||
print("WHAT IS YOUR OPPONENT'S NAME", end=QUESTION_PROMPT)
|
||||
opponent_name = input()
|
||||
print('WHAT IS YOUR MAN\'S NAME', end=QUESTION_PROMPT)
|
||||
print("WHAT IS YOUR MAN'S NAME", end=QUESTION_PROMPT)
|
||||
player_name = input()
|
||||
|
||||
print('DIFFERENT PUNCHES ARE 1 FULL SWING 2 HOOK 3 UPPERCUT 4 JAB')
|
||||
print('WHAT IS YOUR MAN\'S BEST', end=QUESTION_PROMPT)
|
||||
print("DIFFERENT PUNCHES ARE 1 FULL SWING 2 HOOK 3 UPPERCUT 4 JAB")
|
||||
print("WHAT IS YOUR MAN'S BEST", end=QUESTION_PROMPT)
|
||||
player_best = int(input())
|
||||
|
||||
print('WHAT IS HIS VULNERABILITY', end=QUESTION_PROMPT)
|
||||
print("WHAT IS HIS VULNERABILITY", end=QUESTION_PROMPT)
|
||||
player_weakness = int(input())
|
||||
|
||||
opponent_best = 0
|
||||
@@ -36,11 +37,14 @@ def play():
|
||||
opponent_best = random.randint(1, 4)
|
||||
opponent_weakness = random.randint(1, 4)
|
||||
|
||||
print('{}\'S ADVANTAGE is {} AND VULNERABILITY IS SECRET.'
|
||||
.format(opponent_name, opponent_weakness))
|
||||
print(
|
||||
"{}'S ADVANTAGE is {} AND VULNERABILITY IS SECRET.".format(
|
||||
opponent_name, opponent_weakness
|
||||
)
|
||||
)
|
||||
|
||||
for round in (1, 2, 3):
|
||||
print('ROUND {} BEGINS...\n'.format(round))
|
||||
print(f"ROUND {round} BEGINS...\n")
|
||||
if opponent_score >= 2 or player_score >= 2:
|
||||
break
|
||||
|
||||
@@ -53,96 +57,117 @@ def play():
|
||||
player_damage += 2
|
||||
|
||||
if punch == 1:
|
||||
print('{} TAKES A FULL SWING AND'.format(opponent_name), end = ' ')
|
||||
print(f"{opponent_name} TAKES A FULL SWING AND", end=" ")
|
||||
if player_weakness == 1 or random.randint(1, 60) < 30:
|
||||
print('POW!!!! HE HITS HIM RIGHT IN THE FACE!')
|
||||
print("POW!!!! HE HITS HIM RIGHT IN THE FACE!")
|
||||
if player_damage > 35:
|
||||
player_knockedout = True
|
||||
break
|
||||
player_damage += 15
|
||||
else:
|
||||
print('BUT IT\'S BLOCKED!')
|
||||
print("BUT IT'S BLOCKED!")
|
||||
elif punch == 2:
|
||||
print('{} GETS {} IN THE JAW (OUCH!)'.format(opponent_name, player_name), end = ' ')
|
||||
print(
|
||||
"{} GETS {} IN THE JAW (OUCH!)".format(
|
||||
opponent_name, player_name
|
||||
),
|
||||
end=" ",
|
||||
)
|
||||
player_damage += 7
|
||||
print('....AND AGAIN')
|
||||
print("....AND AGAIN")
|
||||
if player_damage > 35:
|
||||
player_knockedout = True
|
||||
break
|
||||
player_damage += 5
|
||||
elif punch == 3:
|
||||
print('{} IS ATTACKED BY AN UPPERCUT (OH,OH)'.format(player_name))
|
||||
print(f"{player_name} IS ATTACKED BY AN UPPERCUT (OH,OH)")
|
||||
if player_weakness == 3 or random.randint(1, 200) > 75:
|
||||
print('{} BLOCKS AND HITS {} WITH A HOOK'.format(player_name, opponent_name))
|
||||
print(
|
||||
"{} BLOCKS AND HITS {} WITH A HOOK".format(
|
||||
player_name, opponent_name
|
||||
)
|
||||
)
|
||||
opponent_damage += 5
|
||||
else:
|
||||
print('AND {} CONNECTS...'.format(opponent_name))
|
||||
print(f"AND {opponent_name} CONNECTS...")
|
||||
player_damage += 8
|
||||
else:
|
||||
print('{} JABS AND'.format(opponent_name), end = ' ')
|
||||
print(f"{opponent_name} JABS AND", end=" ")
|
||||
if player_weakness == 4 or random.randint(1, 7) > 4:
|
||||
print('BLOOD SPILLS !!!')
|
||||
print("BLOOD SPILLS !!!")
|
||||
player_damage += 3
|
||||
else:
|
||||
print('AND IT\'S BLOCKED (LUCKY BLOCK!)')
|
||||
print("AND IT'S BLOCKED (LUCKY BLOCK!)")
|
||||
else:
|
||||
print('{}\'S PUNCH'.format(player_name), end='? ')
|
||||
print(f"{player_name}'S PUNCH", end="? ")
|
||||
punch = int(input())
|
||||
|
||||
if punch == opponent_weakness:
|
||||
opponent_damage += 2
|
||||
|
||||
if punch == 1:
|
||||
print('{} SWINGS AND'.format(player_name), end = ' ')
|
||||
print(f"{player_name} SWINGS AND", end=" ")
|
||||
if opponent_weakness == 1 or random.randint(1, 30) < 10:
|
||||
print('HE CONNECTS!')
|
||||
print("HE CONNECTS!")
|
||||
if opponent_damage > 35:
|
||||
opponent_knockedout = True
|
||||
break
|
||||
opponent_damage += 15
|
||||
else:
|
||||
print('HE MISSES')
|
||||
print("HE MISSES")
|
||||
elif punch == 2:
|
||||
print('{} GIVES THE HOOK...'.format(player_name), end = ' ')
|
||||
print(f"{player_name} GIVES THE HOOK...", end=" ")
|
||||
if opponent_weakness == 2 or random.randint(1, 2) == 1:
|
||||
print('CONNECTS...')
|
||||
print("CONNECTS...")
|
||||
opponent_damage += 7
|
||||
else:
|
||||
print('BUT IT\'S BLOCKED!!!!!!!!!!!!!')
|
||||
print("BUT IT'S BLOCKED!!!!!!!!!!!!!")
|
||||
elif punch == 3:
|
||||
print('{} TRIES AN UPPERCUT'.format(player_name), end = ' ')
|
||||
print(f"{player_name} TRIES AN UPPERCUT", end=" ")
|
||||
if opponent_weakness == 3 or random.randint(1, 100) < 51:
|
||||
print('AND HE CONNECTS!')
|
||||
print("AND HE CONNECTS!")
|
||||
opponent_damage += 4
|
||||
else:
|
||||
print('AND IT\'S BLOCKED (LUCKY BLOCK!)')
|
||||
print("AND IT'S BLOCKED (LUCKY BLOCK!)")
|
||||
else:
|
||||
print('{} JABS AT {}\'S HEAD'.format(player_name, opponent_name), end = ' ')
|
||||
print(
|
||||
f"{player_name} JABS AT {opponent_name}'S HEAD",
|
||||
end=" ",
|
||||
)
|
||||
if opponent_weakness == 4 or random.randint(1, 8) < 4:
|
||||
print('AND HE CONNECTS!')
|
||||
print("AND HE CONNECTS!")
|
||||
opponent_damage += 3
|
||||
else:
|
||||
print('AND IT\'S BLOCKED (LUCKY BLOCK!)')
|
||||
print("AND IT'S BLOCKED (LUCKY BLOCK!)")
|
||||
|
||||
if player_knockedout or opponent_knockedout:
|
||||
break
|
||||
elif player_damage > opponent_damage:
|
||||
print('{} WINS ROUND {}'.format(opponent_name, round))
|
||||
print(f"{opponent_name} WINS ROUND {round}")
|
||||
opponent_score += 1
|
||||
else:
|
||||
print('{} WINS ROUND {}'.format(player_name, round))
|
||||
print(f"{player_name} WINS ROUND {round}")
|
||||
player_score += 1
|
||||
|
||||
if player_knockedout:
|
||||
print('{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP'.format(player_name, opponent_name))
|
||||
print(
|
||||
"{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP".format(
|
||||
player_name, opponent_name
|
||||
)
|
||||
)
|
||||
elif opponent_knockedout:
|
||||
print('{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP'.format(opponent_name, player_name))
|
||||
print(
|
||||
"{} IS KNOCKED COLD AND {} IS THE WINNER AND CHAMP".format(
|
||||
opponent_name, player_name
|
||||
)
|
||||
)
|
||||
elif opponent_score > player_score:
|
||||
print('{} WINS (NICE GOING), {}'.format(opponent_name, player_name))
|
||||
print(f"{opponent_name} WINS (NICE GOING), {player_name}")
|
||||
else:
|
||||
print('{} AMAZINGLY WINS'.format(player_name))
|
||||
print(f"{player_name} AMAZINGLY WINS")
|
||||
|
||||
print('\n\nAND NOW GOODBYE FROM THE OLYMPIC ARENA.')
|
||||
print("\n\nAND NOW GOODBYE FROM THE OLYMPIC ARENA.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
play()
|
||||
|
||||
@@ -15,4 +15,3 @@ public class PlayerBug extends Insect {
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -75,10 +75,10 @@ if Z != "NO":
|
||||
["3", "HEAD", "1"],
|
||||
["4", "FEELERS", "2"],
|
||||
["5", "TAIL", "1"],
|
||||
["6", "LEGS", "6"]
|
||||
["6", "LEGS", "6"],
|
||||
]
|
||||
for row in table:
|
||||
print("{:<16}{:<16}{:<20}".format(row[0], row[1], row[2]))
|
||||
print(f"{row[0]:<16}{row[1]:<16}{row[2]:<20}")
|
||||
print_n_newlines(2)
|
||||
|
||||
A = 0
|
||||
|
||||
@@ -7,11 +7,12 @@ Demonstrates function-based Model View Controller pattern
|
||||
Ported by Peter Sharp
|
||||
"""
|
||||
|
||||
from random import randint
|
||||
from collections import namedtuple
|
||||
from random import randint
|
||||
|
||||
PAGE_WIDTH = 64
|
||||
|
||||
|
||||
def main(states, data):
|
||||
"""
|
||||
Starts the game loop using given states and data
|
||||
@@ -25,13 +26,16 @@ def main(states, data):
|
||||
"""
|
||||
|
||||
while True:
|
||||
if 'exit' == data['state']: break
|
||||
view, control, model = states[data['state']]
|
||||
if "exit" == data["state"]:
|
||||
break
|
||||
view, control, model = states[data["state"]]
|
||||
cmd = view(data)
|
||||
action = control(cmd)
|
||||
data = model(data, action)
|
||||
|
||||
Bodypart = namedtuple('Bodypart', ['name', 'count', 'depends'])
|
||||
|
||||
Bodypart = namedtuple("Bodypart", ["name", "count", "depends"])
|
||||
|
||||
|
||||
def print_start(_):
|
||||
"""
|
||||
@@ -47,16 +51,18 @@ def print_start(_):
|
||||
print()
|
||||
return input("DO YOU WANT INSTRUCTIONS? ")
|
||||
|
||||
|
||||
def control_start(cmd):
|
||||
"""
|
||||
Controls the start state
|
||||
"""
|
||||
if cmd.lower() in ('y', 'yes'):
|
||||
action = 'instructions'
|
||||
if cmd.lower() in ("y", "yes"):
|
||||
action = "instructions"
|
||||
else:
|
||||
action = 'game'
|
||||
action = "game"
|
||||
return action
|
||||
|
||||
|
||||
def print_instructions(data):
|
||||
"""
|
||||
Prints game instructions
|
||||
@@ -71,25 +77,33 @@ def print_instructions(data):
|
||||
print("OPTION OF SEEING THE PICTURES OF THE BUGS.")
|
||||
print("THE NUMBERS STAND FOR PARTS AS FOLLOWS:")
|
||||
|
||||
print_table([
|
||||
print_table(
|
||||
[
|
||||
("NUMBER", "PART", "NUMBER OF PART NEEDED"),
|
||||
*[(i + 1, part.name, part.count) for i, part in enumerate(data['partTypes'])]
|
||||
])
|
||||
*[
|
||||
(i + 1, part.name, part.count)
|
||||
for i, part in enumerate(data["partTypes"])
|
||||
],
|
||||
]
|
||||
)
|
||||
print()
|
||||
print()
|
||||
return ''
|
||||
return ""
|
||||
|
||||
|
||||
def goto_game(_):
|
||||
"""
|
||||
Returns game
|
||||
"""
|
||||
return 'game'
|
||||
return "game"
|
||||
|
||||
|
||||
def update_state(data, action):
|
||||
"""
|
||||
sets game state to given player value
|
||||
"""
|
||||
return {**data, 'state': action}
|
||||
return {**data, "state": action}
|
||||
|
||||
|
||||
def update_game(data, action):
|
||||
"""
|
||||
@@ -98,164 +112,180 @@ def update_game(data, action):
|
||||
# stores logs of what happened during a particular round
|
||||
logs = []
|
||||
|
||||
if 'pictures' == action:
|
||||
data['state'] = 'pictures'
|
||||
if "pictures" == action:
|
||||
data["state"] = "pictures"
|
||||
else:
|
||||
partAdded = False
|
||||
while partAdded == False:
|
||||
for player, parts in data['players'].items():
|
||||
for player, parts in data["players"].items():
|
||||
# rolls the dice for a part
|
||||
newPartIdx = randint(1, 6) - 1
|
||||
|
||||
# gets information about the picked part
|
||||
partType = data['partTypes'][newPartIdx]
|
||||
partType = data["partTypes"][newPartIdx]
|
||||
|
||||
# gets the number of existing parts of that type the player has
|
||||
partCount = parts[newPartIdx]
|
||||
|
||||
logs.append(('rolled', newPartIdx, player))
|
||||
logs.append(("rolled", newPartIdx, player))
|
||||
|
||||
# a new part can only be added if the player has the parts
|
||||
# the new part depends on and doesn't have enough of the part already
|
||||
overMaxParts = partType.count < partCount + 1
|
||||
missingPartDep = partType.depends != None and parts[partType.depends] == 0
|
||||
missingPartDep = (
|
||||
partType.depends != None and parts[partType.depends] == 0
|
||||
)
|
||||
|
||||
if not overMaxParts and not missingPartDep:
|
||||
# adds a new part
|
||||
partCount += 1
|
||||
logs.append(('added', newPartIdx, player))
|
||||
logs.append(("added", newPartIdx, player))
|
||||
partAdded = True
|
||||
elif missingPartDep:
|
||||
logs.append(('missingDep', newPartIdx, player, partType.depends))
|
||||
logs.append(("missingDep", newPartIdx, player, partType.depends))
|
||||
if overMaxParts:
|
||||
logs.append(('overMax', newPartIdx, player, partCount))
|
||||
logs.append(("overMax", newPartIdx, player, partCount))
|
||||
|
||||
data['players'][player][newPartIdx] = partCount
|
||||
data['logs'] = logs
|
||||
data["players"][player][newPartIdx] = partCount
|
||||
data["logs"] = logs
|
||||
|
||||
# checks if any players have finished their bug
|
||||
finished = get_finished(data)
|
||||
if len(finished) > 0:
|
||||
# and sets the state to 'won' if that's the case
|
||||
data['finished'] = finished
|
||||
data['state'] = 'won'
|
||||
data["finished"] = finished
|
||||
data["state"] = "won"
|
||||
return data
|
||||
|
||||
|
||||
def get_finished(data):
|
||||
"""
|
||||
Gets players who have finished their bugs
|
||||
"""
|
||||
totalParts = sum([partType.count for partType in data['partTypes']])
|
||||
totalParts = sum(partType.count for partType in data["partTypes"])
|
||||
finished = []
|
||||
for player, parts in data['players'].items():
|
||||
if(sum(parts) == totalParts): finished.append(player)
|
||||
for player, parts in data["players"].items():
|
||||
if sum(parts) == totalParts:
|
||||
finished.append(player)
|
||||
return finished
|
||||
|
||||
|
||||
def print_game(data):
|
||||
"""
|
||||
Displays the results of the game turn
|
||||
"""
|
||||
for log in data['logs']:
|
||||
for log in data["logs"]:
|
||||
code, partIdx, player, *logdata = log
|
||||
partType = data['partTypes'][partIdx]
|
||||
partType = data["partTypes"][partIdx]
|
||||
|
||||
if('rolled' == code):
|
||||
if "rolled" == code:
|
||||
print()
|
||||
print(f"{player} ROLLED A {partIdx + 1}")
|
||||
print(f"{partIdx + 1}={partType.name}")
|
||||
|
||||
elif('added' == code):
|
||||
if 'YOU' == player:
|
||||
if partType.name in ['FEELERS', 'LEGS', 'TAIL']:
|
||||
elif "added" == code:
|
||||
if "YOU" == player:
|
||||
if partType.name in ["FEELERS", "LEGS", "TAIL"]:
|
||||
print(f"I NOW GIVE YOU A {partType.name.replace('s', '')}.")
|
||||
else:
|
||||
print(f"YOU NOW HAVE A {partType.name}.")
|
||||
elif 'I' == player:
|
||||
if partType.name in ['BODY', 'NECK', 'TAIL']:
|
||||
elif "I" == player:
|
||||
if partType.name in ["BODY", "NECK", "TAIL"]:
|
||||
print(f"I NOW HAVE A {partType.name}.")
|
||||
elif partType.name == 'FEELERS':
|
||||
elif partType.name == "FEELERS":
|
||||
print("I GET A FEELER.")
|
||||
|
||||
if partType.count > 2:
|
||||
print(f"{player} NOW HAVE {data['players'][player][partIdx]} {partType.name}")
|
||||
print(
|
||||
f"{player} NOW HAVE {data['players'][player][partIdx]} {partType.name}"
|
||||
)
|
||||
|
||||
elif 'missingDep' == code:
|
||||
depIdx, = logdata
|
||||
dep = data['partTypes'][depIdx]
|
||||
print(f"YOU DO NOT HAVE A {dep.name}" if 'YOU' == player else f"I NEEDED A {dep.name}")
|
||||
elif "missingDep" == code:
|
||||
(depIdx,) = logdata
|
||||
dep = data["partTypes"][depIdx]
|
||||
print(
|
||||
f"YOU DO NOT HAVE A {dep.name}"
|
||||
if "YOU" == player
|
||||
else f"I NEEDED A {dep.name}"
|
||||
)
|
||||
|
||||
elif 'overMax' == code:
|
||||
partCount, = logdata
|
||||
if(partCount > 1):
|
||||
num = 'TWO' if 2 == partCount else partCount
|
||||
elif "overMax" == code:
|
||||
(partCount,) = logdata
|
||||
if partCount > 1:
|
||||
num = "TWO" if 2 == partCount else partCount
|
||||
maxMsg = f"HAVE {num} {partType.name}S ALREADY"
|
||||
else:
|
||||
maxMsg = f"ALREADY HAVE A {partType.name}"
|
||||
print(f"{player} {maxMsg}")
|
||||
|
||||
return input("DO YOU WANT THE PICTURES? ") if len(data['logs']) else 'n'
|
||||
return input("DO YOU WANT THE PICTURES? ") if len(data["logs"]) else "n"
|
||||
|
||||
|
||||
def print_pictures(data):
|
||||
"""
|
||||
Displays what the bugs look like for each player
|
||||
"""
|
||||
typeIxs = { partType.name: idx for idx, partType in enumerate(data['partTypes']) }
|
||||
typeIxs = {partType.name: idx for idx, partType in enumerate(data["partTypes"])}
|
||||
PIC_WIDTH = 22
|
||||
for player, parts in data['players'].items():
|
||||
for player, parts in data["players"].items():
|
||||
print(f"*****{'YOUR' if 'YOU' == player else 'MY'} BUG*****")
|
||||
print()
|
||||
print()
|
||||
if(parts[typeIxs['BODY']] > 0):
|
||||
if(parts[typeIxs['FEELERS']] > 0):
|
||||
F = ' '.join(['F'] * parts[typeIxs['FEELERS']])
|
||||
if parts[typeIxs["BODY"]] > 0:
|
||||
if parts[typeIxs["FEELERS"]] > 0:
|
||||
F = " ".join(["F"] * parts[typeIxs["FEELERS"]])
|
||||
for _ in range(4):
|
||||
print(' ' * 9 + F)
|
||||
if(parts[typeIxs['HEAD']] > 0):
|
||||
print(" " * 9 + F)
|
||||
if parts[typeIxs["HEAD"]] > 0:
|
||||
print_centered("HHHHHHH", PIC_WIDTH)
|
||||
print_centered("H H", PIC_WIDTH)
|
||||
print_centered("H O O H", PIC_WIDTH)
|
||||
print_centered("H H", PIC_WIDTH)
|
||||
print_centered("H V H", PIC_WIDTH)
|
||||
print_centered("HHHHHHH", PIC_WIDTH)
|
||||
if(parts[typeIxs['NECK']] > 0):
|
||||
if parts[typeIxs["NECK"]] > 0:
|
||||
for _ in range(2):
|
||||
print_centered("N N", PIC_WIDTH)
|
||||
print_centered("BBBBBBBBBBBB", PIC_WIDTH)
|
||||
for _ in range(2):
|
||||
print_centered("B B", PIC_WIDTH)
|
||||
|
||||
if(parts[typeIxs['TAIL']] > 0):
|
||||
if parts[typeIxs["TAIL"]] > 0:
|
||||
print("TTTTTB B")
|
||||
print_centered("BBBBBBBBBBBB", PIC_WIDTH)
|
||||
if(parts[typeIxs['LEGS']] > 0):
|
||||
L = 'L' * parts[typeIxs['LEGS']]
|
||||
if parts[typeIxs["LEGS"]] > 0:
|
||||
L = "L" * parts[typeIxs["LEGS"]]
|
||||
for _ in range(2):
|
||||
print(' '*5+L)
|
||||
print(" " * 5 + L)
|
||||
print()
|
||||
|
||||
|
||||
def control_game(cmd):
|
||||
"""
|
||||
returns state based on command
|
||||
"""
|
||||
if cmd.lower() in ('y', 'yes'):
|
||||
action = 'pictures'
|
||||
if cmd.lower() in ("y", "yes"):
|
||||
action = "pictures"
|
||||
else:
|
||||
action = 'game'
|
||||
action = "game"
|
||||
return action
|
||||
|
||||
|
||||
def print_winner(data):
|
||||
"""
|
||||
Displays the winning message
|
||||
"""
|
||||
for player in data['finished']:
|
||||
for player in data["finished"]:
|
||||
print(f"{'YOUR' if 'YOU' == player else 'MY'} BUG IS FINISHED.")
|
||||
print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!")
|
||||
|
||||
|
||||
def exit_game(_):
|
||||
"""
|
||||
Exists the game regardless of input
|
||||
"""
|
||||
return 'exit'
|
||||
return "exit"
|
||||
|
||||
|
||||
def print_centered(msg, width=PAGE_WIDTH):
|
||||
"""
|
||||
@@ -264,28 +294,26 @@ def print_centered(msg, width=PAGE_WIDTH):
|
||||
spaces = " " * ((width - len(msg)) // 2)
|
||||
print(spaces + msg)
|
||||
|
||||
|
||||
def print_table(rows):
|
||||
for row in rows:
|
||||
print(*row, sep="\t")
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# The main states in the game
|
||||
states = {
|
||||
# Initial state of the game
|
||||
'start': (print_start, control_start, update_state),
|
||||
|
||||
"start": (print_start, control_start, update_state),
|
||||
# displays game instructions
|
||||
'instructions': (print_instructions, goto_game, update_state),
|
||||
|
||||
"instructions": (print_instructions, goto_game, update_state),
|
||||
# the main game state
|
||||
'game': (print_game, control_game, update_game),
|
||||
|
||||
"game": (print_game, control_game, update_game),
|
||||
# displays pictures before returning to game
|
||||
'pictures': (print_pictures, goto_game, update_state),
|
||||
|
||||
"pictures": (print_pictures, goto_game, update_state),
|
||||
# Displays the winning players and message
|
||||
'won': (print_winner, exit_game, update_state)
|
||||
"won": (print_winner, exit_game, update_state),
|
||||
}
|
||||
|
||||
# body part types used by the game to work out whether a player's body part can be added
|
||||
@@ -295,19 +323,16 @@ if __name__ == '__main__':
|
||||
Bodypart(name="HEAD", count=1, depends=1),
|
||||
Bodypart(name="FEELERS", count=2, depends=2),
|
||||
Bodypart(name="TAIL", count=1, depends=0),
|
||||
Bodypart(name="LEGS", count=6 , depends=0)
|
||||
Bodypart(name="LEGS", count=6, depends=0),
|
||||
)
|
||||
|
||||
# all the data used by the game
|
||||
data = {
|
||||
'state': 'start',
|
||||
'partNo': None,
|
||||
'players': {
|
||||
'YOU': [0] * len(partTypes),
|
||||
'I': [0] * len(partTypes)
|
||||
},
|
||||
'partTypes': partTypes,
|
||||
'finished': [],
|
||||
'logs': []
|
||||
"state": "start",
|
||||
"partNo": None,
|
||||
"players": {"YOU": [0] * len(partTypes), "I": [0] * len(partTypes)},
|
||||
"partTypes": partTypes,
|
||||
"finished": [],
|
||||
"logs": [],
|
||||
}
|
||||
main(states, data)
|
||||
@@ -13,13 +13,13 @@ def print_n_newlines(n: int):
|
||||
|
||||
def subroutine_1610():
|
||||
B = 3 / A * random.random()
|
||||
if (B < 0.37):
|
||||
if B < 0.37:
|
||||
C = 0.5
|
||||
elif (B < 0.5):
|
||||
elif B < 0.5:
|
||||
C = 0.4
|
||||
elif (B < 0.63):
|
||||
elif B < 0.63:
|
||||
C = 0.3
|
||||
elif (B < 0.87):
|
||||
elif B < 0.87:
|
||||
C = 0.2
|
||||
else:
|
||||
C = 0.1
|
||||
@@ -44,8 +44,9 @@ def subroutine_1610():
|
||||
|
||||
|
||||
def FNC():
|
||||
Q = (4.5+L/6-(D[1]+D[2])*2.5+4*D[4]+2 *
|
||||
D[5]-(D[3] ** 2)/120-A)*random.random()
|
||||
Q = (
|
||||
4.5 + L / 6 - (D[1] + D[2]) * 2.5 + 4 * D[4] + 2 * D[5] - (D[3] ** 2) / 120 - A
|
||||
) * random.random()
|
||||
return Q
|
||||
|
||||
|
||||
|
||||
@@ -55,5 +55,3 @@ do {
|
||||
print "\n"; print "WE HAVE A WINNER!!\n\n";
|
||||
for (my $I=1; $I<=$M; $I++) { print $A[$W[$I]]." SCORED ".$S[$W[$I]]." POINTS.\n"; }
|
||||
print "\n"; print "THANKS FOR THE GAME.\n"; exit;
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ def print_n_newlines(n: int):
|
||||
for _ in range(n):
|
||||
print()
|
||||
|
||||
|
||||
print_n_whitespaces(32)
|
||||
print("BULLSEYE")
|
||||
print_n_whitespaces(15)
|
||||
@@ -18,10 +19,26 @@ print("IN THIS GAME, UP TO 20 PLAYERS THROW DARTS AT A TARGET")
|
||||
print("WITH 10, 20, 30, AND 40 POINT ZONES. THE OBJECTIVE IS")
|
||||
print("TO GET 200 POINTS.")
|
||||
print()
|
||||
print("THROW",end="");print_n_whitespaces(20);print("DESCRIPTION", end="");print_n_whitespaces(45);print("PROBABLE SCORE")
|
||||
print(" 1",end="");print_n_whitespaces(20);print("FAST OVERARM",end="");print_n_whitespaces(45);print("BULLSEYE OR COMPLETE MISS")
|
||||
print(" 2",end="");print_n_whitespaces(20);print("CONTROLLED OVERARM",end="");print_n_whitespaces(45);print("10, 20 OR 30 POINTS")
|
||||
print(" 3",end="");print_n_whitespaces(20);print("UNDERARM",end="");print_n_whitespaces(45);print("ANYTHING")
|
||||
print("THROW", end="")
|
||||
print_n_whitespaces(20)
|
||||
print("DESCRIPTION", end="")
|
||||
print_n_whitespaces(45)
|
||||
print("PROBABLE SCORE")
|
||||
print(" 1", end="")
|
||||
print_n_whitespaces(20)
|
||||
print("FAST OVERARM", end="")
|
||||
print_n_whitespaces(45)
|
||||
print("BULLSEYE OR COMPLETE MISS")
|
||||
print(" 2", end="")
|
||||
print_n_whitespaces(20)
|
||||
print("CONTROLLED OVERARM", end="")
|
||||
print_n_whitespaces(45)
|
||||
print("10, 20 OR 30 POINTS")
|
||||
print(" 3", end="")
|
||||
print_n_whitespaces(20)
|
||||
print("UNDERARM", end="")
|
||||
print_n_whitespaces(45)
|
||||
print("ANYTHING")
|
||||
print()
|
||||
|
||||
M = 0
|
||||
@@ -54,20 +71,20 @@ while M == 0:
|
||||
else:
|
||||
break
|
||||
if T == 1:
|
||||
P1=.65
|
||||
P2=.55
|
||||
P3=.5
|
||||
P4=.5
|
||||
P1 = 0.65
|
||||
P2 = 0.55
|
||||
P3 = 0.5
|
||||
P4 = 0.5
|
||||
elif T == 2:
|
||||
P1=.99
|
||||
P2=.77
|
||||
P3=.43
|
||||
P4=.01
|
||||
P1 = 0.99
|
||||
P2 = 0.77
|
||||
P3 = 0.43
|
||||
P4 = 0.01
|
||||
elif T == 3:
|
||||
P1=.95
|
||||
P2=.75
|
||||
P3=.45
|
||||
P4=.05
|
||||
P1 = 0.95
|
||||
P2 = 0.75
|
||||
P3 = 0.45
|
||||
P4 = 0.05
|
||||
U = random.random()
|
||||
if U >= P1:
|
||||
print("BULLSEYE!! 40 POINTS!")
|
||||
|
||||
@@ -2,21 +2,241 @@
|
||||
|
||||
|
||||
# This data is meant to be read-only, so we are storing it in a tuple
|
||||
DATA = (2,21,14,14,25,
|
||||
1,2,-1,0,2,45,50,-1,0,5,43,52,-1,0,7,41,52,-1,
|
||||
1,9,37,50,-1,2,11,36,50,-1,3,13,34,49,-1,4,14,32,48,-1,
|
||||
5,15,31,47,-1,6,16,30,45,-1,7,17,29,44,-1,8,19,28,43,-1,
|
||||
9,20,27,41,-1,10,21,26,40,-1,11,22,25,38,-1,12,22,24,36,-1,
|
||||
13,34,-1,14,33,-1,15,31,-1,17,29,-1,18,27,-1,
|
||||
19,26,-1,16,28,-1,13,30,-1,11,31,-1,10,32,-1,
|
||||
8,33,-1,7,34,-1,6,13,16,34,-1,5,12,16,35,-1,
|
||||
4,12,16,35,-1,3,12,15,35,-1,2,35,-1,1,35,-1,
|
||||
2,34,-1,3,34,-1,4,33,-1,6,33,-1,10,32,34,34,-1,
|
||||
14,17,19,25,28,31,35,35,-1,15,19,23,30,36,36,-1,
|
||||
14,18,21,21,24,30,37,37,-1,13,18,23,29,33,38,-1,
|
||||
12,29,31,33,-1,11,13,17,17,19,19,22,22,24,31,-1,
|
||||
10,11,17,18,22,22,24,24,29,29,-1,
|
||||
22,23,26,29,-1,27,29,-1,28,29,-1,4096)
|
||||
DATA = (
|
||||
2,
|
||||
21,
|
||||
14,
|
||||
14,
|
||||
25,
|
||||
1,
|
||||
2,
|
||||
-1,
|
||||
0,
|
||||
2,
|
||||
45,
|
||||
50,
|
||||
-1,
|
||||
0,
|
||||
5,
|
||||
43,
|
||||
52,
|
||||
-1,
|
||||
0,
|
||||
7,
|
||||
41,
|
||||
52,
|
||||
-1,
|
||||
1,
|
||||
9,
|
||||
37,
|
||||
50,
|
||||
-1,
|
||||
2,
|
||||
11,
|
||||
36,
|
||||
50,
|
||||
-1,
|
||||
3,
|
||||
13,
|
||||
34,
|
||||
49,
|
||||
-1,
|
||||
4,
|
||||
14,
|
||||
32,
|
||||
48,
|
||||
-1,
|
||||
5,
|
||||
15,
|
||||
31,
|
||||
47,
|
||||
-1,
|
||||
6,
|
||||
16,
|
||||
30,
|
||||
45,
|
||||
-1,
|
||||
7,
|
||||
17,
|
||||
29,
|
||||
44,
|
||||
-1,
|
||||
8,
|
||||
19,
|
||||
28,
|
||||
43,
|
||||
-1,
|
||||
9,
|
||||
20,
|
||||
27,
|
||||
41,
|
||||
-1,
|
||||
10,
|
||||
21,
|
||||
26,
|
||||
40,
|
||||
-1,
|
||||
11,
|
||||
22,
|
||||
25,
|
||||
38,
|
||||
-1,
|
||||
12,
|
||||
22,
|
||||
24,
|
||||
36,
|
||||
-1,
|
||||
13,
|
||||
34,
|
||||
-1,
|
||||
14,
|
||||
33,
|
||||
-1,
|
||||
15,
|
||||
31,
|
||||
-1,
|
||||
17,
|
||||
29,
|
||||
-1,
|
||||
18,
|
||||
27,
|
||||
-1,
|
||||
19,
|
||||
26,
|
||||
-1,
|
||||
16,
|
||||
28,
|
||||
-1,
|
||||
13,
|
||||
30,
|
||||
-1,
|
||||
11,
|
||||
31,
|
||||
-1,
|
||||
10,
|
||||
32,
|
||||
-1,
|
||||
8,
|
||||
33,
|
||||
-1,
|
||||
7,
|
||||
34,
|
||||
-1,
|
||||
6,
|
||||
13,
|
||||
16,
|
||||
34,
|
||||
-1,
|
||||
5,
|
||||
12,
|
||||
16,
|
||||
35,
|
||||
-1,
|
||||
4,
|
||||
12,
|
||||
16,
|
||||
35,
|
||||
-1,
|
||||
3,
|
||||
12,
|
||||
15,
|
||||
35,
|
||||
-1,
|
||||
2,
|
||||
35,
|
||||
-1,
|
||||
1,
|
||||
35,
|
||||
-1,
|
||||
2,
|
||||
34,
|
||||
-1,
|
||||
3,
|
||||
34,
|
||||
-1,
|
||||
4,
|
||||
33,
|
||||
-1,
|
||||
6,
|
||||
33,
|
||||
-1,
|
||||
10,
|
||||
32,
|
||||
34,
|
||||
34,
|
||||
-1,
|
||||
14,
|
||||
17,
|
||||
19,
|
||||
25,
|
||||
28,
|
||||
31,
|
||||
35,
|
||||
35,
|
||||
-1,
|
||||
15,
|
||||
19,
|
||||
23,
|
||||
30,
|
||||
36,
|
||||
36,
|
||||
-1,
|
||||
14,
|
||||
18,
|
||||
21,
|
||||
21,
|
||||
24,
|
||||
30,
|
||||
37,
|
||||
37,
|
||||
-1,
|
||||
13,
|
||||
18,
|
||||
23,
|
||||
29,
|
||||
33,
|
||||
38,
|
||||
-1,
|
||||
12,
|
||||
29,
|
||||
31,
|
||||
33,
|
||||
-1,
|
||||
11,
|
||||
13,
|
||||
17,
|
||||
17,
|
||||
19,
|
||||
19,
|
||||
22,
|
||||
22,
|
||||
24,
|
||||
31,
|
||||
-1,
|
||||
10,
|
||||
11,
|
||||
17,
|
||||
18,
|
||||
22,
|
||||
22,
|
||||
24,
|
||||
24,
|
||||
29,
|
||||
29,
|
||||
-1,
|
||||
22,
|
||||
23,
|
||||
26,
|
||||
29,
|
||||
-1,
|
||||
27,
|
||||
29,
|
||||
-1,
|
||||
28,
|
||||
29,
|
||||
-1,
|
||||
4096,
|
||||
)
|
||||
|
||||
|
||||
def display_intro():
|
||||
@@ -28,7 +248,7 @@ def display_intro():
|
||||
def tab(column):
|
||||
"""Emulates the TAB command in BASIC. Returns a string with ASCII
|
||||
codes for setting the cursor to the specified column."""
|
||||
return "\r\33[{}C".format(column)
|
||||
return f"\r\33[{column}C"
|
||||
|
||||
|
||||
def play():
|
||||
|
||||
@@ -8,4 +8,3 @@ There are two versions of this program here:
|
||||
BASIC program.
|
||||
* `bunny-modern.rb` takes more advantage of the features of modern
|
||||
tools and languages.
|
||||
|
||||
|
||||
@@ -35,5 +35,3 @@ do {
|
||||
|
||||
print "COME BACK WHEN YOU NEED HELP WITH ANOTHER REPORT!\n";
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -22,21 +22,53 @@
|
||||
|
||||
import random
|
||||
|
||||
|
||||
WORDS = [ ["Ability", "Basal", "Behavioral", "Child-centered",
|
||||
"Differentiated", "Discovery", "Flexible", "Heterogeneous",
|
||||
"Homogenous", "Manipulative", "Modular", "Tavistock",
|
||||
"Individualized"],
|
||||
|
||||
["learning", "evaluative", "objective", "cognitive",
|
||||
"enrichment", "scheduling", "humanistic", "integrated",
|
||||
"non-graded", "training", "vertical age", "motivational",
|
||||
"creative"] ,
|
||||
|
||||
["grouping", "modification", "accountability", "process",
|
||||
"core curriculum", "algorithm", "performance",
|
||||
"reinforcement", "open classroom", "resource", "structure",
|
||||
"facility","environment"] ]
|
||||
WORDS = [
|
||||
[
|
||||
"Ability",
|
||||
"Basal",
|
||||
"Behavioral",
|
||||
"Child-centered",
|
||||
"Differentiated",
|
||||
"Discovery",
|
||||
"Flexible",
|
||||
"Heterogeneous",
|
||||
"Homogenous",
|
||||
"Manipulative",
|
||||
"Modular",
|
||||
"Tavistock",
|
||||
"Individualized",
|
||||
],
|
||||
[
|
||||
"learning",
|
||||
"evaluative",
|
||||
"objective",
|
||||
"cognitive",
|
||||
"enrichment",
|
||||
"scheduling",
|
||||
"humanistic",
|
||||
"integrated",
|
||||
"non-graded",
|
||||
"training",
|
||||
"vertical age",
|
||||
"motivational",
|
||||
"creative",
|
||||
],
|
||||
[
|
||||
"grouping",
|
||||
"modification",
|
||||
"accountability",
|
||||
"process",
|
||||
"core curriculum",
|
||||
"algorithm",
|
||||
"performance",
|
||||
"reinforcement",
|
||||
"open classroom",
|
||||
"resource",
|
||||
"structure",
|
||||
"facility",
|
||||
"environment",
|
||||
],
|
||||
]
|
||||
|
||||
|
||||
# Display intro text
|
||||
@@ -62,7 +94,7 @@ while still_running:
|
||||
|
||||
response = input("? ")
|
||||
try:
|
||||
if response.upper()[0] != 'Y':
|
||||
if response.upper()[0] != "Y":
|
||||
still_running = False
|
||||
except:
|
||||
still_running = False
|
||||
@@ -71,7 +103,6 @@ while still_running:
|
||||
print("Come back when you need help with another report!\n")
|
||||
|
||||
|
||||
|
||||
######################################################################
|
||||
#
|
||||
# Porting Notes
|
||||
@@ -104,10 +135,3 @@ print("Come back when you need help with another report!\n")
|
||||
# choose a field and pick the buzzwords accordingly.
|
||||
#
|
||||
######################################################################
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#
|
||||
########################################################
|
||||
|
||||
|
||||
def parse_input():
|
||||
"""
|
||||
function to parse input for weekday and leap year boolean
|
||||
@@ -32,7 +33,7 @@ def parse_input():
|
||||
"wednesday": -3,
|
||||
"thursday": -4,
|
||||
"friday": -5,
|
||||
"saturday": -6
|
||||
"saturday": -6,
|
||||
}
|
||||
|
||||
day = 0
|
||||
@@ -51,11 +52,11 @@ def parse_input():
|
||||
while True:
|
||||
leap = input("IS IT A LEAP YEAR?:")
|
||||
|
||||
if 'y' in leap.lower():
|
||||
if "y" in leap.lower():
|
||||
leap_day = True
|
||||
break
|
||||
|
||||
if 'n' in leap.lower():
|
||||
if "n" in leap.lower():
|
||||
leap_day = False
|
||||
break
|
||||
|
||||
@@ -71,7 +72,7 @@ def calendar(weekday, leap_year):
|
||||
_leap_year_: bool - indicates if the year is a leap year
|
||||
"""
|
||||
months_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
||||
days = 'S M T W T F S\n'
|
||||
days = "S M T W T F S\n"
|
||||
sep = "*" * 59
|
||||
years_day = 365
|
||||
d = weekday
|
||||
@@ -80,7 +81,8 @@ def calendar(weekday, leap_year):
|
||||
months_days[2] = 29
|
||||
years_day = 366
|
||||
|
||||
months_names = [" JANUARY ",
|
||||
months_names = [
|
||||
" JANUARY ",
|
||||
" FEBRUARY",
|
||||
" MARCH ",
|
||||
" APRIL ",
|
||||
@@ -91,15 +93,19 @@ def calendar(weekday, leap_year):
|
||||
"SEPTEMBER",
|
||||
" OCTOBER ",
|
||||
" NOVEMBER",
|
||||
" DECEMBER"]
|
||||
" DECEMBER",
|
||||
]
|
||||
|
||||
days_count = 0 # S in the original program
|
||||
|
||||
# main loop
|
||||
for n in range(1, 13):
|
||||
days_count += months_days[n - 1]
|
||||
print("** {} ****************** {} ****************** {} **\n".format(days_count,
|
||||
months_names[n-1], years_day-days_count))
|
||||
print(
|
||||
"** {} ****************** {} ****************** {} **\n".format(
|
||||
days_count, months_names[n - 1], years_day - days_count
|
||||
)
|
||||
)
|
||||
print(days)
|
||||
print(sep)
|
||||
|
||||
@@ -113,11 +119,11 @@ def calendar(weekday, leap_year):
|
||||
break
|
||||
|
||||
if d2 <= 0:
|
||||
print("{}".format(' '), end=' ')
|
||||
print("{}".format(" "), end=" ")
|
||||
elif d2 < 10:
|
||||
print(" {}".format(d2), end=' ')
|
||||
print(f" {d2}", end=" ")
|
||||
else:
|
||||
print("{}".format(d2), end=' ')
|
||||
print(f"{d2}", end=" ")
|
||||
print()
|
||||
|
||||
if d2 >= months_days[n]:
|
||||
|
||||
@@ -49,7 +49,7 @@ def get_coordinates(prompt):
|
||||
continue
|
||||
|
||||
try:
|
||||
x, y = [int(c) for c in response.split(",")]
|
||||
x, y = (int(c) for c in response.split(","))
|
||||
except ValueError as ve:
|
||||
print(err_msg)
|
||||
continue
|
||||
|
||||
@@ -33,5 +33,3 @@ while ($T<9) {
|
||||
print "YOUR 9 LIVES ARE USED, BUT YOU WILL BE LONG REMEMBERED FOR\n";
|
||||
print "YOUR CONTRIBUTIONS TO THE FIELD OF COMIC BOOK CHEMISTRY.\n";
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -1,77 +1,89 @@
|
||||
def print_lightning_bolt():
|
||||
|
||||
print('*'*36)
|
||||
print("*" * 36)
|
||||
n = 24
|
||||
while n > 16:
|
||||
print(' '*n + 'x x')
|
||||
print(" " * n + "x x")
|
||||
n -= 1
|
||||
print(' '*16 + 'x xxx')
|
||||
print(' '*15 + 'x x')
|
||||
print(' '*14+ 'xxx x')
|
||||
print(" " * 16 + "x xxx")
|
||||
print(" " * 15 + "x x")
|
||||
print(" " * 14 + "xxx x")
|
||||
n -= 1
|
||||
while n > 8:
|
||||
print(' '*n + 'x x')
|
||||
print(" " * n + "x x")
|
||||
n -= 1
|
||||
print(' '*8 + 'xx')
|
||||
print(' '*7 +'x')
|
||||
print('*'*36)
|
||||
print(" " * 8 + "xx")
|
||||
print(" " * 7 + "x")
|
||||
print("*" * 36)
|
||||
|
||||
|
||||
def print_solution(n):
|
||||
|
||||
print('\n{} plus 3 gives {}. This Divided by 5 equals {}'.format(n, n+3, (n+3)/5))
|
||||
print('This times 8 gives {}. If we divide 5 and add 5.'.format(( (n+3)/5 )*8 ))
|
||||
print('We get {}, which, minus 1 equals {}'.format(( ((n+3)/5)*8)/5+5, ((((n+3)/5)*8)/5+5)-1 ))
|
||||
print(
|
||||
"\n{} plus 3 gives {}. This Divided by 5 equals {}".format(
|
||||
n, n + 3, (n + 3) / 5
|
||||
)
|
||||
)
|
||||
print(f"This times 8 gives {((n + 3) / 5) * 8}. If we divide 5 and add 5.")
|
||||
print(
|
||||
"We get {}, which, minus 1 equals {}".format(
|
||||
(((n + 3) / 5) * 8) / 5 + 5, ((((n + 3) / 5) * 8) / 5 + 5) - 1
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def Game():
|
||||
print('\nTake a Number and ADD 3. Now, Divide this number by 5 and')
|
||||
print('multiply by 8. Now, Divide by 5 and add the same. Subtract 1')
|
||||
print("\nTake a Number and ADD 3. Now, Divide this number by 5 and")
|
||||
print("multiply by 8. Now, Divide by 5 and add the same. Subtract 1")
|
||||
|
||||
resp = float(input('\nWhat do you have? '))
|
||||
resp = float(input("\nWhat do you have? "))
|
||||
comp_guess = (((resp - 4) * 5) / 8) * 5 - 3
|
||||
resp2 = input('\nI bet your number was {} was i right(Yes or No)? '.format(comp_guess))
|
||||
resp2 = input(f"\nI bet your number was {comp_guess} was i right(Yes or No)? ")
|
||||
|
||||
if resp2 == 'Yes' or resp2 == 'YES' or resp2 == 'yes':
|
||||
print('\nHuh, I Knew I was unbeatable')
|
||||
print('And here is how i did it')
|
||||
if resp2 == "Yes" or resp2 == "YES" or resp2 == "yes":
|
||||
print("\nHuh, I Knew I was unbeatable")
|
||||
print("And here is how i did it")
|
||||
print_solution(comp_guess)
|
||||
input('')
|
||||
input("")
|
||||
|
||||
else:
|
||||
resp3 = float(input('\nHUH!! what was you original number? '))
|
||||
resp3 = float(input("\nHUH!! what was you original number? "))
|
||||
|
||||
if resp3 == comp_guess:
|
||||
print('\nThat was my guess, AHA i was right')
|
||||
print("Shamed to accept defeat i guess, don't worry you can master mathematics too")
|
||||
print('Here is how i did it')
|
||||
print("\nThat was my guess, AHA i was right")
|
||||
print(
|
||||
"Shamed to accept defeat i guess, don't worry you can master mathematics too"
|
||||
)
|
||||
print("Here is how i did it")
|
||||
print_solution(comp_guess)
|
||||
input('')
|
||||
input("")
|
||||
|
||||
else:
|
||||
print('\nSo you think you\'re so smart, EH?')
|
||||
print('Now, Watch')
|
||||
print("\nSo you think you're so smart, EH?")
|
||||
print("Now, Watch")
|
||||
print_solution(resp3)
|
||||
|
||||
resp4 = input('\nNow do you believe me? ')
|
||||
resp4 = input("\nNow do you believe me? ")
|
||||
|
||||
if resp4 == 'Yes' or resp4 == 'YES' or resp4 == 'yes':
|
||||
print('\nOk, Lets play again sometime bye!!!!')
|
||||
input('')
|
||||
if resp4 == "Yes" or resp4 == "YES" or resp4 == "yes":
|
||||
print("\nOk, Lets play again sometime bye!!!!")
|
||||
input("")
|
||||
|
||||
else:
|
||||
print('\nYOU HAVE MADE ME VERY MAD!!!!!')
|
||||
print("\nYOU HAVE MADE ME VERY MAD!!!!!")
|
||||
print("BY THE WRATH OF THE MATHEMATICS AND THE RAGE OF THE GODS")
|
||||
print("THERE SHALL BE LIGHTNING!!!!!!!")
|
||||
print_lightning_bolt()
|
||||
print('\nI Hope you believe me now, for your own sake')
|
||||
input('')
|
||||
print("\nI Hope you believe me now, for your own sake")
|
||||
input("")
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
print('I am CHIEF NUMBERS FREEK, The GREAT INDIAN MATH GOD.')
|
||||
play = input('\nAre you ready to take the test you called me out for(Yes or No)? ')
|
||||
if play == 'Yes' or play == 'YES' or play == 'yes':
|
||||
if __name__ == "__main__":
|
||||
|
||||
print("I am CHIEF NUMBERS FREEK, The GREAT INDIAN MATH GOD.")
|
||||
play = input("\nAre you ready to take the test you called me out for(Yes or No)? ")
|
||||
if play == "Yes" or play == "YES" or play == "yes":
|
||||
Game()
|
||||
else:
|
||||
print('Ok, Nevermind. Let me go back to my great slumber, Bye')
|
||||
input('')
|
||||
print("Ok, Nevermind. Let me go back to my great slumber, Bye")
|
||||
input("")
|
||||
|
||||
@@ -83,8 +83,12 @@ def play_game():
|
||||
player_column = -1
|
||||
while player_row == -1 or player_column == -1:
|
||||
try:
|
||||
coordinates = [int(item) for item in input(
|
||||
"Coordinates of chomp (Row, Column) ").split(",")]
|
||||
coordinates = [
|
||||
int(item)
|
||||
for item in input("Coordinates of chomp (Row, Column) ").split(
|
||||
","
|
||||
)
|
||||
]
|
||||
player_row = coordinates[0]
|
||||
player_column = coordinates[1]
|
||||
|
||||
|
||||
@@ -6,65 +6,81 @@ def tab(n):
|
||||
return " " * n
|
||||
|
||||
|
||||
battles = [["JULY 21, 1861. GEN. BEAUREGARD, COMMANDING THE SOUTH, MET",
|
||||
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",
|
||||
"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."],
|
||||
|
||||
"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."]]
|
||||
[
|
||||
"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]]
|
||||
["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 = {}
|
||||
@@ -87,7 +103,7 @@ d = -1 # number of players in the game
|
||||
print()
|
||||
while True:
|
||||
X = input("DO YOU WANT INSTRUCTIONS? ")
|
||||
if (X == "YES" or X == "NO"):
|
||||
if X == "YES" or X == "NO":
|
||||
break
|
||||
print("YES OR NO -- ")
|
||||
|
||||
@@ -192,12 +208,14 @@ while True:
|
||||
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[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)
|
||||
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)))
|
||||
@@ -263,8 +281,7 @@ while True:
|
||||
else:
|
||||
print(" UNION ", end="")
|
||||
# Find morale
|
||||
o = ((2 * math.pow(fa[z], 2) +
|
||||
math.pow(ha[z], 2)) / math.pow(f1, 2) + 1)
|
||||
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:
|
||||
@@ -291,7 +308,7 @@ while True:
|
||||
if bs != "YES":
|
||||
while True:
|
||||
y = int(input("YOUR STRATEGY "))
|
||||
if (abs(y - 3) < 3):
|
||||
if abs(y - 3) < 3:
|
||||
break
|
||||
print(f"STRATEGY {y} NOT ALLOWED.")
|
||||
if y == 5:
|
||||
@@ -317,7 +334,7 @@ while True:
|
||||
print(y2)
|
||||
else:
|
||||
for i in range(1, 3):
|
||||
if (i == 1):
|
||||
if i == 1:
|
||||
print("CONFEDERATE STRATEGY ? ", end="")
|
||||
while True:
|
||||
y = int(input())
|
||||
@@ -325,10 +342,10 @@ while True:
|
||||
break
|
||||
print(f"STRATEGY {y} NOT ALLOWED.")
|
||||
print("YOUR STRATEGY ? ", end="")
|
||||
if (i == 2):
|
||||
if i == 2:
|
||||
y2 = y
|
||||
y = y1
|
||||
if (y2 != 5):
|
||||
if y2 != 5:
|
||||
break
|
||||
else:
|
||||
y1 = y
|
||||
@@ -356,36 +373,42 @@ while True:
|
||||
e = 7 * c5 / 13
|
||||
u = 1
|
||||
|
||||
if (d == 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"):
|
||||
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(
|
||||
"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)):
|
||||
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)):
|
||||
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):
|
||||
if a != 0:
|
||||
w += 1
|
||||
|
||||
# Lines 2530 to 2590 from original are unreachable.
|
||||
if (a != 0):
|
||||
if a != 0:
|
||||
t1 += c5 + e
|
||||
t2 += c6 + e2
|
||||
p1 += c1
|
||||
@@ -402,7 +425,7 @@ while True:
|
||||
s = 3
|
||||
s0 = 0
|
||||
for i in range(1, 5):
|
||||
if (sa[i] <= 5):
|
||||
if sa[i] <= 5:
|
||||
continue
|
||||
sa[i] -= 5
|
||||
s0 += s
|
||||
@@ -420,12 +443,12 @@ print()
|
||||
print()
|
||||
print()
|
||||
print(f"THE CONFEDERACY HAS WON {w} BATTLES AND LOST {l}")
|
||||
if (y == 5 or (y2 != 5 and w <= 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):
|
||||
if r1 > 0:
|
||||
print(f"FOR THE {w + l + w0} BATTLES FOUGHT (EXCLUDING RERUNS)")
|
||||
print(" \t \t ")
|
||||
print("CONFEDERACY\t UNION")
|
||||
@@ -433,8 +456,9 @@ if (r1 > 0):
|
||||
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"):
|
||||
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")
|
||||
|
||||
@@ -44,17 +44,21 @@ def attackFirst():
|
||||
while True:
|
||||
print("YOU ATTACK FIRST. TYPE (1) FOR ARMY; (2) FOR NAVY;")
|
||||
print("AND (3) FOR AIR FORCE.")
|
||||
print("?", end=' ')
|
||||
print("?", end=" ")
|
||||
unitType = int(input())
|
||||
if not (unitType < 1 or unitType > 3):
|
||||
break
|
||||
|
||||
while True:
|
||||
print("HOW MANY MEN")
|
||||
print("?", end=' ')
|
||||
print("?", end=" ")
|
||||
numUnits = int(input())
|
||||
if not ((numUnits < 0) or ((unitType == 1) and (numUnits > usrArmy)) or (
|
||||
(unitType == 2) and (numUnits > usrNavy)) or ((unitType == 3) and (numUnits > usrAir))):
|
||||
if not (
|
||||
(numUnits < 0)
|
||||
or ((unitType == 1) and (numUnits > usrArmy))
|
||||
or ((unitType == 2) and (numUnits > usrNavy))
|
||||
or ((unitType == 3) and (numUnits > usrAir))
|
||||
):
|
||||
break
|
||||
|
||||
if unitType == 1:
|
||||
@@ -62,7 +66,12 @@ def attackFirst():
|
||||
print("YOU LOST " + str(numUnits) + " MEN FROM YOUR ARMY.")
|
||||
usrArmy = usrArmy - numUnits
|
||||
elif numUnits < (2 * usrArmy / 3):
|
||||
print("YOU LOST " + str(int(numUnits / 3)) + " MEN, BUT I LOST " + str(int(2 * cpuArmy / 3)))
|
||||
print(
|
||||
"YOU LOST "
|
||||
+ str(int(numUnits / 3))
|
||||
+ " MEN, BUT I LOST "
|
||||
+ str(int(2 * cpuArmy / 3))
|
||||
)
|
||||
usrArmy = int(usrArmy - (numUnits / 3))
|
||||
cpuArmy = 0
|
||||
else:
|
||||
@@ -128,7 +137,12 @@ def attackSecond():
|
||||
print("HOW MANY MEN")
|
||||
print("? ", end="")
|
||||
numUnits = int(input())
|
||||
if not((numUnits < 0) or ((unitType == 1) and (numUnits > usrArmy)) or ((unitType == 2) and (numUnits > usrNavy)) or ((unitType == 3) and (numUnits > usrAir))):
|
||||
if not (
|
||||
(numUnits < 0)
|
||||
or ((unitType == 1) and (numUnits > usrArmy))
|
||||
or ((unitType == 2) and (numUnits > usrNavy))
|
||||
or ((unitType == 3) and (numUnits > usrAir))
|
||||
):
|
||||
break
|
||||
|
||||
if unitType == 1:
|
||||
@@ -165,7 +179,9 @@ def attackSecond():
|
||||
print("")
|
||||
print("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,")
|
||||
|
||||
if (planeCrashWin == True) or ((usrArmy + usrNavy + usrAir) > (int(3/2*(cpuArmy + cpuNavy + cpuAir)))):
|
||||
if (planeCrashWin == True) or (
|
||||
(usrArmy + usrNavy + usrAir) > (int(3 / 2 * (cpuArmy + cpuNavy + cpuAir)))
|
||||
):
|
||||
print("YOU WON, OH! SHUCKS!!!!")
|
||||
elif (usrArmy + usrNavy + usrAir) < int(2 / 3 * (cpuArmy + cpuNavy + cpuAir)):
|
||||
print("YOU LOST-I CONQUERED YOUR COUNTRY. IT SERVES YOU")
|
||||
@@ -181,5 +197,6 @@ def main():
|
||||
attackFirst()
|
||||
attackSecond()
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -222,6 +222,3 @@ this set that use GOSUB.
|
||||
|
||||
The rest of the code if fairly straight forward, replay the game or end with
|
||||
a report of your winnings or losings.
|
||||
|
||||
|
||||
|
||||
|
||||
1
29_Craps/csharp/.gitignore
vendored
1
29_Craps/csharp/.gitignore
vendored
@@ -2,4 +2,3 @@
|
||||
TestResults
|
||||
bin
|
||||
obj
|
||||
|
||||
|
||||
@@ -139,5 +139,3 @@ namespace Craps
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -57,7 +57,9 @@ while play_again:
|
||||
winnings -= wager
|
||||
elif roll_2 == roll_1:
|
||||
print(f"{roll_1} - a winner.........congrats!!!!!!!!")
|
||||
print(f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars")
|
||||
print(
|
||||
f"{roll_1} at 2 to 1 odds pays you...let me see... {2 * wager} dollars"
|
||||
)
|
||||
winnings += 2 * wager
|
||||
else:
|
||||
print(f"{roll_2} - no point. I will roll again")
|
||||
@@ -69,7 +71,7 @@ while play_again:
|
||||
print(f"You are now ahead ${winnings}")
|
||||
else:
|
||||
print("You are now even at 0")
|
||||
play_again = (m == "5")
|
||||
play_again = m == "5"
|
||||
|
||||
if winnings < 0:
|
||||
print(f"Too bad, you are in the hole. Come again.")
|
||||
|
||||
@@ -122,4 +122,3 @@ end
|
||||
|
||||
craps = CRAPSGAME.new
|
||||
craps.play
|
||||
|
||||
|
||||
@@ -42,19 +42,26 @@ def play_game():
|
||||
move = [-1, -1, -1]
|
||||
while move == [-1, -1, -1]:
|
||||
try:
|
||||
coordinates = [int(item)
|
||||
for item in input(prompt).split(",")]
|
||||
coordinates = [int(item) for item in input(prompt).split(",")]
|
||||
if len(coordinates) == 3:
|
||||
move = coordinates
|
||||
else:
|
||||
raise ValueError
|
||||
except (ValueError, IndexError):
|
||||
print("Please enter valid coordinates.")
|
||||
if (abs(move[0]-position[0]) + abs(move[1]-position[1]) + abs(move[2]-position[2])) > 1:
|
||||
if (
|
||||
abs(move[0] - position[0])
|
||||
+ abs(move[1] - position[1])
|
||||
+ abs(move[2] - position[2])
|
||||
) > 1:
|
||||
print("\nIllegal move. You lose")
|
||||
money = money - wager
|
||||
break
|
||||
elif not move[0] in [1, 2, 3] or not move[1] in [1, 2, 3] or not move[2] in [1, 2, 3]:
|
||||
elif (
|
||||
not move[0] in [1, 2, 3]
|
||||
or not move[1] in [1, 2, 3]
|
||||
or not move[2] in [1, 2, 3]
|
||||
):
|
||||
print("\nIllegal move. You lose")
|
||||
money = money - wager
|
||||
break
|
||||
@@ -106,8 +113,7 @@ def main():
|
||||
keep_playing = True
|
||||
while keep_playing:
|
||||
play_game()
|
||||
keep_playing = input(
|
||||
"\nPlay again? (yes or no) ").lower().startswith("y")
|
||||
keep_playing = input("\nPlay again? (yes or no) ").lower().startswith("y")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -258,4 +258,3 @@ end
|
||||
greeting
|
||||
initializePot
|
||||
gameLoop startGame
|
||||
|
||||
|
||||
@@ -14,4 +14,3 @@ Perl makes life easy.
|
||||
* We use ternarys to generate the message if you miss the sub.
|
||||
* We use join to stitch the pieces of the string together.
|
||||
* If we have a ternary where we don't want to return anything we return an empty list rather than an empty string - if you return the latter you still get the padding spaces.
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ def get_num_charges():
|
||||
|
||||
def ask_for_new_game():
|
||||
answer = input("Another game (Y or N): ")
|
||||
if answer.lower().strip()[0] == 'y':
|
||||
if answer.lower().strip()[0] == "y":
|
||||
start_new_game()
|
||||
else:
|
||||
print("OK. Hope you enjoyed yourself")
|
||||
@@ -76,7 +76,7 @@ def get_shot_input():
|
||||
print(f"Example: 3 2 1")
|
||||
continue
|
||||
try:
|
||||
x, y, z = [int(num) for num in [x, y, z]]
|
||||
x, y, z = (int(num) for num in [x, y, z])
|
||||
return x, y, z
|
||||
except ValueError:
|
||||
print("Please enter whole numbers only")
|
||||
@@ -92,7 +92,7 @@ def play_game(search_area, num_charges):
|
||||
print("\nGood luck!\n")
|
||||
|
||||
# Generate position for submarine
|
||||
a, b, c = [random.randint(0, search_area) for _ in range(3)]
|
||||
a, b, c = (random.randint(0, search_area) for _ in range(3))
|
||||
|
||||
# Get inputs until win or lose
|
||||
for i in range(num_charges):
|
||||
@@ -116,5 +116,5 @@ def start_new_game():
|
||||
play_game(search_area, num_charges)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
start_new_game()
|
||||
|
||||
@@ -33,5 +33,3 @@ for (my $J=1; $J<$Wid; $J++) {
|
||||
}
|
||||
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
Original source downloaded [from Vintage Basic](http://www.vintage-basic.net/games.html)
|
||||
|
||||
Conversion to [Microsoft C#](https://docs.microsoft.com/en-us/dotnet/csharp/) by James Curran (http://www.noveltheory.com)
|
||||
|
||||
|
||||
@@ -38,5 +38,3 @@ do {
|
||||
print "? "; chomp($Z = <STDIN>);
|
||||
} until (uc($Z) ne "YES");
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@
|
||||
|
||||
import random
|
||||
|
||||
|
||||
# We'll track counts of roll outcomes in a 13-element list.
|
||||
# The first two indices (0 & 1) are ignored, leaving just
|
||||
# the indices that match the roll values (2 through 12).
|
||||
@@ -66,7 +65,7 @@ while still_playing:
|
||||
# Keep playing?
|
||||
print("")
|
||||
response = input("Try again? ")
|
||||
if len(response) > 0 and response.upper()[0] == 'Y':
|
||||
if len(response) > 0 and response.upper()[0] == "Y":
|
||||
# Clear out the frequency list
|
||||
freq = [0] * 13
|
||||
else:
|
||||
@@ -74,8 +73,6 @@ while still_playing:
|
||||
still_playing = False
|
||||
|
||||
|
||||
|
||||
|
||||
########################################################
|
||||
#
|
||||
# Porting Notes
|
||||
@@ -114,10 +111,3 @@ while still_playing:
|
||||
# rolled each time?
|
||||
#
|
||||
########################################################
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -183,4 +183,3 @@ public class Digits {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import random
|
||||
|
||||
|
||||
def printIntro():
|
||||
print(" DIGITS")
|
||||
print(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
@@ -45,6 +46,7 @@ def read10Numbers():
|
||||
|
||||
return numbers
|
||||
|
||||
|
||||
def readContinueChoice():
|
||||
print("\nDO YOU WANT TO TRY AGAIN (1 FOR YES, 0 FOR NO) ? ")
|
||||
try:
|
||||
@@ -53,7 +55,8 @@ def readContinueChoice():
|
||||
except (ValueError, TypeError) as m:
|
||||
return False
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
printIntro()
|
||||
if readInstructionChoice():
|
||||
printInstructions()
|
||||
@@ -90,7 +93,10 @@ if __name__ == '__main__':
|
||||
validNumbers = False
|
||||
break
|
||||
|
||||
print("\n%-14s%-14s%-14s%-14s" % ("MY GUESS", "YOUR NO.", "RESULT", "NO. RIGHT"))
|
||||
print(
|
||||
"\n%-14s%-14s%-14s%-14s"
|
||||
% ("MY GUESS", "YOUR NO.", "RESULT", "NO. RIGHT")
|
||||
)
|
||||
|
||||
for number in numbers:
|
||||
s = 0
|
||||
@@ -118,7 +124,9 @@ if __name__ == '__main__':
|
||||
k[int(z2)][number] = k[int(z2)][number] + 1
|
||||
z = z - (z / 9) * 9
|
||||
z = 3 * z + number
|
||||
print("\n%-14d%-14d%-14s%-14d" % (myGuess, number, result, runningCorrect))
|
||||
print(
|
||||
"\n%-14d%-14d%-14s%-14d" % (myGuess, number, result, runningCorrect)
|
||||
)
|
||||
|
||||
z1 = z - (z / 9) * 9
|
||||
z2 = number
|
||||
@@ -128,7 +136,7 @@ if __name__ == '__main__':
|
||||
if runningCorrect > 10:
|
||||
print()
|
||||
print("I GUESSED MORE THAN 1/3 OF YOUR NUMBERS.")
|
||||
print("I WIN." + u"\u0007")
|
||||
print("I WIN." + "\u0007")
|
||||
elif runningCorrect < 10:
|
||||
print("I GUESSED LESS THAN 1/3 OF YOUR NUMBERS.")
|
||||
print("YOU BEAT ME. CONGRATULATIONS *****")
|
||||
|
||||
@@ -25,41 +25,45 @@ import random
|
||||
marbles_in_middle = -1
|
||||
human_marbles = -1
|
||||
computer_marbles = -1
|
||||
whose_turn = ''
|
||||
whose_turn = ""
|
||||
|
||||
# Only called during development for serious errors that are due to mistakes
|
||||
# in the program. Should never be called during a regular game.
|
||||
def serious_error(msg):
|
||||
print('serious_error: ' + msg)
|
||||
print("serious_error: " + msg)
|
||||
exit(1)
|
||||
|
||||
|
||||
def welcome_screen():
|
||||
print('Welcome to Even Wins!')
|
||||
print('Based on evenwins.bas from Creative Computing')
|
||||
print("Welcome to Even Wins!")
|
||||
print("Based on evenwins.bas from Creative Computing")
|
||||
print()
|
||||
print('Even Wins is a two-person game. You start with')
|
||||
print('27 marbles in the middle of the table.')
|
||||
print("Even Wins is a two-person game. You start with")
|
||||
print("27 marbles in the middle of the table.")
|
||||
print()
|
||||
print('Players alternate taking marbles from the middle.')
|
||||
print('A player can take 1 to 4 marbles on their turn, and')
|
||||
print('turns cannot be skipped. The game ends when there are')
|
||||
print('no marbles left, and the winner is the one with an even')
|
||||
print('number of marbles.')
|
||||
print("Players alternate taking marbles from the middle.")
|
||||
print("A player can take 1 to 4 marbles on their turn, and")
|
||||
print("turns cannot be skipped. The game ends when there are")
|
||||
print("no marbles left, and the winner is the one with an even")
|
||||
print("number of marbles.")
|
||||
print()
|
||||
|
||||
|
||||
def marbles_str(n):
|
||||
if n == 1: return '1 marble'
|
||||
return f'{n} marbles'
|
||||
if n == 1:
|
||||
return "1 marble"
|
||||
return f"{n} marbles"
|
||||
|
||||
|
||||
def choose_first_player():
|
||||
global whose_turn
|
||||
while True:
|
||||
ans = input('Do you want to play first? (y/n) --> ')
|
||||
if ans == 'y':
|
||||
whose_turn = 'human'
|
||||
ans = input("Do you want to play first? (y/n) --> ")
|
||||
if ans == "y":
|
||||
whose_turn = "human"
|
||||
return
|
||||
elif ans == 'n':
|
||||
whose_turn = 'computer'
|
||||
elif ans == "n":
|
||||
whose_turn = "computer"
|
||||
return
|
||||
else:
|
||||
print()
|
||||
@@ -67,14 +71,16 @@ def choose_first_player():
|
||||
print('or "n" if you want to play second.')
|
||||
print()
|
||||
|
||||
|
||||
def next_player():
|
||||
global whose_turn
|
||||
if whose_turn == 'human':
|
||||
whose_turn = 'computer'
|
||||
elif whose_turn == 'computer':
|
||||
whose_turn = 'human'
|
||||
if whose_turn == "human":
|
||||
whose_turn = "computer"
|
||||
elif whose_turn == "computer":
|
||||
whose_turn = "human"
|
||||
else:
|
||||
serious_error(f'play_game: unknown player {whose_turn}')
|
||||
serious_error(f"play_game: unknown player {whose_turn}")
|
||||
|
||||
|
||||
# Converts a string s to an int, if possible.
|
||||
def to_int(s):
|
||||
@@ -84,16 +90,18 @@ def to_int(s):
|
||||
except:
|
||||
return False, 0
|
||||
|
||||
|
||||
def print_board():
|
||||
global marbles_in_middle
|
||||
global human_marbles
|
||||
global computer_marbles
|
||||
print()
|
||||
print(f' marbles in the middle: {marbles_in_middle} ' + marbles_in_middle*'*')
|
||||
print(f' # marbles you have: {human_marbles}')
|
||||
print(f'# marbles computer has: {computer_marbles}')
|
||||
print(f" marbles in the middle: {marbles_in_middle} " + marbles_in_middle * "*")
|
||||
print(f" # marbles you have: {human_marbles}")
|
||||
print(f"# marbles computer has: {computer_marbles}")
|
||||
print()
|
||||
|
||||
|
||||
def human_turn():
|
||||
global marbles_in_middle
|
||||
global human_marbles
|
||||
@@ -102,44 +110,46 @@ def human_turn():
|
||||
max_choice = min(4, marbles_in_middle)
|
||||
print("It's your turn!")
|
||||
while True:
|
||||
s = input(f'Marbles to take? (1 - {max_choice}) --> ')
|
||||
s = input(f"Marbles to take? (1 - {max_choice}) --> ")
|
||||
ok, n = to_int(s)
|
||||
if not ok:
|
||||
print()
|
||||
print(f' Please enter a whole number from 1 to {max_choice}')
|
||||
print(f" Please enter a whole number from 1 to {max_choice}")
|
||||
print()
|
||||
continue
|
||||
if n < 1:
|
||||
print()
|
||||
print(' You must take at least 1 marble!')
|
||||
print(" You must take at least 1 marble!")
|
||||
print()
|
||||
continue
|
||||
if n > max_choice:
|
||||
print()
|
||||
print(f' You can take at most {marbles_str(max_choice)}')
|
||||
print(f" You can take at most {marbles_str(max_choice)}")
|
||||
print()
|
||||
continue
|
||||
print()
|
||||
print(f'Okay, taking {marbles_str(n)} ...')
|
||||
print(f"Okay, taking {marbles_str(n)} ...")
|
||||
marbles_in_middle -= n
|
||||
human_marbles += n
|
||||
return
|
||||
|
||||
|
||||
def game_over():
|
||||
global marbles_in_middle
|
||||
global human_marbles
|
||||
global computer_marbles
|
||||
print()
|
||||
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
|
||||
print('!! All the marbles are taken: Game Over!')
|
||||
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
|
||||
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
|
||||
print("!! All the marbles are taken: Game Over!")
|
||||
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
|
||||
print()
|
||||
print_board()
|
||||
if human_marbles % 2 == 0:
|
||||
print('You are the winner! Congratulations!')
|
||||
print("You are the winner! Congratulations!")
|
||||
else:
|
||||
print('The computer wins: all hail mighty silicon!')
|
||||
print('')
|
||||
print("The computer wins: all hail mighty silicon!")
|
||||
print("")
|
||||
|
||||
|
||||
def computer_turn():
|
||||
global marbles_in_middle
|
||||
@@ -149,7 +159,7 @@ def computer_turn():
|
||||
marbles_to_take = 0
|
||||
|
||||
print("It's the computer's turn ...")
|
||||
r = marbles_in_middle - 6 * int((marbles_in_middle/6)) #line 500
|
||||
r = marbles_in_middle - 6 * int(marbles_in_middle / 6) # line 500
|
||||
|
||||
if int(human_marbles / 2) == human_marbles / 2: # line 510
|
||||
if r < 1.5 or r > 5.3: # lines 710 and 720
|
||||
@@ -165,10 +175,11 @@ def computer_turn():
|
||||
else:
|
||||
marbles_to_take = r + 1
|
||||
|
||||
print(f'Computer takes {marbles_str(marbles_to_take)} ...')
|
||||
print(f"Computer takes {marbles_str(marbles_to_take)} ...")
|
||||
marbles_in_middle -= marbles_to_take
|
||||
computer_marbles += marbles_to_take
|
||||
|
||||
|
||||
def play_game():
|
||||
global marbles_in_middle
|
||||
global human_marbles
|
||||
@@ -184,16 +195,17 @@ def play_game():
|
||||
if marbles_in_middle == 0:
|
||||
game_over()
|
||||
return
|
||||
elif whose_turn == 'human':
|
||||
elif whose_turn == "human":
|
||||
human_turn()
|
||||
print_board()
|
||||
next_player()
|
||||
elif whose_turn == 'computer':
|
||||
elif whose_turn == "computer":
|
||||
computer_turn()
|
||||
print_board()
|
||||
next_player()
|
||||
else:
|
||||
serious_error(f'play_game: unknown player {whose_turn}')
|
||||
serious_error(f"play_game: unknown player {whose_turn}")
|
||||
|
||||
|
||||
def main():
|
||||
global whose_turn
|
||||
@@ -206,16 +218,17 @@ def main():
|
||||
|
||||
# ask if the user if they want to play again
|
||||
print()
|
||||
again = input('Would you like to play again? (y/n) --> ')
|
||||
if again == 'y':
|
||||
again = input("Would you like to play again? (y/n) --> ")
|
||||
if again == "y":
|
||||
print()
|
||||
print("Ok, let's play again ...")
|
||||
print()
|
||||
else:
|
||||
print()
|
||||
print('Ok, thanks for playing ... goodbye!')
|
||||
print("Ok, thanks for playing ... goodbye!")
|
||||
print()
|
||||
return
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
# The original author of this game was
|
||||
# Michael Kass of New Hyde Park, New
|
||||
# York.
|
||||
import random
|
||||
import math
|
||||
import random
|
||||
from typing import Callable, List, Tuple
|
||||
|
||||
flip_dict = {"X": "O", "O": "X"}
|
||||
|
||||
@@ -20,4 +20,3 @@ of the code (using the previous `D1` value), but also catching the
|
||||
uninitialised path, and assigning a "best guess" value.
|
||||
|
||||
krt@krt.com.au 2020-10-10
|
||||
|
||||
|
||||
@@ -22,4 +22,3 @@ of the code (using the previous `D1` value), but also catching the
|
||||
uninitialised path, and assigning a "best guess" value.
|
||||
|
||||
krt@krt.com.au 2020-10-10
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
#! /usr/bin/env python3
|
||||
|
||||
import sys # for system function, like exit()
|
||||
import random # for generating random numbers
|
||||
|
||||
import sys # for system function, like exit()
|
||||
|
||||
### global variables for storing player's status
|
||||
player_funds = 0 # no money
|
||||
@@ -23,10 +22,9 @@ FORT_NEWYORK = 3
|
||||
FORT_NAMES = ["HOCHELAGA (MONTREAL)", "STADACONA (QUEBEC)", "NEW YORK"]
|
||||
|
||||
|
||||
|
||||
def printAtColumn(column: int, words: str):
|
||||
"""Print the words at the specified column"""
|
||||
spaces = ' ' * column # make a fat string of spaces
|
||||
spaces = " " * column # make a fat string of spaces
|
||||
print(spaces + words)
|
||||
|
||||
|
||||
@@ -46,7 +44,7 @@ def getFortChoice():
|
||||
input is a valid choice (1,2,3) return it, otherwise keep
|
||||
prompting the user."""
|
||||
result = 0
|
||||
while ( result == 0 ):
|
||||
while result == 0:
|
||||
print("")
|
||||
print("YOU MAY TRADE YOUR FURS AT FORT 1, FORT 2,")
|
||||
print("OR FORT 3. FORT 1 IS FORT HOCHELAGA (MONTREAL)")
|
||||
@@ -73,17 +71,17 @@ def getFortChoice():
|
||||
def showFortComment(which_fort):
|
||||
"""Print the description for the fort"""
|
||||
print("")
|
||||
if ( which_fort == FORT_MONTREAL ):
|
||||
if which_fort == FORT_MONTREAL:
|
||||
print("YOU HAVE CHOSEN THE EASIEST ROUTE. HOWEVER, THE FORT")
|
||||
print("IS FAR FROM ANY SEAPORT. THE VALUE")
|
||||
print("YOU RECEIVE FOR YOUR FURS WILL BE LOW AND THE COST")
|
||||
print("OF SUPPLIES HIGHER THAN AT FORTS STADACONA OR NEW YORK.")
|
||||
elif ( which_fort == FORT_QUEBEC ):
|
||||
elif which_fort == FORT_QUEBEC:
|
||||
print("YOU HAVE CHOSEN A HARD ROUTE. IT IS, IN COMPARSION,")
|
||||
print("HARDER THAN THE ROUTE TO HOCHELAGA BUT EASIER THAN")
|
||||
print("THE ROUTE TO NEW YORK. YOU WILL RECEIVE AN AVERAGE VALUE")
|
||||
print("FOR YOUR FURS AND THE COST OF YOUR SUPPLIES WILL BE AVERAGE.")
|
||||
elif ( which_fort == FORT_NEWYORK ):
|
||||
elif which_fort == FORT_NEWYORK:
|
||||
print("YOU HAVE CHOSEN THE MOST DIFFICULT ROUTE. AT")
|
||||
print("FORT NEW YORK YOU WILL RECEIVE THE HIGHEST VALUE")
|
||||
print("FOR YOUR FURS. THE COST OF YOUR SUPPLIES")
|
||||
@@ -100,14 +98,14 @@ def getYesOrNo():
|
||||
checking the first letter of input.
|
||||
Return a single letter 'Y' or 'N'"""
|
||||
result = 0
|
||||
while ( result not in ( 'Y', 'N' ) ):
|
||||
while result not in ("Y", "N"):
|
||||
print("ANSWER YES OR NO")
|
||||
player_choice = input(">> ")
|
||||
player_choice = player_choice.strip().upper() # trim spaces, make upper-case
|
||||
if ( player_choice.startswith( 'Y' ) ):
|
||||
result = 'Y'
|
||||
elif ( player_choice.startswith( 'N' ) ):
|
||||
result = 'N'
|
||||
if player_choice.startswith("Y"):
|
||||
result = "Y"
|
||||
elif player_choice.startswith("N"):
|
||||
result = "N"
|
||||
return result
|
||||
|
||||
|
||||
@@ -120,7 +118,7 @@ def getFursPurchase():
|
||||
print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.")
|
||||
print("")
|
||||
|
||||
for i in ( range( len( FUR_NAMES ) ) ):
|
||||
for i in range(len(FUR_NAMES)):
|
||||
print("HOW MANY " + FUR_NAMES[i] + " DO YOU HAVE")
|
||||
count_str = input(">> ")
|
||||
try:
|
||||
@@ -132,24 +130,23 @@ def getFursPurchase():
|
||||
return results
|
||||
|
||||
|
||||
|
||||
###
|
||||
### MAIN
|
||||
###
|
||||
|
||||
if ( __name__ == '__main__' ):
|
||||
if __name__ == "__main__":
|
||||
|
||||
printAtColumn(31, "FUR TRADER")
|
||||
printAtColumn(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
printAtColumn(15, "(Ported to Python Oct 2012 krt@krt.com.au)")
|
||||
print("\n\n\n")
|
||||
|
||||
game_state = 'starting'
|
||||
game_state = "starting"
|
||||
fox_price = None # sometimes this takes the "last" price (probably this was a bug)
|
||||
|
||||
while ( True ):
|
||||
while True:
|
||||
|
||||
if ( game_state == 'starting' ):
|
||||
if game_state == "starting":
|
||||
showIntroduction()
|
||||
|
||||
player_funds = 600 # Initial player start money
|
||||
@@ -157,69 +154,88 @@ if ( __name__ == '__main__' ):
|
||||
|
||||
print("DO YOU WISH TO TRADE FURS?")
|
||||
should_trade = getYesOrNo()
|
||||
if ( should_trade == 'N' ):
|
||||
if should_trade == "N":
|
||||
sys.exit(0) # STOP
|
||||
game_state = 'trading'
|
||||
game_state = "trading"
|
||||
|
||||
elif ( game_state == 'trading' ):
|
||||
elif game_state == "trading":
|
||||
print("")
|
||||
print("YOU HAVE $ %1.2f IN SAVINGS" % (player_funds))
|
||||
print("AND " + str(MAX_FURS) + " FURS TO BEGIN THE EXPEDITION")
|
||||
player_furs = getFursPurchase()
|
||||
|
||||
if ( sum( player_furs ) > MAX_FURS ):
|
||||
if sum(player_furs) > MAX_FURS:
|
||||
print("")
|
||||
print("YOU MAY NOT HAVE THAT MANY FURS.")
|
||||
print("DO NOT TRY TO CHEAT. I CAN ADD.")
|
||||
print("YOU MUST START AGAIN.")
|
||||
game_state = 'starting' # T/N: Wow, harsh.
|
||||
game_state = "starting" # T/N: Wow, harsh.
|
||||
else:
|
||||
game_state = 'choosing fort'
|
||||
game_state = "choosing fort"
|
||||
|
||||
elif ( game_state == 'choosing fort' ):
|
||||
elif game_state == "choosing fort":
|
||||
which_fort = getFortChoice()
|
||||
showFortComment(which_fort)
|
||||
print("DO YOU WANT TO TRADE AT ANOTHER FORT?")
|
||||
change_fort = getYesOrNo()
|
||||
if ( change_fort == 'N' ):
|
||||
game_state = 'travelling'
|
||||
if change_fort == "N":
|
||||
game_state = "travelling"
|
||||
|
||||
elif ( game_state == 'travelling' ):
|
||||
elif game_state == "travelling":
|
||||
print("")
|
||||
if ( which_fort == FORT_MONTREAL ):
|
||||
mink_price = int( ( 0.2 * random.random() + 0.70 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.7)*10^2+.5)/10^2
|
||||
ermine_price = int( ( 0.2 * random.random() + 0.65 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.65)*10^2+.5)/10^2
|
||||
beaver_price = int( ( 0.2 * random.random() + 0.75 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.75)*10^2+.5)/10^2
|
||||
fox_price = int( ( 0.2 * random.random() + 0.80 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.8)*10^2+.5)/10^2
|
||||
if which_fort == FORT_MONTREAL:
|
||||
mink_price = (
|
||||
int((0.2 * random.random() + 0.70) * 100 + 0.5) / 100
|
||||
) # INT((.2*RND(1)+.7)*10^2+.5)/10^2
|
||||
ermine_price = (
|
||||
int((0.2 * random.random() + 0.65) * 100 + 0.5) / 100
|
||||
) # INT((.2*RND(1)+.65)*10^2+.5)/10^2
|
||||
beaver_price = (
|
||||
int((0.2 * random.random() + 0.75) * 100 + 0.5) / 100
|
||||
) # INT((.2*RND(1)+.75)*10^2+.5)/10^2
|
||||
fox_price = (
|
||||
int((0.2 * random.random() + 0.80) * 100 + 0.5) / 100
|
||||
) # INT((.2*RND(1)+.8)*10^2+.5)/10^2
|
||||
|
||||
print("SUPPLIES AT FORT HOCHELAGA COST $150.00.")
|
||||
print("YOUR TRAVEL EXPENSES TO HOCHELAGA WERE $10.00.")
|
||||
player_funds -= 160
|
||||
|
||||
elif ( which_fort == FORT_QUEBEC ):
|
||||
mink_price = int( ( 0.30 * random.random() + 0.85 ) * 100 + 0.5 ) / 100 #INT((.3*RND(1)+.85)*10^2+.5)/10^2
|
||||
ermine_price = int( ( 0.15 * random.random() + 0.80 ) * 100 + 0.5 ) / 100 #INT((.15*RND(1)+.8)*10^2+.5)/10^2
|
||||
beaver_price = int( ( 0.20 * random.random() + 0.90 ) * 100 + 0.5 ) / 100 #INT((.2*RND(1)+.9)*10^2+.5)/10^2
|
||||
fox_price = int( ( 0.25 * random.random() + 1.10 ) * 100 + 0.5 ) / 100 #INT((.25*RND(1)+1.1)*10^2+.5)/10^2
|
||||
elif which_fort == FORT_QUEBEC:
|
||||
mink_price = (
|
||||
int((0.30 * random.random() + 0.85) * 100 + 0.5) / 100
|
||||
) # INT((.3*RND(1)+.85)*10^2+.5)/10^2
|
||||
ermine_price = (
|
||||
int((0.15 * random.random() + 0.80) * 100 + 0.5) / 100
|
||||
) # INT((.15*RND(1)+.8)*10^2+.5)/10^2
|
||||
beaver_price = (
|
||||
int((0.20 * random.random() + 0.90) * 100 + 0.5) / 100
|
||||
) # INT((.2*RND(1)+.9)*10^2+.5)/10^2
|
||||
fox_price = (
|
||||
int((0.25 * random.random() + 1.10) * 100 + 0.5) / 100
|
||||
) # INT((.25*RND(1)+1.1)*10^2+.5)/10^2
|
||||
event_picker = int(10 * random.random()) + 1
|
||||
|
||||
if ( event_picker <= 2 ):
|
||||
if event_picker <= 2:
|
||||
print("YOUR BEAVER WERE TOO HEAVY TO CARRY ACROSS")
|
||||
print("THE PORTAGE. YOU HAD TO LEAVE THE PELTS, BUT FOUND")
|
||||
print("THEM STOLEN WHEN YOU RETURNED.")
|
||||
player_furs[FUR_BEAVER] = 0
|
||||
elif ( event_picker <= 6 ):
|
||||
elif event_picker <= 6:
|
||||
print("YOU ARRIVED SAFELY AT FORT STADACONA.")
|
||||
elif ( event_picker <= 8 ):
|
||||
elif event_picker <= 8:
|
||||
print("YOUR CANOE UPSET IN THE LACHINE RAPIDS. YOU")
|
||||
print("LOST ALL YOUR FURS.")
|
||||
player_furs = [0, 0, 0, 0]
|
||||
elif ( event_picker <= 10 ):
|
||||
elif event_picker <= 10:
|
||||
print("YOUR FOX PELTS WERE NOT CURED PROPERLY.")
|
||||
print("NO ONE WILL BUY THEM.")
|
||||
player_furs[FUR_FOX] = 0
|
||||
else:
|
||||
print( "Internal Error #3, Out-of-bounds event_picker" + str( event_picker ) )
|
||||
print(
|
||||
"Internal Error #3, Out-of-bounds event_picker"
|
||||
+ str(event_picker)
|
||||
)
|
||||
sys.exit(1) # you have a bug
|
||||
|
||||
print("")
|
||||
@@ -227,35 +243,46 @@ if ( __name__ == '__main__' ):
|
||||
print("YOUR TRAVEL EXPENSES TO STADACONA WERE $15.00.")
|
||||
player_funds -= 140
|
||||
|
||||
elif ( which_fort == FORT_NEWYORK ):
|
||||
mink_price = int( ( 0.15 * random.random() + 1.05 ) * 100 + 0.5 ) / 100 #INT((.15*RND(1)+1.05)*10^2+.5)/10^2
|
||||
ermine_price = int( ( 0.15 * random.random() + 0.95 ) * 100 + 0.5 ) / 100 #INT((.15*RND(1)+.95)*10^2+.5)/10^2
|
||||
beaver_price = int( ( 0.25 * random.random() + 1.00 ) * 100 + 0.5 ) / 100 #INT((.25*RND(1)+1.00)*10^2+.5)/10^2
|
||||
if ( fox_price == None ):
|
||||
elif which_fort == FORT_NEWYORK:
|
||||
mink_price = (
|
||||
int((0.15 * random.random() + 1.05) * 100 + 0.5) / 100
|
||||
) # INT((.15*RND(1)+1.05)*10^2+.5)/10^2
|
||||
ermine_price = (
|
||||
int((0.15 * random.random() + 0.95) * 100 + 0.5) / 100
|
||||
) # INT((.15*RND(1)+.95)*10^2+.5)/10^2
|
||||
beaver_price = (
|
||||
int((0.25 * random.random() + 1.00) * 100 + 0.5) / 100
|
||||
) # INT((.25*RND(1)+1.00)*10^2+.5)/10^2
|
||||
if fox_price == None:
|
||||
# Original Bug? There is no Fox price generated for New York, it will use any previous "D1" price
|
||||
# So if there was no previous value, make one up
|
||||
fox_price = int( ( 0.25 * random.random() + 1.05 ) * 100 + 0.5 ) / 100 # not in orginal code
|
||||
fox_price = (
|
||||
int((0.25 * random.random() + 1.05) * 100 + 0.5) / 100
|
||||
) # not in orginal code
|
||||
event_picker = int(10 * random.random()) + 1
|
||||
|
||||
if ( event_picker <= 2 ):
|
||||
if event_picker <= 2:
|
||||
print("YOU WERE ATTACKED BY A PARTY OF IROQUOIS.")
|
||||
print("ALL PEOPLE IN YOUR TRADING GROUP WERE")
|
||||
print("KILLED. THIS ENDS THE GAME.")
|
||||
sys.exit(0)
|
||||
elif ( event_picker <= 6 ):
|
||||
elif event_picker <= 6:
|
||||
print("YOU WERE LUCKY. YOU ARRIVED SAFELY")
|
||||
print("AT FORT NEW YORK.")
|
||||
elif ( event_picker <= 8 ):
|
||||
elif event_picker <= 8:
|
||||
print("YOU NARROWLY ESCAPED AN IROQUOIS RAIDING PARTY.")
|
||||
print("HOWEVER, YOU HAD TO LEAVE ALL YOUR FURS BEHIND.")
|
||||
player_furs = [0, 0, 0, 0]
|
||||
elif ( event_picker <= 10 ):
|
||||
elif event_picker <= 10:
|
||||
mink_price /= 2
|
||||
fox_price /= 2
|
||||
print("YOUR MINK AND BEAVER WERE DAMAGED ON YOUR TRIP.")
|
||||
print("YOU RECEIVE ONLY HALF THE CURRENT PRICE FOR THESE FURS.")
|
||||
else:
|
||||
print( "Internal Error #4, Out-of-bounds event_picker" + str( event_picker ) )
|
||||
print(
|
||||
"Internal Error #4, Out-of-bounds event_picker"
|
||||
+ str(event_picker)
|
||||
)
|
||||
sys.exit(1) # you have a bug
|
||||
|
||||
print("")
|
||||
@@ -263,7 +290,6 @@ if ( __name__ == '__main__' ):
|
||||
print("YOUR TRAVEL EXPENSES TO NEW YORK WERE $25.00.")
|
||||
player_funds -= 105
|
||||
|
||||
|
||||
else:
|
||||
print("Internal error #2, fort " + str(which_fort) + " does not exist")
|
||||
sys.exit(1) # you have a bug
|
||||
@@ -283,15 +309,14 @@ if ( __name__ == '__main__' ):
|
||||
player_funds += beaver_value + fox_value + ermine_value + mink_value
|
||||
|
||||
print("")
|
||||
print( "YOU NOW HAVE $ %1.2f INCLUDING YOUR PREVIOUS SAVINGS" % ( player_funds ) )
|
||||
print(
|
||||
"YOU NOW HAVE $ %1.2f INCLUDING YOUR PREVIOUS SAVINGS" % (player_funds)
|
||||
)
|
||||
|
||||
print("")
|
||||
print("DO YOU WANT TO TRADE FURS NEXT YEAR?")
|
||||
should_trade = getYesOrNo()
|
||||
if ( should_trade == 'N' ):
|
||||
if should_trade == "N":
|
||||
sys.exit(0) # STOP
|
||||
else:
|
||||
game_state = 'trading'
|
||||
|
||||
|
||||
|
||||
game_state = "trading"
|
||||
|
||||
@@ -8,8 +8,3 @@ Program.cs contains the C# source code.
|
||||
It has been written for .NET Core 3.1
|
||||
|
||||
The source code is well documented.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -208,4 +208,3 @@ public class Gomoko {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -117,5 +117,3 @@ sub ValidMove {
|
||||
#$Board[$X][$Y]= $Val;
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -48,5 +48,3 @@ sub ENTERS { #GOSUB 70
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ while True:
|
||||
won = False
|
||||
my_guess = int(limit * random() + 1)
|
||||
|
||||
print("I'm thinking of a number between 1 and {}".format(limit))
|
||||
print(f"I'm thinking of a number between 1 and {limit}")
|
||||
print("Now you try to guess what it is.")
|
||||
|
||||
while still_guessing:
|
||||
@@ -79,7 +79,7 @@ while True:
|
||||
print("Too high. Try a smaller answer")
|
||||
guess_count += 1
|
||||
else:
|
||||
print("That's it! You got it in {} tries".format(guess_count))
|
||||
print(f"That's it! You got it in {guess_count} tries")
|
||||
won = True
|
||||
still_guessing = False
|
||||
|
||||
@@ -89,7 +89,7 @@ while True:
|
||||
elif guess_count == limit_goal:
|
||||
print("Good.")
|
||||
else:
|
||||
print("You should have been able to get it in only {}".format(limit_goal))
|
||||
print(f"You should have been able to get it in only {limit_goal}")
|
||||
insert_whitespaces()
|
||||
else:
|
||||
insert_whitespaces()
|
||||
|
||||
@@ -15,7 +15,7 @@ def gunner():
|
||||
S1 = 0
|
||||
|
||||
while True:
|
||||
T = int(R * (.1 + .8 * random()))
|
||||
T = int(R * (0.1 + 0.8 * random()))
|
||||
S = 0
|
||||
|
||||
print("\nDISTANCE TO THE TARGET IS", T, "YARDS.")
|
||||
@@ -39,8 +39,10 @@ def gunner():
|
||||
X = T - I
|
||||
E = int(X)
|
||||
|
||||
if (abs(E) < 100):
|
||||
print("*** TARGET DESTROYED *** ", S, "ROUNDS OF AMMUNITION EXPENDED.")
|
||||
if abs(E) < 100:
|
||||
print(
|
||||
"*** TARGET DESTROYED *** ", S, "ROUNDS OF AMMUNITION EXPENDED."
|
||||
)
|
||||
S1 += S
|
||||
if Z == 4:
|
||||
print("\n\nTOTAL ROUNDS EXPENDED WERE: ", S1)
|
||||
@@ -52,7 +54,9 @@ def gunner():
|
||||
return
|
||||
else:
|
||||
Z += 1
|
||||
print("\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY...")
|
||||
print(
|
||||
"\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..."
|
||||
)
|
||||
break
|
||||
else:
|
||||
if E > 100:
|
||||
@@ -80,6 +84,6 @@ if __name__ == "__main__":
|
||||
gunner()
|
||||
|
||||
Y = input("TRY AGAIN (Y OR N)? ")
|
||||
if (Y != "Y"):
|
||||
if Y != "Y":
|
||||
print("\nOK. RETURN TO BASE CAMP.")
|
||||
break
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from random import random
|
||||
from random import seed
|
||||
from random import random, seed
|
||||
|
||||
|
||||
def gen_random():
|
||||
@@ -36,12 +35,12 @@ def b_input(promptstring): # emulate BASIC input. It rejects non-numeric values
|
||||
|
||||
seed()
|
||||
title = "HAMURABI"
|
||||
title = title.rjust(32, ' ')
|
||||
title = title.rjust(32, " ")
|
||||
print(title)
|
||||
attribution = "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"
|
||||
attribution = attribution.rjust(15, " ")
|
||||
print(attribution)
|
||||
print('\n\n\n')
|
||||
print("\n\n\n")
|
||||
print("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA")
|
||||
print("FOR A TEN-YEAR TERM OF OFFICE.\n")
|
||||
|
||||
@@ -164,11 +163,11 @@ while Z < 11: # line 270. main loop. while the year is less than 11
|
||||
C = int(Q / 20)
|
||||
# REM *** HORROS, A 15% CHANCE OF PLAGUE
|
||||
# yeah, should be HORRORS, but left it
|
||||
Q = int(10 * (2 * random() - .3))
|
||||
Q = int(10 * (2 * random() - 0.3))
|
||||
if P >= C and Z != 99: # if there are some people without full bellies...
|
||||
# REM *** STARVE ENOUGH FOR IMPEACHMENT?
|
||||
D = P - C
|
||||
if D > .45 * P:
|
||||
if D > 0.45 * P:
|
||||
print("\nYOU STARVED", D, "PEOPLE IN ONE YEAR!!!")
|
||||
national_fink()
|
||||
Z = 99 # exit the loop
|
||||
@@ -191,13 +190,13 @@ if Z != 99:
|
||||
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 * .8 * random()), "PEOPLE")
|
||||
print("REALLY WASN'T TOO BAD AT ALL. ", int(P * 0.8 * random()), "PEOPLE")
|
||||
print("WOULD DEARLY LIKE TO SEE YOU ASSASSINATED BUT WE ALL HAVE OUR")
|
||||
print("TRIVIAL PROBLEMS.")
|
||||
else:
|
||||
print("A FANTASTIC PERFORMANCE!!! CHARLEMANGE, DISRAELI, AND")
|
||||
print("JEFFERSON COMBINED COULD NOT HAVE DONE BETTER!\n")
|
||||
for N in range(1, 10):
|
||||
print('\a')
|
||||
print("\a")
|
||||
|
||||
print("\nSO LONG FOR NOW.\n")
|
||||
|
||||
@@ -114,19 +114,62 @@ PHASES = (
|
||||
("Now we put up a hand.", draw_left_hand),
|
||||
("Next the other hand.", draw_right_hand),
|
||||
("Now we draw one foot", draw_left_foot),
|
||||
("Here's the other foot -- you're hung!!", draw_right_foot)
|
||||
("Here's the other foot -- you're hung!!", draw_right_foot),
|
||||
)
|
||||
|
||||
|
||||
words = ["GUM", "SIN", "FOR", "CRY", "LUG", "BYE", "FLY",
|
||||
"UGLY", "EACH", "FROM", "WORK", "TALK", "WITH", "SELF",
|
||||
"PIZZA", "THING", "FEIGN", "FIEND", "ELBOW", "FAULT", "DIRTY",
|
||||
"BUDGET", "SPIRIT", "QUAINT", "MAIDEN", "ESCORT", "PICKAX",
|
||||
"EXAMPLE", "TENSION", "QUININE", "KIDNEY", "REPLICA", "SLEEPER",
|
||||
"TRIANGLE", "KANGAROO", "MAHOGANY", "SERGEANT", "SEQUENCE",
|
||||
"MOUSTACHE", "DANGEROUS", "SCIENTIST", "DIFFERENT", "QUIESCENT",
|
||||
"MAGISTRATE", "ERRONEOUSLY", "LOUDSPEAKER", "PHYTOTOXIC",
|
||||
"MATRIMONIAL", "PARASYMPATHOMIMETIC", "THIGMOTROPISM"]
|
||||
words = [
|
||||
"GUM",
|
||||
"SIN",
|
||||
"FOR",
|
||||
"CRY",
|
||||
"LUG",
|
||||
"BYE",
|
||||
"FLY",
|
||||
"UGLY",
|
||||
"EACH",
|
||||
"FROM",
|
||||
"WORK",
|
||||
"TALK",
|
||||
"WITH",
|
||||
"SELF",
|
||||
"PIZZA",
|
||||
"THING",
|
||||
"FEIGN",
|
||||
"FIEND",
|
||||
"ELBOW",
|
||||
"FAULT",
|
||||
"DIRTY",
|
||||
"BUDGET",
|
||||
"SPIRIT",
|
||||
"QUAINT",
|
||||
"MAIDEN",
|
||||
"ESCORT",
|
||||
"PICKAX",
|
||||
"EXAMPLE",
|
||||
"TENSION",
|
||||
"QUININE",
|
||||
"KIDNEY",
|
||||
"REPLICA",
|
||||
"SLEEPER",
|
||||
"TRIANGLE",
|
||||
"KANGAROO",
|
||||
"MAHOGANY",
|
||||
"SERGEANT",
|
||||
"SEQUENCE",
|
||||
"MOUSTACHE",
|
||||
"DANGEROUS",
|
||||
"SCIENTIST",
|
||||
"DIFFERENT",
|
||||
"QUIESCENT",
|
||||
"MAGISTRATE",
|
||||
"ERRONEOUSLY",
|
||||
"LOUDSPEAKER",
|
||||
"PHYTOTOXIC",
|
||||
"MATRIMONIAL",
|
||||
"PARASYMPATHOMIMETIC",
|
||||
"THIGMOTROPISM",
|
||||
]
|
||||
|
||||
|
||||
def play_game(guess_target):
|
||||
@@ -158,7 +201,9 @@ def play_game(guess_target):
|
||||
guess_list.append(guess_letter)
|
||||
guess_count += 1
|
||||
if guess_letter in guess_target:
|
||||
indices = [i for i, letter in enumerate(guess_target) if letter == guess_letter]
|
||||
indices = [
|
||||
i for i, letter in enumerate(guess_target) if letter == guess_letter
|
||||
]
|
||||
for i in indices:
|
||||
guess_progress[i] = guess_letter
|
||||
if guess_progress == guess_target:
|
||||
@@ -207,11 +252,12 @@ def main():
|
||||
print("You did all the words!!")
|
||||
keep_playing = False
|
||||
else:
|
||||
keep_playing = input("Want another word? (yes or no) ").lower().startswith("y")
|
||||
keep_playing = (
|
||||
input("Want another word? (yes or no) ").lower().startswith("y")
|
||||
)
|
||||
|
||||
print("It's been fun! Bye for now.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
@@ -80,4 +80,3 @@ static int ReadInt(string question)
|
||||
Console.WriteLine("!Invalid Number Entered.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,5 +41,3 @@ do {
|
||||
} until (uc($A) ne "YES");
|
||||
print "\n"; print "SO LONG. HOPE YOU ENJOYED YOURSELF!!!\n";
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -2,17 +2,18 @@
|
||||
import random
|
||||
|
||||
MAX_ATTEMPTS = 6
|
||||
QUESTION_PROMPT='? '
|
||||
QUESTION_PROMPT = "? "
|
||||
|
||||
|
||||
def play():
|
||||
print('HI LO')
|
||||
print('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n')
|
||||
print('THIS IS THE GAME OF HI LO.\n')
|
||||
print('YOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE')
|
||||
print('HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU')
|
||||
print('GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!')
|
||||
print('THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,')
|
||||
print('IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.\n\n')
|
||||
print("HI LO")
|
||||
print("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n")
|
||||
print("THIS IS THE GAME OF HI LO.\n")
|
||||
print("YOU WILL HAVE 6 TRIES TO GUESS THE AMOUNT OF MONEY IN THE")
|
||||
print("HI LO JACKPOT, WHICH IS BETWEEN 1 AND 100 DOLLARS. IF YOU")
|
||||
print("GUESS THE AMOUNT, YOU WIN ALL THE MONEY IN THE JACKPOT!")
|
||||
print("THEN YOU GET ANOTHER CHANCE TO WIN MORE MONEY. HOWEVER,")
|
||||
print("IF YOU DO NOT GUESS THE AMOUNT, THE GAME ENDS.\n\n")
|
||||
|
||||
total_winnings = 0
|
||||
while True:
|
||||
@@ -21,31 +22,32 @@ def play():
|
||||
guessed_correctly = False
|
||||
|
||||
for attempt in range(MAX_ATTEMPTS):
|
||||
print('YOUR GUESS', end=QUESTION_PROMPT)
|
||||
print("YOUR GUESS", end=QUESTION_PROMPT)
|
||||
guess = int(input())
|
||||
|
||||
if guess == secret:
|
||||
print('GOT IT!!!!!!!!!! YOU WIN {} DOLLARS.'.format(secret))
|
||||
print(f"GOT IT!!!!!!!!!! YOU WIN {secret} DOLLARS.")
|
||||
guessed_correctly = True
|
||||
break
|
||||
elif guess > secret:
|
||||
print('YOUR GUESS IS TOO HIGH.')
|
||||
print("YOUR GUESS IS TOO HIGH.")
|
||||
else:
|
||||
print('YOUR GUESS IS TOO LOW.')
|
||||
print("YOUR GUESS IS TOO LOW.")
|
||||
|
||||
if guessed_correctly:
|
||||
total_winnings += secret
|
||||
print('YOUR TOTAL WINNINGS ARE NOW {} DOLLARS.'.format(total_winnings))
|
||||
print(f"YOUR TOTAL WINNINGS ARE NOW {total_winnings} DOLLARS.")
|
||||
else:
|
||||
print('YOU BLEW IT...TOO BAD...THE NUMBER WAS {}'.format(secret))
|
||||
print(f"YOU BLEW IT...TOO BAD...THE NUMBER WAS {secret}")
|
||||
|
||||
print('\n')
|
||||
print('PLAY AGAIN (YES OR NO)', end=QUESTION_PROMPT)
|
||||
print("\n")
|
||||
print("PLAY AGAIN (YES OR NO)", end=QUESTION_PROMPT)
|
||||
answer = input().upper()
|
||||
if answer != 'YES':
|
||||
if answer != "YES":
|
||||
break
|
||||
|
||||
print('\nSO LONG. HOPE YOU ENJOYED YOURSELF!!!')
|
||||
print("\nSO LONG. HOPE YOU ENJOYED YOURSELF!!!")
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
play()
|
||||
|
||||
@@ -1,15 +1,48 @@
|
||||
|
||||
def new_board():
|
||||
# Using a dictionary in python to store the board, since we are not including all numbers within a given range.
|
||||
board = {}
|
||||
for i in [13, 14, 15, 22, 23, 24, 29, 30, 31, 32, 33, 34, 35, 38, 39, 40, 42, 43, 44, 47, 48, 49, 50, 51, 52, 53, 58, 59, 60, 67, 68, 69]:
|
||||
board[i] = '!'
|
||||
board[41] = 'O'
|
||||
for i in [
|
||||
13,
|
||||
14,
|
||||
15,
|
||||
22,
|
||||
23,
|
||||
24,
|
||||
29,
|
||||
30,
|
||||
31,
|
||||
32,
|
||||
33,
|
||||
34,
|
||||
35,
|
||||
38,
|
||||
39,
|
||||
40,
|
||||
42,
|
||||
43,
|
||||
44,
|
||||
47,
|
||||
48,
|
||||
49,
|
||||
50,
|
||||
51,
|
||||
52,
|
||||
53,
|
||||
58,
|
||||
59,
|
||||
60,
|
||||
67,
|
||||
68,
|
||||
69,
|
||||
]:
|
||||
board[i] = "!"
|
||||
board[41] = "O"
|
||||
return board
|
||||
|
||||
|
||||
def print_instructions():
|
||||
print("""
|
||||
print(
|
||||
"""
|
||||
HERE IS THE BOARD:
|
||||
|
||||
! ! !
|
||||
@@ -36,18 +69,45 @@ HERE IS THE BOARD:
|
||||
TO SAVE TYPING TIME, A COMPRESSED VERSION OF THE GAME BOARD
|
||||
WILL BE USED DURING PLAY. REFER TO THE ABOVE ONE FOR PEG
|
||||
NUMBERS. OK, LET'S BEGIN.
|
||||
""")
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def print_board(board):
|
||||
"""Prints the boards using indexes in the passed parameter"""
|
||||
print(" " * 2 + board[13] + board[14] + board[15])
|
||||
print(" " * 2 + board[22] + board[23] + board[24])
|
||||
print(board[29] + board[30] + board[31] + board[32] + board[33] + board[34] + board[35])
|
||||
print(board[38] + board[39] + board[40] + board[41] + board[42] + board[43] + board[44])
|
||||
print(board[47] + board[48] + board[49] + board[50] + board[51] + board[52] + board[53])
|
||||
print(
|
||||
board[29]
|
||||
+ board[30]
|
||||
+ board[31]
|
||||
+ board[32]
|
||||
+ board[33]
|
||||
+ board[34]
|
||||
+ board[35]
|
||||
)
|
||||
print(
|
||||
board[38]
|
||||
+ board[39]
|
||||
+ board[40]
|
||||
+ board[41]
|
||||
+ board[42]
|
||||
+ board[43]
|
||||
+ board[44]
|
||||
)
|
||||
print(
|
||||
board[47]
|
||||
+ board[48]
|
||||
+ board[49]
|
||||
+ board[50]
|
||||
+ board[51]
|
||||
+ board[52]
|
||||
+ board[53]
|
||||
)
|
||||
print(" " * 2 + board[58] + board[59] + board[60])
|
||||
print(" " * 2 + board[67] + board[68] + board[69])
|
||||
|
||||
|
||||
def play_game():
|
||||
# Create new board
|
||||
board = new_board()
|
||||
@@ -61,7 +121,7 @@ def play_game():
|
||||
# Check peg count and print the user's score
|
||||
peg_count = 0
|
||||
for key in board.keys():
|
||||
if board[key] == '!':
|
||||
if board[key] == "!":
|
||||
peg_count += 1
|
||||
|
||||
print("YOU HAD " + str(peg_count) + " PEGS REMAINING")
|
||||
@@ -70,6 +130,7 @@ def play_game():
|
||||
print("BRAVO! YOU MADE A PERFECT SCORE!")
|
||||
print("SAVE THIS PAPER AS A RECORD OF YOUR ACCOMPLISHMENT!")
|
||||
|
||||
|
||||
def move(board):
|
||||
"""Queries the user to move. Returns false if the user puts in an invalid input or move, returns true if the move was successful"""
|
||||
start_input = input("MOVE WHICH PIECE? ")
|
||||
@@ -79,7 +140,7 @@ def move(board):
|
||||
|
||||
start = int(start_input)
|
||||
|
||||
if start not in board or board[start] != '!':
|
||||
if start not in board or board[start] != "!":
|
||||
return False
|
||||
|
||||
end_input = input("TO WHERE? ")
|
||||
@@ -89,15 +150,19 @@ def move(board):
|
||||
|
||||
end = int(end_input)
|
||||
|
||||
if end not in board or board[end] != 'O':
|
||||
if end not in board or board[end] != "O":
|
||||
return False
|
||||
|
||||
difference = abs(start - end)
|
||||
center = (end + start) / 2
|
||||
if (difference == 2 or difference == 18) and board[end] == 'O' and board[center] == '!':
|
||||
board[start] = 'O'
|
||||
board[center] = 'O'
|
||||
board[end] = '!'
|
||||
if (
|
||||
(difference == 2 or difference == 18)
|
||||
and board[end] == "O"
|
||||
and board[center] == "!"
|
||||
):
|
||||
board[start] = "O"
|
||||
board[center] = "O"
|
||||
board[end] = "!"
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
@@ -109,15 +174,20 @@ def main():
|
||||
print_instructions()
|
||||
play_game()
|
||||
|
||||
|
||||
def is_game_finished(board):
|
||||
# Checks all locations and whether or not a move is possible at that location.
|
||||
for pos in board.keys():
|
||||
if board[pos] == '!':
|
||||
if board[pos] == "!":
|
||||
for space in [1, 9]:
|
||||
# Checks if the next location has a peg
|
||||
nextToPeg = ((pos + space) in board) and board[pos + space] == '!'
|
||||
nextToPeg = ((pos + space) in board) and board[pos + space] == "!"
|
||||
# Checks both going forward (+ location) or backwards (-location)
|
||||
hasMovableSpace = (not ((pos - space) in board and board[pos - space] == '!')) or (not ((pos + space * 2) in board and board[pos + space * 2] == '!'))
|
||||
hasMovableSpace = (
|
||||
not ((pos - space) in board and board[pos - space] == "!")
|
||||
) or (
|
||||
not ((pos + space * 2) in board and board[pos + space * 2] == "!")
|
||||
)
|
||||
if nextToPeg and hasMovableSpace:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import random
|
||||
import math
|
||||
import random
|
||||
import time
|
||||
|
||||
|
||||
def basic_print(*zones, **kwargs):
|
||||
"""Simulates the PRINT command from BASIC to some degree.
|
||||
Supports `printing zones` if given multiple arguments."""
|
||||
@@ -10,7 +11,7 @@ def basic_print(*zones, **kwargs):
|
||||
if len(zones) == 1:
|
||||
line = str(zones[0])
|
||||
else:
|
||||
line = "".join(["{:<14}".format(str(zone)) for zone in zones])
|
||||
line = "".join([f"{str(zone):<14}" for zone in zones])
|
||||
identation = kwargs.get("indent", 0)
|
||||
end = kwargs.get("end", "\n")
|
||||
print(" " * identation + line, end=end)
|
||||
@@ -40,7 +41,7 @@ HORSE_NAMES = [
|
||||
"JOLLY",
|
||||
"HORSE",
|
||||
"JELLY DO NOT",
|
||||
"MIDNIGHT"
|
||||
"MIDNIGHT",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import random
|
||||
|
||||
BELLS_ON_SUCCESS = False
|
||||
|
||||
|
||||
def print_with_tab(space_count, msg):
|
||||
if space_count > 0:
|
||||
spaces = " " * space_count
|
||||
@@ -22,6 +23,7 @@ def print_with_tab(space_count, msg):
|
||||
|
||||
print(spaces + msg)
|
||||
|
||||
|
||||
def print_instructions():
|
||||
print("LETTER GUESSING GAME")
|
||||
print()
|
||||
@@ -29,8 +31,9 @@ def print_instructions():
|
||||
print("TRY TO GUESS MY LETTER AND I'LL GIVE YOU CLUES")
|
||||
print("AS TO HOW CLOSE YOU'RE GETTING TO MY LETTER.")
|
||||
|
||||
|
||||
def play_game():
|
||||
target_value = random.randint(ord('A'), ord('Z'))
|
||||
target_value = random.randint(ord("A"), ord("Z"))
|
||||
num_guesses = 0
|
||||
print()
|
||||
print("O.K., I HAVE A LETTER. START GUESSING.")
|
||||
@@ -62,6 +65,7 @@ def play_game():
|
||||
print("TOO LOW. TRY A HIGHER LETTER.")
|
||||
continue
|
||||
|
||||
|
||||
def main():
|
||||
print_with_tab(33, "LETTER")
|
||||
print_with_tab(15, "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
|
||||
@@ -74,5 +78,6 @@ def main():
|
||||
while True:
|
||||
play_game()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -91,5 +91,3 @@ for ($X=$X1-1; $X<=$X2+1; $X++) {
|
||||
$X1=$X1-1; $Y1=$Y1-1; $X2=$X2+1; $Y2=$Y2+1;
|
||||
goto Line210;
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -78,5 +78,3 @@ if ($R<2) {
|
||||
print "NOT BAD, BUT YOU MIGHT SPEND A LITTLE MORE TIME\n";
|
||||
print "READING THE NURSERY GREATS.\n";
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -7,4 +7,3 @@ A tribute to the great American artist, Robert Indiana.
|
||||
His greatest work will be reproduced with a message of
|
||||
your choice up to 60 characters. If you can't think of
|
||||
a message, simply type the word 'LOVE'
|
||||
|
||||
|
||||
@@ -50,5 +50,3 @@ foreach my $Size (@Data) {
|
||||
|
||||
for (my $I=1; $I<10; $I++) { print "\n"; }
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,10 @@
|
||||
|
||||
# Image data. Each top-level element is a row. Each row element
|
||||
# contains alternating character and blank run lengths.
|
||||
DATA = [ [60, ],
|
||||
DATA = [
|
||||
[
|
||||
60,
|
||||
],
|
||||
[1, 12, 26, 9, 12],
|
||||
[3, 8, 24, 17, 8],
|
||||
[4, 6, 23, 21, 6],
|
||||
@@ -41,7 +44,6 @@ DATA = [ [60, ],
|
||||
[4, 6, 15, 5, 2, 23, 5],
|
||||
[1, 29, 5, 17, 8],
|
||||
[1, 29, 9, 9, 12],
|
||||
|
||||
[1, 13, 5, 40, 1],
|
||||
[1, 13, 5, 40, 1],
|
||||
[4, 6, 13, 3, 10, 6, 12, 5, 1],
|
||||
@@ -59,7 +61,10 @@ DATA = [ [60, ],
|
||||
[10, 10, 16, 6, 12, 5, 1],
|
||||
[11, 8, 13, 27, 1],
|
||||
[11, 8, 13, 27, 1],
|
||||
[60, ] ]
|
||||
[
|
||||
60,
|
||||
],
|
||||
]
|
||||
|
||||
|
||||
# Assume that the total length of the first element
|
||||
@@ -81,7 +86,7 @@ if message == "":
|
||||
message = "LOVE"
|
||||
|
||||
# Repeat the message until we get at least one line's worth
|
||||
while(len(message) < ROW_LEN):
|
||||
while len(message) < ROW_LEN:
|
||||
message += message
|
||||
|
||||
# Display image
|
||||
@@ -89,7 +94,7 @@ print("\n" * 9)
|
||||
for row in DATA:
|
||||
print_message = True
|
||||
position = 0
|
||||
line_text = ''
|
||||
line_text = ""
|
||||
for length in row:
|
||||
if print_message:
|
||||
text = message[position : (position + length)]
|
||||
@@ -104,7 +109,6 @@ for row in DATA:
|
||||
print("")
|
||||
|
||||
|
||||
|
||||
######################################################################
|
||||
#
|
||||
# Porting Notes
|
||||
@@ -146,10 +150,3 @@ print("")
|
||||
# ((5, ), (1, 1, 2), (2, 1, 1))
|
||||
#
|
||||
######################################################################
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ Ported by Dave LeCompte
|
||||
import collections
|
||||
import math
|
||||
|
||||
|
||||
PAGE_WIDTH = 64
|
||||
|
||||
COLUMN_WIDTH = 2
|
||||
|
||||
@@ -9,4 +9,3 @@ This folder for chapter #59 contains three different games. Three folders here
|
||||
- lunar
|
||||
|
||||
Conversion to [Rust](https://www.rust-lang.org)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import random, sys
|
||||
|
||||
import random
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
@@ -14,7 +14,7 @@ def main():
|
||||
|
||||
# get user inputs for game conditions
|
||||
print("Mastermind")
|
||||
print('Creative Computing Morristown, New Jersey')
|
||||
print("Creative Computing Morristown, New Jersey")
|
||||
while num_colors > 8:
|
||||
num_colors = int(input("Number of colors (max 8): ")) # C9 in BASIC
|
||||
num_positions = int(input("Number of positions: ")) # P9 in BASIC
|
||||
@@ -22,56 +22,66 @@ def main():
|
||||
possibilities = num_colors**num_positions
|
||||
all_possibilities = [1] * possibilities
|
||||
|
||||
print("Number of possibilities {}".format(possibilities))
|
||||
print('Color\tLetter')
|
||||
print('=====\t======')
|
||||
print(f"Number of possibilities {possibilities}")
|
||||
print("Color\tLetter")
|
||||
print("=====\t======")
|
||||
for element in range(0, num_colors):
|
||||
print("{}\t{}".format(colors[element], colors[element][0]))
|
||||
print(f"{colors[element]}\t{colors[element][0]}")
|
||||
|
||||
current_round = 1
|
||||
|
||||
while current_round <= num_rounds:
|
||||
print('Round number {}'.format(current_round))
|
||||
print(f"Round number {current_round}")
|
||||
num_moves = 1
|
||||
guesses = []
|
||||
turn_over = False
|
||||
print('Guess my combination ...')
|
||||
print("Guess my combination ...")
|
||||
answer = int(possibilities * random.random())
|
||||
numeric_answer = [-1] * num_positions
|
||||
for i in range(0, answer):
|
||||
numeric_answer = get_possibility(numeric_answer)
|
||||
# human_readable_answer = make_human_readable(numeric_answer)
|
||||
while (num_moves < 10 and not turn_over ):
|
||||
print('Move # {} Guess : '.format(num_moves))
|
||||
user_command = input('Guess ')
|
||||
while num_moves < 10 and not turn_over:
|
||||
print(f"Move # {num_moves} Guess : ")
|
||||
user_command = input("Guess ")
|
||||
if user_command == "BOARD":
|
||||
print_board(guesses) # 2000
|
||||
elif user_command == "QUIT": # 2500
|
||||
human_readable_answer = make_human_readable(numeric_answer)
|
||||
print('QUITTER! MY COMBINATION WAS: {}'.format(human_readable_answer))
|
||||
print('GOOD BYE')
|
||||
print(f"QUITTER! MY COMBINATION WAS: {human_readable_answer}")
|
||||
print("GOOD BYE")
|
||||
quit()
|
||||
elif len(user_command) != num_positions: # 410
|
||||
print("BAD NUMBER OF POSITIONS")
|
||||
else:
|
||||
invalid_letters = get_invalid_letters(user_command)
|
||||
if invalid_letters > "":
|
||||
print("INVALID GUESS: {}".format(invalid_letters))
|
||||
print(f"INVALID GUESS: {invalid_letters}")
|
||||
else:
|
||||
guess_results = compare_two_positions(user_command, make_human_readable(numeric_answer))
|
||||
print("Results: {}".format(guess_results))
|
||||
guess_results = compare_two_positions(
|
||||
user_command, make_human_readable(numeric_answer)
|
||||
)
|
||||
print(f"Results: {guess_results}")
|
||||
if guess_results[1] == num_positions: # correct guess
|
||||
turn_over = True
|
||||
print("You guessed it in {} moves!".format(num_moves))
|
||||
print(f"You guessed it in {num_moves} moves!")
|
||||
human_score = human_score + num_moves
|
||||
print_score()
|
||||
else:
|
||||
print("You have {} blacks and {} whites".format(guess_results[1], guess_results[2]))
|
||||
print(
|
||||
"You have {} blacks and {} whites".format(
|
||||
guess_results[1], guess_results[2]
|
||||
)
|
||||
)
|
||||
num_moves = num_moves + 1
|
||||
guesses.append(guess_results)
|
||||
if not turn_over: # RAN OUT OF MOVES
|
||||
print("YOU RAN OUT OF MOVES! THAT'S ALL YOU GET!")
|
||||
print("THE ACTUAL COMBINATION WAS: {}".format(make_human_readable(numeric_answer)))
|
||||
print(
|
||||
"THE ACTUAL COMBINATION WAS: {}".format(
|
||||
make_human_readable(numeric_answer)
|
||||
)
|
||||
)
|
||||
human_score = human_score + num_moves
|
||||
print_score()
|
||||
|
||||
@@ -79,16 +89,18 @@ def main():
|
||||
guesses = []
|
||||
turn_over = False
|
||||
inconsistent_information = False
|
||||
while(not turn_over and not inconsistent_information ):
|
||||
while not turn_over and not inconsistent_information:
|
||||
all_possibilities = [1] * possibilities
|
||||
num_moves = 1
|
||||
inconsistent_information = False
|
||||
print("NOW I GUESS. THINK OF A COMBINATION.")
|
||||
player_ready = input("HIT RETURN WHEN READY: ")
|
||||
while (num_moves < 10 and not turn_over and not inconsistent_information):
|
||||
while num_moves < 10 and not turn_over and not inconsistent_information:
|
||||
found_guess = False
|
||||
computer_guess = int(possibilities * random.random())
|
||||
if all_possibilities[computer_guess] == 1: # random guess is possible, use it
|
||||
if (
|
||||
all_possibilities[computer_guess] == 1
|
||||
): # random guess is possible, use it
|
||||
found_guess = True
|
||||
guess = computer_guess
|
||||
else:
|
||||
@@ -104,8 +116,8 @@ def main():
|
||||
guess = i
|
||||
break
|
||||
if not found_guess: # inconsistent info from user
|
||||
print('YOU HAVE GIVEN ME INCONSISTENT INFORMATION.')
|
||||
print('TRY AGAIN, AND THIS TIME PLEASE BE MORE CAREFUL.')
|
||||
print("YOU HAVE GIVEN ME INCONSISTENT INFORMATION.")
|
||||
print("TRY AGAIN, AND THIS TIME PLEASE BE MORE CAREFUL.")
|
||||
turn_over = True
|
||||
inconsistent_information = True
|
||||
else:
|
||||
@@ -113,12 +125,14 @@ def main():
|
||||
for i in range(0, guess):
|
||||
numeric_guess = get_possibility(numeric_guess)
|
||||
human_readable_guess = make_human_readable(numeric_guess)
|
||||
print('My guess is: {}'.format(human_readable_guess))
|
||||
blacks, whites = input("ENTER BLACKS, WHITES (e.g. 1,2): ").split(",")
|
||||
print(f"My guess is: {human_readable_guess}")
|
||||
blacks, whites = input("ENTER BLACKS, WHITES (e.g. 1,2): ").split(
|
||||
","
|
||||
)
|
||||
blacks = int(blacks)
|
||||
whites = int(whites)
|
||||
if blacks == num_positions: # Correct guess
|
||||
print('I GOT IT IN {} MOVES'.format(num_moves))
|
||||
print(f"I GOT IT IN {num_moves} MOVES")
|
||||
turn_over = True
|
||||
computer_score = computer_score + num_moves
|
||||
print_score()
|
||||
@@ -129,11 +143,17 @@ def main():
|
||||
continue
|
||||
numeric_possibility = [-1] * num_positions
|
||||
for j in range(0, i):
|
||||
numeric_possibility = get_possibility(numeric_possibility)
|
||||
human_readable_possibility = make_human_readable(numeric_possibility) #4000
|
||||
comparison = compare_two_positions(human_readable_possibility, human_readable_guess)
|
||||
numeric_possibility = get_possibility(
|
||||
numeric_possibility
|
||||
)
|
||||
human_readable_possibility = make_human_readable(
|
||||
numeric_possibility
|
||||
) # 4000
|
||||
comparison = compare_two_positions(
|
||||
human_readable_possibility, human_readable_guess
|
||||
)
|
||||
print(comparison)
|
||||
if ((blacks != comparison[1]) or (whites != comparison[2])):
|
||||
if (blacks != comparison[1]) or (whites != comparison[2]):
|
||||
all_possibilities[i] = 0
|
||||
if not turn_over: # COMPUTER DID NOT GUESS
|
||||
print("I USED UP ALL MY MOVES!")
|
||||
@@ -144,6 +164,7 @@ def main():
|
||||
print_score(is_final_score=True)
|
||||
sys.exit()
|
||||
|
||||
|
||||
# 470
|
||||
def get_invalid_letters(user_command):
|
||||
"""Makes sure player input consists of valid colors for selected game configuration."""
|
||||
@@ -154,13 +175,15 @@ def get_invalid_letters(user_command):
|
||||
invalid_letters = invalid_letters + letter
|
||||
return invalid_letters
|
||||
|
||||
|
||||
# 2000
|
||||
def print_board(guesses):
|
||||
"""Prints previous guesses within the round."""
|
||||
print("Board")
|
||||
print("Move\tGuess\tBlack White")
|
||||
for idx, guess in enumerate(guesses):
|
||||
print('{}\t{}\t{} {}'.format(idx+1, guess[0], guess[1], guess[2]))
|
||||
print(f"{idx + 1}\t{guess[0]}\t{guess[1]} {guess[2]}")
|
||||
|
||||
|
||||
# 3500
|
||||
# Easily the place for most optimization, since they generate every possibility
|
||||
@@ -184,6 +207,7 @@ def get_possibility(possibility):
|
||||
possibility = [0] * num_positions
|
||||
return possibility
|
||||
|
||||
|
||||
# 4500
|
||||
def compare_two_positions(guess, answer):
|
||||
"""Returns blacks (correct color and position) and whites (correct color only) for candidate position (guess) versus reference position (answer)."""
|
||||
@@ -194,7 +218,9 @@ def compare_two_positions(guess, answer):
|
||||
for pos in range(0, num_positions):
|
||||
if guess[pos] != answer[pos]:
|
||||
for pos2 in range(0, num_positions):
|
||||
if not(guess[pos] != answer[pos2] or guess[pos2] == answer[pos2]): # correct color but not correct place
|
||||
if not (
|
||||
guess[pos] != answer[pos2] or guess[pos2] == answer[pos2]
|
||||
): # correct color but not correct place
|
||||
whites = whites + 1
|
||||
answer = answer[:pos2] + chr(increment) + answer[pos2 + 1 :]
|
||||
guess = guess[:pos] + chr(increment + 1) + guess[pos + 1 :]
|
||||
@@ -207,6 +233,7 @@ def compare_two_positions(guess, answer):
|
||||
increment = increment + 2
|
||||
return [initial_guess, blacks, whites]
|
||||
|
||||
|
||||
# 5000 + logic from 1160
|
||||
def print_score(is_final_score=False):
|
||||
"""Prints score after each turn ends, including final score at end of game."""
|
||||
@@ -215,16 +242,18 @@ def print_score(is_final_score=False):
|
||||
print("FINAL SCORE:")
|
||||
else:
|
||||
print("SCORE:")
|
||||
print(" COMPUTER {}".format(computer_score))
|
||||
print(" HUMAN {}".format(human_score))
|
||||
print(f" COMPUTER {computer_score}")
|
||||
print(f" HUMAN {human_score}")
|
||||
|
||||
|
||||
# 4000, 5500, 6000 subroutines are all identical
|
||||
def make_human_readable(num):
|
||||
"""Make the numeric representation of a position human readable."""
|
||||
retval = ''
|
||||
retval = ""
|
||||
for i in range(0, len(num)):
|
||||
retval = retval + color_letters[int(num[i])]
|
||||
return retval
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -12,4 +12,3 @@ I was torn between using the correct singular term "die" instead of "dice".
|
||||
In the end I used a (poor?) combination of both.
|
||||
|
||||
krt@krt.com.au 2020-10-12
|
||||
|
||||
|
||||
@@ -126,4 +126,3 @@ begin
|
||||
writeln( 'THE DICE ROLL AGAIN...' );
|
||||
end;
|
||||
end.
|
||||
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
from random import randint
|
||||
|
||||
print("Math Dice")
|
||||
print("https://github.com/coding-horror/basic-computer-games")
|
||||
print()
|
||||
print("""This program generates images of two dice.
|
||||
print(
|
||||
"""This program generates images of two dice.
|
||||
When two dice and an equals sign followed by a question
|
||||
mark have been printed, type your answer, and hit the ENTER
|
||||
key.
|
||||
To conclude the program, type 0.
|
||||
""")
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def print_dice(n):
|
||||
|
||||
def print_0():
|
||||
print("| |")
|
||||
|
||||
def print_2():
|
||||
print("| * * |")
|
||||
|
||||
@@ -41,6 +45,7 @@ def print_dice(n):
|
||||
|
||||
print(" ----- ")
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
while True:
|
||||
@@ -70,10 +75,8 @@ def main():
|
||||
else:
|
||||
print("Correct!")
|
||||
|
||||
|
||||
print("The dice roll again....")
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -12,4 +12,3 @@ is distance above homebase.
|
||||
|
||||
You get 10 tries. After each try, I will tell
|
||||
you how far you are from each wugwump.
|
||||
|
||||
|
||||
@@ -93,4 +93,3 @@ continue {
|
||||
print "\nThat was fun! Let's play again.......\n";
|
||||
print "Four more Mugwumps are now in hiding.\n\n";
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ def calculate_distance(guess, mugwump):
|
||||
d = sqrt(((mugwump[0] - guess[0]) ** 2) + ((mugwump[1] - guess[1]) ** 2))
|
||||
return d
|
||||
|
||||
|
||||
def play_again():
|
||||
print("THAT WAS FUN! LET'S PLAY AGAIN.......")
|
||||
choice = input("Press Enter to play again, any other key then Enter to quit.")
|
||||
@@ -45,6 +46,7 @@ def play_again():
|
||||
else:
|
||||
exit()
|
||||
|
||||
|
||||
def play_round():
|
||||
mugwumps = generate_mugwumps()
|
||||
turns = 1
|
||||
|
||||
@@ -31,5 +31,3 @@ if (uc($D) eq "YES") {
|
||||
print "\n"; print "I REALLY ENJOYED MEETING YOU $A.\n";
|
||||
print "HAVE A NICE DAY!\n";
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -42,5 +42,3 @@ while (1) {
|
||||
print "LET'S TRY ANOTHER.\n";
|
||||
} #goto Line20;
|
||||
exit;
|
||||
|
||||
|
||||
|
||||
@@ -1,38 +1,35 @@
|
||||
import random
|
||||
|
||||
|
||||
# Class of the Game
|
||||
class NIM:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.Piles = {
|
||||
1 : 7,
|
||||
2 : 5,
|
||||
3 : 3,
|
||||
4 : 1
|
||||
}
|
||||
self.Piles = {1: 7, 2: 5, 3: 3, 4: 1}
|
||||
|
||||
def Remove_pegs(self, command):
|
||||
|
||||
try:
|
||||
|
||||
pile, num = command.split(',')
|
||||
pile, num = command.split(",")
|
||||
num = int(num)
|
||||
pile = int(pile)
|
||||
|
||||
except Exception as e:
|
||||
|
||||
if 'not enough values' in str(e):
|
||||
print('\nNot a valid command. Your command should be in the form of "1,3", Try Again\n')
|
||||
if "not enough values" in str(e):
|
||||
print(
|
||||
'\nNot a valid command. Your command should be in the form of "1,3", Try Again\n'
|
||||
)
|
||||
|
||||
else:
|
||||
print('\nError, Try again\n')
|
||||
print("\nError, Try again\n")
|
||||
return None
|
||||
|
||||
if self._command_integrity(num, pile) == True:
|
||||
self.Piles[pile] -= num
|
||||
else:
|
||||
print('\nInvalid value of either Peg or Pile\n')
|
||||
print("\nInvalid value of either Peg or Pile\n")
|
||||
|
||||
def get_AI_move(self):
|
||||
|
||||
@@ -58,20 +55,22 @@ class NIM:
|
||||
def print_pegs(self):
|
||||
|
||||
for pile, peg in self.Piles.items():
|
||||
print('Pile {} : {}'.format(pile, 'O '*peg))
|
||||
print("Pile {} : {}".format(pile, "O " * peg))
|
||||
|
||||
def Help(self):
|
||||
|
||||
print('-'*10)
|
||||
print("-" * 10)
|
||||
print('\nThe Game is player with a number of Piles of Objects("O" == one peg)')
|
||||
print('\nThe Piles are arranged as given below(Tradional NIM)\n')
|
||||
print("\nThe Piles are arranged as given below(Tradional NIM)\n")
|
||||
self.print_pegs()
|
||||
print('\nAny Number of of Objects are removed one pile by "YOU" and the machine alternatively')
|
||||
print('\nOn your turn, you may take all the objects that remain in any pile')
|
||||
print('but you must take ATLEAST one object')
|
||||
print('\nAnd you may take objects from only one pile on a single turn.')
|
||||
print('\nThe winner is defined as the one that picks the last remaning object')
|
||||
print('-'*10)
|
||||
print(
|
||||
'\nAny Number of of Objects are removed one pile by "YOU" and the machine alternatively'
|
||||
)
|
||||
print("\nOn your turn, you may take all the objects that remain in any pile")
|
||||
print("but you must take ATLEAST one object")
|
||||
print("\nAnd you may take objects from only one pile on a single turn.")
|
||||
print("\nThe winner is defined as the one that picks the last remaning object")
|
||||
print("-" * 10)
|
||||
|
||||
def Checkforwin(self):
|
||||
|
||||
@@ -85,42 +84,47 @@ class NIM:
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
# main program
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Game initialization
|
||||
game = NIM()
|
||||
|
||||
print('Hello, This is a game of NIM')
|
||||
help = input('Do You Need Instruction (YES or NO): ')
|
||||
print("Hello, This is a game of NIM")
|
||||
help = input("Do You Need Instruction (YES or NO): ")
|
||||
|
||||
if help == 'yes' or help == 'YES' or help == 'Yes':
|
||||
if help == "yes" or help == "YES" or help == "Yes":
|
||||
|
||||
# Printing Game Instruction
|
||||
game.Help()
|
||||
|
||||
# Start game loop
|
||||
input('\nPress Enter to start the Game:\n')
|
||||
input("\nPress Enter to start the Game:\n")
|
||||
End = False
|
||||
while True:
|
||||
|
||||
game.print_pegs()
|
||||
|
||||
# Players Move
|
||||
command = input('\nYOUR MOVE - Number of PILE, Number of Object? ')
|
||||
command = input("\nYOUR MOVE - Number of PILE, Number of Object? ")
|
||||
game.Remove_pegs(command)
|
||||
End = game.Checkforwin()
|
||||
if End == True:
|
||||
print('\nPlayer Wins the Game, Congratulations!!')
|
||||
input('\nPress any key to exit')
|
||||
print("\nPlayer Wins the Game, Congratulations!!")
|
||||
input("\nPress any key to exit")
|
||||
break
|
||||
|
||||
# Computers Move
|
||||
command = game.get_AI_move()
|
||||
print('\nA.I MOVE - A.I Removed {} pegs from Pile {}'.format(command[1],command[0]))
|
||||
game.Remove_pegs(str(command[0]) +',' + str(command[1]))
|
||||
print(
|
||||
"\nA.I MOVE - A.I Removed {} pegs from Pile {}".format(
|
||||
command[1], command[0]
|
||||
)
|
||||
)
|
||||
game.Remove_pegs(str(command[0]) + "," + str(command[1]))
|
||||
End = game.Checkforwin()
|
||||
if End == True:
|
||||
print('\nComputer Wins the Game, Better Luck Next Time\n')
|
||||
input('Press any key to exit')
|
||||
print("\nComputer Wins the Game, Better Luck Next Time\n")
|
||||
input("Press any key to exit")
|
||||
break
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user