Merge pull request #626 from MartinThoma/py-linting-3

Python: Fix Flake8 issue E712 + PEP8 variable naming
This commit is contained in:
Jeff Atwood
2022-03-11 17:36:32 -06:00
committed by GitHub
8 changed files with 172 additions and 181 deletions

View File

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

View File

@@ -115,38 +115,38 @@ def update_game(data, action):
if "pictures" == action: if "pictures" == action:
data["state"] = "pictures" data["state"] = "pictures"
else: else:
partAdded = False part_added = False
while partAdded == False: while not part_added:
for player, parts in data["players"].items(): for player, parts in data["players"].items():
# rolls the dice for a part # rolls the dice for a part
newPartIdx = randint(1, 6) - 1 new_part_idx = randint(1, 6) - 1
# gets information about the picked part # gets information about the picked part
partType = data["partTypes"][newPartIdx] part_type = data["partTypes"][new_part_idx]
# gets the number of existing parts of that type the player has # gets the number of existing parts of that type the player has
partCount = parts[newPartIdx] part_count = parts[new_part_idx]
logs.append(("rolled", newPartIdx, player)) logs.append(("rolled", new_part_idx, player))
# a new part can only be added if the player has the parts # 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 # the new part depends on and doesn't have enough of the part already
overMaxParts = partType.count < partCount + 1 overMaxParts = part_type.count < part_count + 1
missingPartDep = ( missingPartDep = (
partType.depends != None and parts[partType.depends] == 0 part_type.depends != None and parts[part_type.depends] == 0
) )
if not overMaxParts and not missingPartDep: if not overMaxParts and not missingPartDep:
# adds a new part # adds a new part
partCount += 1 part_count += 1
logs.append(("added", newPartIdx, player)) logs.append(("added", new_part_idx, player))
partAdded = True part_added = True
elif missingPartDep: elif missingPartDep:
logs.append(("missingDep", newPartIdx, player, partType.depends)) logs.append(("missingDep", new_part_idx, player, part_type.depends))
if overMaxParts: if overMaxParts:
logs.append(("overMax", newPartIdx, player, partCount)) logs.append(("overMax", new_part_idx, player, part_count))
data["players"][player][newPartIdx] = partCount data["players"][player][new_part_idx] = part_count
data["logs"] = logs data["logs"] = logs
# checks if any players have finished their bug # checks if any players have finished their bug
@@ -162,10 +162,10 @@ def get_finished(data):
""" """
Gets players who have finished their bugs Gets players who have finished their bugs
""" """
totalParts = sum(partType.count for partType in data["partTypes"]) total_parts = sum(part_type.count for part_type in data["partTypes"])
finished = [] finished = []
for player, parts in data["players"].items(): for player, parts in data["players"].items():
if sum(parts) == totalParts: if sum(parts) == total_parts:
finished.append(player) finished.append(player)
return finished return finished
@@ -175,34 +175,34 @@ def print_game(data):
Displays the results of the game turn Displays the results of the game turn
""" """
for log in data["logs"]: for log in data["logs"]:
code, partIdx, player, *logdata = log code, part_idx, player, *logdata = log
partType = data["partTypes"][partIdx] part_type = data["partTypes"][part_idx]
if "rolled" == code: if "rolled" == code:
print() print()
print(f"{player} ROLLED A {partIdx + 1}") print(f"{player} ROLLED A {part_idx + 1}")
print(f"{partIdx + 1}={partType.name}") print(f"{part_idx + 1}={part_type.name}")
elif "added" == code: elif "added" == code:
if "YOU" == player: if "YOU" == player:
if partType.name in ["FEELERS", "LEGS", "TAIL"]: if part_type.name in ["FEELERS", "LEGS", "TAIL"]:
print(f"I NOW GIVE YOU A {partType.name.replace('s', '')}.") print(f"I NOW GIVE YOU A {part_type.name.replace('s', '')}.")
else: else:
print(f"YOU NOW HAVE A {partType.name}.") print(f"YOU NOW HAVE A {part_type.name}.")
elif "I" == player: elif "I" == player:
if partType.name in ["BODY", "NECK", "TAIL"]: if part_type.name in ["BODY", "NECK", "TAIL"]:
print(f"I NOW HAVE A {partType.name}.") print(f"I NOW HAVE A {part_type.name}.")
elif partType.name == "FEELERS": elif part_type.name == "FEELERS":
print("I GET A FEELER.") print("I GET A FEELER.")
if partType.count > 2: if part_type.count > 2:
print( print(
f"{player} NOW HAVE {data['players'][player][partIdx]} {partType.name}" f"{player} NOW HAVE {data['players'][player][part_idx]} {part_type.name}"
) )
elif "missingDep" == code: elif "missingDep" == code:
(depIdx,) = logdata (dep_idx,) = logdata
dep = data["partTypes"][depIdx] dep = data["partTypes"][dep_idx]
print( print(
f"YOU DO NOT HAVE A {dep.name}" f"YOU DO NOT HAVE A {dep.name}"
if "YOU" == player if "YOU" == player
@@ -210,12 +210,12 @@ def print_game(data):
) )
elif "overMax" == code: elif "overMax" == code:
(partCount,) = logdata (part_count,) = logdata
if partCount > 1: if part_count > 1:
num = "TWO" if 2 == partCount else partCount num = "TWO" if 2 == part_count else part_count
maxMsg = f"HAVE {num} {partType.name}S ALREADY" maxMsg = f"HAVE {num} {part_type.name}S ALREADY"
else: else:
maxMsg = f"ALREADY HAVE A {partType.name}" maxMsg = f"ALREADY HAVE A {part_type.name}"
print(f"{player} {maxMsg}") 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"
@@ -225,7 +225,7 @@ def print_pictures(data):
""" """
Displays what the bugs look like for each player Displays what the bugs look like for each player
""" """
typeIxs = {partType.name: idx for idx, partType in enumerate(data["partTypes"])} typeIxs = {part_type.name: idx for idx, part_type in enumerate(data["partTypes"])}
PIC_WIDTH = 22 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(f"*****{'YOUR' if 'YOU' == player else 'MY'} BUG*****")
@@ -317,7 +317,7 @@ if __name__ == "__main__":
} }
# body part types used by the game to work out whether a player's body part can be added # body part types used by the game to work out whether a player's body part can be added
partTypes = ( part_types = (
Bodypart(name="BODY", count=1, depends=None), Bodypart(name="BODY", count=1, depends=None),
Bodypart(name="NECK", count=1, depends=0), Bodypart(name="NECK", count=1, depends=0),
Bodypart(name="HEAD", count=1, depends=1), Bodypart(name="HEAD", count=1, depends=1),
@@ -330,8 +330,8 @@ if __name__ == "__main__":
data = { data = {
"state": "start", "state": "start",
"partNo": None, "partNo": None,
"players": {"YOU": [0] * len(partTypes), "I": [0] * len(partTypes)}, "players": {"YOU": [0] * len(part_types), "I": [0] * len(part_types)},
"partTypes": partTypes, "partTypes": part_types,
"finished": [], "finished": [],
"logs": [], "logs": [],
} }

View File

@@ -214,7 +214,7 @@ while True:
death = True death = True
break break
if death == True: if death:
break break
# 1310 # 1310
print_n_newlines(3) print_n_newlines(3)

View File

@@ -1,14 +1,14 @@
MAX_UNITS = 72000 MAX_UNITS = 72000
planeCrashWin = False plane_crash_win = False
usrArmy = 0 usr_army = 0
usrNavy = 0 usr_navy = 0
usrAir = 0 usr_air = 0
cpuArmy = 30000 cpu_army = 30000
cpuNavy = 20000 cpu_navy = 20000
cpuAir = 22000 cpu_air = 22000
def showIntro(): def show_intro():
global MAX_UNITS global MAX_UNITS
print(" " * 32 + "COMBAT") print(" " * 32 + "COMBAT")
@@ -18,172 +18,172 @@ def showIntro():
print("WE HAVE " + str(MAX_UNITS) + " SOLDIERS APIECE.") print("WE HAVE " + str(MAX_UNITS) + " SOLDIERS APIECE.")
def getForces(): def get_forces():
global usrArmy, usrNavy, usrAir global usr_army, usr_navy, usr_air
while True: while True:
print("DISTRIBUTE YOUR FORCES.") print("DISTRIBUTE YOUR FORCES.")
print(" ME YOU") print(" ME YOU")
print("ARMY " + str(cpuArmy) + " ? ", end="") print("ARMY " + str(cpu_army) + " ? ", end="")
usrArmy = int(input()) usr_army = int(input())
print("NAVY " + str(cpuNavy) + " ? ", end="") print("NAVY " + str(cpu_navy) + " ? ", end="")
usrNavy = int(input()) usr_navy = int(input())
print("A. F. " + str(cpuAir) + " ? ", end="") print("A. F. " + str(cpu_air) + " ? ", end="")
usrAir = int(input()) usr_air = int(input())
if not ((usrArmy + usrNavy + usrAir) > MAX_UNITS): if not ((usr_army + usr_navy + usr_air) > MAX_UNITS):
break break
def attackFirst(): def attack_first():
global usrArmy, usrNavy, usrAir global usr_army, usr_navy, usr_air
global cpuArmy, cpuNavy, cpuAir global cpu_army, cpu_navy, cpu_air
numUnits = 0 num_units = 0
unitType = 0 unit_type = 0
while True: while True:
print("YOU ATTACK FIRST. TYPE (1) FOR ARMY; (2) FOR NAVY;") print("YOU ATTACK FIRST. TYPE (1) FOR ARMY; (2) FOR NAVY;")
print("AND (3) FOR AIR FORCE.") print("AND (3) FOR AIR FORCE.")
print("?", end=" ") print("?", end=" ")
unitType = int(input()) unit_type = int(input())
if not (unitType < 1 or unitType > 3): if not (unit_type < 1 or unit_type > 3):
break break
while True: while True:
print("HOW MANY MEN") print("HOW MANY MEN")
print("?", end=" ") print("?", end=" ")
numUnits = int(input()) num_units = int(input())
if not ( if not (
(numUnits < 0) (num_units < 0)
or ((unitType == 1) and (numUnits > usrArmy)) or ((unit_type == 1) and (num_units > usr_army))
or ((unitType == 2) and (numUnits > usrNavy)) or ((unit_type == 2) and (num_units > usr_navy))
or ((unitType == 3) and (numUnits > usrAir)) or ((unit_type == 3) and (num_units > usr_air))
): ):
break break
if unitType == 1: if unit_type == 1:
if numUnits < (usrArmy / 3): if num_units < (usr_army / 3):
print("YOU LOST " + str(numUnits) + " MEN FROM YOUR ARMY.") print("YOU LOST " + str(num_units) + " MEN FROM YOUR ARMY.")
usrArmy = usrArmy - numUnits usr_army = usr_army - num_units
elif numUnits < (2 * usrArmy / 3): elif num_units < (2 * usr_army / 3):
print( print(
"YOU LOST " "YOU LOST "
+ str(int(numUnits / 3)) + str(int(num_units / 3))
+ " MEN, BUT I LOST " + " MEN, BUT I LOST "
+ str(int(2 * cpuArmy / 3)) + str(int(2 * cpu_army / 3))
) )
usrArmy = int(usrArmy - (numUnits / 3)) usr_army = int(usr_army - (num_units / 3))
cpuArmy = 0 cpu_army = 0
else: else:
print("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO") print("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO")
print("OF YOUR AIR FORCE BASES AND 3 ARMY BASES.") print("OF YOUR AIR FORCE BASES AND 3 ARMY BASES.")
usrArmy = int(usrArmy / 3) usr_army = int(usr_army / 3)
usrAir = int(usrAir / 3) usr_air = int(usr_air / 3)
cpuNavy = int(2 * cpuNavy / 3) cpu_navy = int(2 * cpu_navy / 3)
elif unitType == 2: elif unit_type == 2:
if numUnits < cpuNavy / 3: if num_units < cpu_navy / 3:
print("YOUR ATTACK WAS STOPPED!") print("YOUR ATTACK WAS STOPPED!")
usrNavy = usrNavy - numUnits usr_navy = usr_navy - num_units
elif numUnits < 2 * cpuNavy / 3: elif num_units < 2 * cpu_navy / 3:
print("YOU DESTROYED " + str(int(2 * cpuNavy / 3)) + " OF MY ARMY.") print("YOU DESTROYED " + str(int(2 * cpu_navy / 3)) + " OF MY ARMY.")
cpuNavy = int(cpuNavy / 3) cpu_navy = int(cpu_navy / 3)
else: else:
print("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO") print("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO")
print("OF YOUR AIR FORCE BASES AND 3 ARMY BASES.") print("OF YOUR AIR FORCE BASES AND 3 ARMY BASES.")
usrArmy = int(usrArmy / 3) usr_army = int(usr_army / 3)
usrAir = int(usrAir / 3) usr_air = int(usr_air / 3)
cpuNavy = int(2 * cpuNavy / 3) cpu_navy = int(2 * cpu_navy / 3)
elif unitType == 3: elif unit_type == 3:
if numUnits < usrAir / 3: if num_units < usr_air / 3:
print("YOUR ATTACK WAS WIPED OUT.") print("YOUR ATTACK WAS WIPED OUT.")
usrAir = usrAir - numUnits usr_air = usr_air - num_units
elif numUnits < 2 * usrAir / 3: elif num_units < 2 * usr_air / 3:
print("WE HAD A DOGFIGHT. YOU WON - AND FINISHED YOUR MISSION.") print("WE HAD A DOGFIGHT. YOU WON - AND FINISHED YOUR MISSION.")
cpuArmy = int(2 * cpuArmy / 3) cpu_army = int(2 * cpu_army / 3)
cpuNavy = int(cpuNavy / 3) cpu_navy = int(cpu_navy / 3)
cpuAir = int(cpuAir / 3) cpu_air = int(cpu_air / 3)
else: else:
print("YOU WIPED OUT ONE OF MY ARMY PATROLS, BUT I DESTROYED") print("YOU WIPED OUT ONE OF MY ARMY PATROLS, BUT I DESTROYED")
print("TWO NAVY BASES AND BOMBED THREE ARMY BASES.") print("TWO NAVY BASES AND BOMBED THREE ARMY BASES.")
usrArmy = int(usrArmy / 4) usr_army = int(usr_army / 4)
usrNavy = int(usrNavy / 3) usr_navy = int(usr_navy / 3)
cpuArmy = int(2 * cpuArmy / 3) cpu_army = int(2 * cpu_army / 3)
def attackSecond(): def attack_second():
global usrArmy, usrNavy, usrAir, cpuArmy, cpuNavy, cpuAir global usr_army, usr_navy, usr_air, cpu_army, cpu_navy, cpu_air
global planeCrashWin global plane_crash_win
numUnits = 0 num_units = 0
unitType = 0 unit_type = 0
print("") print("")
print(" YOU ME") print(" YOU ME")
print("ARMY ", end="") print("ARMY ", end="")
print("%-14s%s\n" % (usrArmy, cpuArmy), end="") print("%-14s%s\n" % (usr_army, cpu_army), end="")
print("NAVY ", end="") print("NAVY ", end="")
print("%-14s%s\n" % (usrNavy, cpuNavy), end="") print("%-14s%s\n" % (usr_navy, cpu_navy), end="")
print("A. F. ", end="") print("A. F. ", end="")
print("%-14s%s\n" % (usrAir, cpuAir), end="") print("%-14s%s\n" % (usr_air, cpu_air), end="")
while True: while True:
print("WHAT IS YOUR NEXT MOVE?") print("WHAT IS YOUR NEXT MOVE?")
print("ARMY=1 NAVY=2 AIR FORCE=3") print("ARMY=1 NAVY=2 AIR FORCE=3")
print("? ", end="") print("? ", end="")
unitType = int(input()) unit_type = int(input())
if not ((unitType < 1) or (unitType > 3)): if not ((unit_type < 1) or (unit_type > 3)):
break break
while True: while True:
print("HOW MANY MEN") print("HOW MANY MEN")
print("? ", end="") print("? ", end="")
numUnits = int(input()) num_units = int(input())
if not ( if not (
(numUnits < 0) (num_units < 0)
or ((unitType == 1) and (numUnits > usrArmy)) or ((unit_type == 1) and (num_units > usr_army))
or ((unitType == 2) and (numUnits > usrNavy)) or ((unit_type == 2) and (num_units > usr_navy))
or ((unitType == 3) and (numUnits > usrAir)) or ((unit_type == 3) and (num_units > usr_air))
): ):
break break
if unitType == 1: if unit_type == 1:
if numUnits < (cpuArmy / 2): if num_units < (cpu_army / 2):
print("I WIPED OUT YOUR ATTACK!") print("I WIPED OUT YOUR ATTACK!")
usrArmy = usrArmy - numUnits usr_army = usr_army - num_units
else: else:
print("YOU DESTROYED MY ARMY!") print("YOU DESTROYED MY ARMY!")
cpuArmy = 0 cpu_army = 0
elif unitType == 2: elif unit_type == 2:
if numUnits < (cpuNavy / 2): if num_units < (cpu_navy / 2):
print("I SUNK TWO OF YOUR BATTLESHIPS, AND MY AIR FORCE") print("I SUNK TWO OF YOUR BATTLESHIPS, AND MY AIR FORCE")
print("WIPED OUT YOUR UNGUARDED CAPITOL.") print("WIPED OUT YOUR UNGUARDED CAPITOL.")
usrArmy = int(usrArmy / 4) usr_army = int(usr_army / 4)
usrNavy = int(usrNavy / 2) usr_navy = int(usr_navy / 2)
else: else:
print("YOUR NAVY SHOT DOWN THREE OF MY XIII PLANES,") print("YOUR NAVY SHOT DOWN THREE OF MY XIII PLANES,")
print("AND SUNK THREE BATTLESHIPS.") print("AND SUNK THREE BATTLESHIPS.")
cpuAir = int(2 * cpuAir / 3) cpu_air = int(2 * cpu_air / 3)
cpuNavy = int(cpuNavy / 2) cpu_navy = int(cpu_navy / 2)
elif unitType == 3: elif unit_type == 3:
if numUnits > (cpuAir / 2): if num_units > (cpu_air / 2):
print("MY NAVY AND AIR FORCE IN A COMBINED ATTACK LEFT") print("MY NAVY AND AIR FORCE IN A COMBINED ATTACK LEFT")
print("YOUR COUNTRY IN SHAMBLES.") print("YOUR COUNTRY IN SHAMBLES.")
usrArmy = int(usrArmy / 3) usr_army = int(usr_army / 3)
usrNavy = int(usrNavy / 3) usr_navy = int(usr_navy / 3)
usrAir = int(usrAir / 3) usr_air = int(usr_air / 3)
else: else:
print("ONE OF YOUR PLANES CRASHED INTO MY HOUSE. I AM DEAD.") print("ONE OF YOUR PLANES CRASHED INTO MY HOUSE. I AM DEAD.")
print("MY COUNTRY FELL APART.") print("MY COUNTRY FELL APART.")
planeCrashWin = True plane_crash_win = True
if planeCrashWin == False: if not plane_crash_win:
print("") print("")
print("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,") print("FROM THE RESULTS OF BOTH OF YOUR ATTACKS,")
if (planeCrashWin == True) or ( if plane_crash_win or (
(usrArmy + usrNavy + usrAir) > (int(3 / 2 * (cpuArmy + cpuNavy + cpuAir))) (usr_army + usr_navy + usr_air) > (int(3 / 2 * (cpu_army + cpu_navy + cpu_air)))
): ):
print("YOU WON, OH! SHUCKS!!!!") print("YOU WON, OH! SHUCKS!!!!")
elif (usrArmy + usrNavy + usrAir) < int(2 / 3 * (cpuArmy + cpuNavy + cpuAir)): elif (usr_army + usr_navy + usr_air) < int(2 / 3 * (cpu_army + cpu_navy + cpu_air)):
print("YOU LOST-I CONQUERED YOUR COUNTRY. IT SERVES YOU") print("YOU LOST-I CONQUERED YOUR COUNTRY. IT SERVES YOU")
print("RIGHT FOR PLAYING THIS STUPID GAME!!!") print("RIGHT FOR PLAYING THIS STUPID GAME!!!")
else: else:
@@ -192,10 +192,10 @@ def attackSecond():
def main(): def main():
showIntro() show_intro()
getForces() get_forces()
attackFirst() attack_first()
attackSecond() attack_second()
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -76,7 +76,7 @@ while True:
continue continue
if I == -1: if I == -1:
break break
elif check_move(I, J, N) == False: elif not check_move(I, J, N):
print("ILLEGAL MOVE. TRY AGAIN...") print("ILLEGAL MOVE. TRY AGAIN...")
else: else:
if A[I - 1][J - 1] != 0: if A[I - 1][J - 1] != 0:
@@ -91,13 +91,13 @@ while True:
continue continue
X = I + F X = I + F
Y = J + F Y = J + F
if check_move(X, Y, N) == False: if not check_move(X, Y, N):
continue continue
if A[X - 1][Y - 1] == 1: if A[X - 1][Y - 1] == 1:
SkipEFLoop = True SkipEFLoop = True
X = I - E X = I - E
Y = J - F Y = J - F
if check_move(X, Y, N) == False: # 750 if not check_move(X, Y, N): # 750
while True: # 610 while True: # 610
X = random.randint(1, N) X = random.randint(1, N)
Y = random.randint(1, N) Y = random.randint(1, N)

View File

@@ -4,11 +4,9 @@ import random
# Class of the Game # Class of the Game
class NIM: class NIM:
def __init__(self): 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):
def Remove_pegs(self, command):
try: try:
pile, num = command.split(",") pile, num = command.split(",")
@@ -26,39 +24,35 @@ class NIM:
print("\nError, Try again\n") print("\nError, Try again\n")
return None return None
if self._command_integrity(num, pile) == True: if self._command_integrity(num, pile):
self.Piles[pile] -= num self.piles[pile] -= num
else: else:
print("\nInvalid value of either Peg or Pile\n") print("\nInvalid value of either Peg or Pile\n")
def get_AI_move(self): def get_ai_move(self):
possible_pile = [] possible_pile = []
for k, v in self.Piles.items(): for k, v in self.piles.items():
if v != 0: if v != 0:
possible_pile.append(k) possible_pile.append(k)
pile = random.choice(possible_pile) pile = random.choice(possible_pile)
num = random.randint(1, self.Piles[pile]) num = random.randint(1, self.piles[pile])
return pile, num return pile, num
def _command_integrity(self, num, pile): def _command_integrity(self, num, pile):
if pile <= 4 and pile >= 1: if pile <= 4 and pile >= 1:
if num <= self.Piles[pile]: if num <= self.piles[pile]:
return True return True
return False return False
def print_pegs(self): def print_pegs(self):
for pile, peg in self.piles.items():
for pile, peg in self.Piles.items():
print("Pile {} : {}".format(pile, "O " * peg)) print("Pile {} : {}".format(pile, "O " * peg))
def Help(self): def help(self):
print("-" * 10) print("-" * 10)
print('\nThe Game is player with a number of Piles of Objects("O" == one peg)') 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")
@@ -72,10 +66,9 @@ class NIM:
print("\nThe winner is defined as the one that picks the last remaning object") print("\nThe winner is defined as the one that picks the last remaning object")
print("-" * 10) print("-" * 10)
def Checkforwin(self): def check_for_win(self):
sum = 0 sum = 0
for k, v in self.Piles.items(): for k, v in self.piles.items():
sum += v sum += v
if sum == 0: if sum == 0:
@@ -85,46 +78,45 @@ class NIM:
return False return False
# main program def main():
if __name__ == "__main__":
# Game initialization # Game initialization
game = NIM() game = NIM()
print("Hello, This is a game of NIM") print("Hello, This is a game of NIM")
help = input("Do You Need Instruction (YES or NO): ") help = input("Do You Need Instruction (YES or NO): ")
if help == "yes" or help == "YES" or help == "Yes": if help.lower() == "yes":
game.help()
# Printing Game Instruction
game.Help()
# Start game loop # Start game loop
input("\nPress Enter to start the Game:\n") input("\nPress Enter to start the Game:\n")
End = False end = False
while True: while True:
game.print_pegs() game.print_pegs()
# Players Move # 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) game.remove_pegs(command)
End = game.Checkforwin() end = game.check_for_win()
if End == True: if end:
print("\nPlayer Wins the Game, Congratulations!!") print("\nPlayer Wins the Game, Congratulations!!")
input("\nPress any key to exit") input("\nPress any key to exit")
break break
# Computers Move # Computers Move
command = game.get_AI_move() command = game.get_ai_move()
print( print(
"\nA.I MOVE - A.I Removed {} pegs from Pile {}".format( "\nA.I MOVE - A.I Removed {} pegs from Pile {}".format(
command[1], command[0] command[1], command[0]
) )
) )
game.Remove_pegs(str(command[0]) + "," + str(command[1])) game.remove_pegs(str(command[0]) + "," + str(command[1]))
End = game.Checkforwin() end = game.check_for_win()
if End == True: if end:
print("\nComputer Wins the Game, Better Luck Next Time\n") print("\nComputer Wins the Game, Better Luck Next Time\n")
input("Press any key to exit") input("Press any key to exit")
break break
if __name__ == "__main__":
main()

View File

@@ -81,7 +81,7 @@ class Stock_Market:
print("\nWHAT IS YOUR TRANSACTION IN") print("\nWHAT IS YOUR TRANSACTION IN")
flag = False flag = False
while flag != True: while not flag:
new_holdings = [] new_holdings = []
for stock in self.data.keys(): for stock in self.data.keys():
try: try:

View File

@@ -265,8 +265,7 @@ def test_weekday_calc(year, month, day):
basic_weekday = calculate_day_of_week(year, month, day) # Sunday = 1, Saturday = 7 basic_weekday = calculate_day_of_week(year, month, day) # Sunday = 1, Saturday = 7
test = ((python_weekday + 2) % 7) == (basic_weekday % 7) if ((python_weekday + 2) % 7) != (basic_weekday % 7):
if test == False:
print(f"testing yr {year} month {month} day {day}") print(f"testing yr {year} month {month} day {day}")
print(f"python says {python_weekday}") print(f"python says {python_weekday}")
print(f"BASIC says {basic_weekday}") print(f"BASIC says {basic_weekday}")