From 3b2739b8a2565a3b6930fbf97a0aba80c52f1e78 Mon Sep 17 00:00:00 2001 From: Martin Thoma Date: Fri, 18 Mar 2022 22:27:31 +0100 Subject: [PATCH] Clean Code: Apply flake8-simplify to Python Also flake8-comprehensions which was added to the CI For flake8-simplify, there are a few false-positives, e.g. https://github.com/MartinThoma/flake8-simplify/issues/115 --- .github/workflows/check-python.yml | 2 +- 00_Utilities/markdown_todo.py | 15 ++-- 00_Utilities/python/ci-requirements.in | 1 + 00_Utilities/python/ci-requirements.txt | 3 + 04_Awari/python/awari.py | 16 ++--- 05_Bagels/python/bagels.py | 2 +- 10_Blackjack/python/blackjack.py | 6 +- 12_Bombs_Away/python/bombs_away.py | 2 +- 16_Bug/python/Bug.py | 2 +- 16_Bug/python/bug-overengineered.py | 24 +++---- 17_Bullfight/python/Bullfight.py | 4 +- 23_Checkers/python/checkers.py | 10 +-- 26_Chomp/python/chomp.py | 4 +- 28_Combat/python/combat.py | 2 +- 30_Cube/python/cube.py | 82 ++++++++++++---------- 34_Digits/python/Digits.py | 5 +- 39_Golf/python/golf.py | 28 ++++---- 46_Hexapawn/python/hexapawn.py | 18 ++--- 50_Horserace/python/horserace.py | 6 +- 65_Nim/python/Traditional_NIM.py | 12 +--- 75_Roulette/python/roulette.py | 38 +++++----- 77_Salvo/python/salvo.py | 24 +++---- 84_Super_Star_Trek/python/superstartrek.py | 15 ++-- 86_Target/python/target.py | 2 +- 88_3-D_Tic-Tac-Toe/python/qubit.py | 5 +- 89_Tic-Tac-Toe/python/tictactoe2.py | 46 ++++++------ 90_Tower/python/tower.py | 3 +- 94_War/python/war.py | 5 +- 28 files changed, 168 insertions(+), 214 deletions(-) diff --git a/.github/workflows/check-python.yml b/.github/workflows/check-python.yml index 21fa84da..cf8e42ce 100644 --- a/.github/workflows/check-python.yml +++ b/.github/workflows/check-python.yml @@ -28,4 +28,4 @@ jobs: mypy . --exclude 79_Slalom --exclude 27_Civil_War --exclude 38_Fur_Trader --exclude 81_Splat --exclude 09_Battle --exclude 40_Gomoko --exclude 36_Flip_Flop --exclude 43_Hammurabi --exclude 04_Awari --exclude 78_Sine_Wave --exclude 77_Salvo --exclude 34_Digits --exclude 17_Bullfight --exclude 16_Bug - name: Test with flake8 run: | - flake8 . --ignore E501,W503,E203,E731,B011 + flake8 . --ignore E501,W503,E203,E731,B011,SIM119,SIM106 diff --git a/00_Utilities/markdown_todo.py b/00_Utilities/markdown_todo.py index 52e3112a..bdcedb15 100644 --- a/00_Utilities/markdown_todo.py +++ b/00_Utilities/markdown_todo.py @@ -34,7 +34,7 @@ prev_game = "" for dirName, subdirList, fileList in os.walk(rootDir): split_dir = dirName.split(os.path.sep) - if len(split_dir) == 2 and not split_dir[1] in [".git", "00_Utilities"]: + if len(split_dir) == 2 and split_dir[1] not in [".git", "00_Utilities"]: if prev_game == "": prev_game = split_dir[1] checklist[0] = split_dir[1] @@ -55,13 +55,12 @@ for dirName, subdirList, fileList in os.walk(rootDir): ] prev_game = split_dir[1] - elif len(split_dir) == 3 and split_dir[1] != ".git": - if split_dir[2] in lang_pos.keys(): - if len(fileList) > 1 or len(subdirList) > 0: - # there is more files than the readme - checklist[lang_pos[split_dir[2]]] = "✅" - else: - checklist[lang_pos[split_dir[2]]] = "⬜️" + elif len(split_dir) == 3 and split_dir[1] != ".git" and split_dir[2] in lang_pos: + if len(fileList) > 1 or len(subdirList) > 0: + # there is more files than the readme + checklist[lang_pos[split_dir[2]]] = "✅" + else: + checklist[lang_pos[split_dir[2]]] = "⬜️" sorted_strings = list( diff --git a/00_Utilities/python/ci-requirements.in b/00_Utilities/python/ci-requirements.in index 7efd7199..ae5fa2e0 100644 --- a/00_Utilities/python/ci-requirements.in +++ b/00_Utilities/python/ci-requirements.in @@ -1,4 +1,5 @@ pytest flake8 flake8-bugbear +flake8-comprehensions mypy diff --git a/00_Utilities/python/ci-requirements.txt b/00_Utilities/python/ci-requirements.txt index 56923d59..cffeacb3 100644 --- a/00_Utilities/python/ci-requirements.txt +++ b/00_Utilities/python/ci-requirements.txt @@ -12,8 +12,11 @@ flake8==4.0.1 # via # -r ci-requirements.in # flake8-bugbear + # flake8-comprehensions flake8-bugbear==22.1.11 # via -r ci-requirements.in +flake8-comprehensions==3.8.0 + # via -r ci-requirements.in iniconfig==1.1.1 # via pytest mccabe==0.6.1 diff --git a/04_Awari/python/awari.py b/04_Awari/python/awari.py index 4398cb3f..42754c05 100644 --- a/04_Awari/python/awari.py +++ b/04_Awari/python/awari.py @@ -297,25 +297,17 @@ def do_move(m, home, board): if m > 13: m = m - 14 board[m] += 1 - if board[m] == 1: - # capture - if (m != 6) and (m != 13) and (board[12 - m] != 0): - do_capture(m, home, board) + if board[m] == 1 and (m != 6) and (m != 13) and (board[12 - m] != 0): + do_capture(m, home, board) return m def player_has_stones(board): - for i in range(6): - if board[i] > 0: - return True - return False + return any(board[i] > 0 for i in range(6)) def computer_has_stones(board): - for i in range(7, 13): - if board[i] > 0: - return True - return False + return any(board[i] > 0 for i in range(7, 13)) def execute_move(move, home, board): diff --git a/05_Bagels/python/bagels.py b/05_Bagels/python/bagels.py index a843813d..703ced43 100644 --- a/05_Bagels/python/bagels.py +++ b/05_Bagels/python/bagels.py @@ -48,7 +48,7 @@ def print_rules(): def pick_number(): # Note that this returns a list of individual digits # as separate strings, not a single integer or string - numbers = [i for i in range(10)] + numbers = list(range(10)) random.shuffle(numbers) num = numbers[0:3] num = [str(i) for i in num] diff --git a/10_Blackjack/python/blackjack.py b/10_Blackjack/python/blackjack.py index e17b54f4..e4d6fa40 100644 --- a/10_Blackjack/python/blackjack.py +++ b/10_Blackjack/python/blackjack.py @@ -290,10 +290,8 @@ class Game: print(player_hands_message) print(f"{player.get_name()} Hand:\t{player.hand_as_string(True)}") - if PlayerType.Player == player.player_type: - # player isn't the dealer - if player.bet == 0: # player is out of money - break + if PlayerType.Player == player.player_type and player.bet == 0: + break # play through turn # check their hand value for a blackjack(21) or bust diff --git a/12_Bombs_Away/python/bombs_away.py b/12_Bombs_Away/python/bombs_away.py index 5c591f44..819315e0 100644 --- a/12_Bombs_Away/python/bombs_away.py +++ b/12_Bombs_Away/python/bombs_away.py @@ -186,4 +186,4 @@ if __name__ == "__main__": again = True while again: play_game() - again = True if input("ANOTHER MISSION? (Y OR N): ").upper() == "Y" else False + again = input("ANOTHER MISSION? (Y OR N): ").upper() == "Y" diff --git a/16_Bug/python/Bug.py b/16_Bug/python/Bug.py index 71344b4c..03e9b91a 100644 --- a/16_Bug/python/Bug.py +++ b/16_Bug/python/Bug.py @@ -96,7 +96,7 @@ U = 0 V = 0 Y = 0 -while not (Y > 0): +while Y <= 0: Z = random.randint(1, 6) print() C = 1 diff --git a/16_Bug/python/bug-overengineered.py b/16_Bug/python/bug-overengineered.py index cafd2124..73a1a347 100644 --- a/16_Bug/python/bug-overengineered.py +++ b/16_Bug/python/bug-overengineered.py @@ -26,7 +26,7 @@ def main(states, data): """ while True: - if "exit" == data["state"]: + if data["state"] == "exit": break view, control, model = states[data["state"]] cmd = view(data) @@ -112,7 +112,7 @@ def update_game(data, action): # stores logs of what happened during a particular round logs = [] - if "pictures" == action: + if action == "pictures": data["state"] = "pictures" else: part_added = False @@ -178,18 +178,18 @@ def print_game(data): code, part_idx, player, *logdata = log part_type = data["partTypes"][part_idx] - if "rolled" == code: + if code == "rolled": print() print(f"{player} ROLLED A {part_idx + 1}") print(f"{part_idx + 1}={part_type.name}") - elif "added" == code: - if "YOU" == player: + elif code == "added": + if player == "YOU": if part_type.name in ["FEELERS", "LEGS", "TAIL"]: print(f"I NOW GIVE YOU A {part_type.name.replace('s', '')}.") else: print(f"YOU NOW HAVE A {part_type.name}.") - elif "I" == player: + elif player == "I": if part_type.name in ["BODY", "NECK", "TAIL"]: print(f"I NOW HAVE A {part_type.name}.") elif part_type.name == "FEELERS": @@ -200,19 +200,19 @@ def print_game(data): f"{player} NOW HAVE {data['players'][player][part_idx]} {part_type.name}" ) - elif "missingDep" == code: + elif code == "missingDep": (dep_idx,) = logdata dep = data["partTypes"][dep_idx] print( f"YOU DO NOT HAVE A {dep.name}" - if "YOU" == player + if player == "YOU" else f"I NEEDED A {dep.name}" ) - elif "overMax" == code: + elif code == "overMax": (part_count,) = logdata if part_count > 1: - num = "TWO" if 2 == part_count else part_count + num = "TWO" if part_count == 2 else part_count maxMsg = f"HAVE {num} {part_type.name}S ALREADY" else: maxMsg = f"ALREADY HAVE A {part_type.name}" @@ -228,7 +228,7 @@ def print_pictures(data): typeIxs = {part_type.name: idx for idx, part_type in enumerate(data["partTypes"])} PIC_WIDTH = 22 for player, parts in data["players"].items(): - print(f"*****{'YOUR' if 'YOU' == player else 'MY'} BUG*****") + print(f"*****{'YOUR' if player == 'YOU' else 'MY'} BUG*****") print() print() if parts[typeIxs["BODY"]] > 0: @@ -276,7 +276,7 @@ def print_winner(data): Displays the winning message """ for player in data["finished"]: - print(f"{'YOUR' if 'YOU' == player else 'MY'} BUG IS FINISHED.") + print(f"{'YOUR' if player == 'YOU' else 'MY'} BUG IS FINISHED.") print("I HOPE YOU ENJOYED THE GAME, PLAY IT AGAIN SOON!!") diff --git a/17_Bullfight/python/Bullfight.py b/17_Bullfight/python/Bullfight.py index b0cb4647..c2a68887 100644 --- a/17_Bullfight/python/Bullfight.py +++ b/17_Bullfight/python/Bullfight.py @@ -81,9 +81,7 @@ if Z != "NO": print("THE BETTER YOUR CHANCES ARE.") print_n_newlines(2) -D = {} -D[5] = 1 -D[4] = 1 +D = {4: 1, 5: 1} LS = ["", "SUPERB", "GOOD", "FAIR", "POOR", "AWFUL"] A = random.randint(1, 5) print(f"YOU HAVE DRAWN A {LS[A]} BULL.") diff --git a/23_Checkers/python/checkers.py b/23_Checkers/python/checkers.py index 3ba92b02..5b5616c2 100644 --- a/23_Checkers/python/checkers.py +++ b/23_Checkers/python/checkers.py @@ -237,11 +237,11 @@ class Board: if self.spaces[landing_x][landing_y] == COMPUTER_PIECE: for delta_x in (-2, 2): test_record = self.try_extend(landing_x, landing_y, delta_x, -2) - if not (move_record is None): - if (best_move is None) or ( - move_record.quality > best_move.quality - ): - best_move = test_record + if (move_record is not None) and ( + (best_move is None) + or (move_record.quality > best_move.quality) + ): + best_move = test_record else: assert self.spaces[landing_x][landing_y] == COMPUTER_KING for delta_x in (-2, 2): diff --git a/26_Chomp/python/chomp.py b/26_Chomp/python/chomp.py index f46799a1..0188b269 100755 --- a/26_Chomp/python/chomp.py +++ b/26_Chomp/python/chomp.py @@ -18,9 +18,7 @@ class Canvas: def render(self): lines = [" 1 2 3 4 5 6 7 8 9"] - row = 0 - for line in self._buffer: - row += 1 + for row, line in enumerate(self._buffer, start=1): lines.append(" " + str(row) + " " * 5 + " ".join(line)) return "\n".join(lines) diff --git a/28_Combat/python/combat.py b/28_Combat/python/combat.py index ef24c9d4..87e12532 100644 --- a/28_Combat/python/combat.py +++ b/28_Combat/python/combat.py @@ -30,7 +30,7 @@ def get_forces(): usr_navy = int(input()) print("A. F. " + str(cpu_air) + " ? ", end="") usr_air = int(input()) - if not ((usr_army + usr_navy + usr_air) > MAX_UNITS): + if (usr_army + usr_navy + usr_air) <= MAX_UNITS: break diff --git a/30_Cube/python/cube.py b/30_Cube/python/cube.py index 654efad0..479edd52 100755 --- a/30_Cube/python/cube.py +++ b/30_Cube/python/cube.py @@ -4,16 +4,21 @@ # Converted from BASIC to Python by Trevor Hobson import random +from typing import Tuple -def mine_position(): - mine = [] - for _ in range(3): - mine.append(random.randint(1, 3)) - return mine +def mine_position() -> Tuple[int, int, int]: + return (random.randint(1, 3), random.randint(1, 3), random.randint(1, 3)) -def play_game(): +def parse_move(move: str) -> Tuple[int, int, int]: + coordinates = [int(item) for item in move.split(",")] + if len(coordinates) == 3: + return tuple(coordinates) # type: ignore + raise ValueError + + +def play_game() -> None: """Play one round of the game""" money = 500 @@ -21,10 +26,9 @@ def play_game(): while True: mines = [] for _ in range(5): - mine = [] while True: mine = mine_position() - if not (mine in mines or mine == [1, 1, 1] or mine == [3, 3, 3]): + if not (mine in mines or mine == (1, 1, 1) or mine == (3, 3, 3)): break mines.append(mine) wager = -1 @@ -37,16 +41,12 @@ def play_game(): except ValueError: print("Please enter a number.") prompt = "\nIt's your move: " - position = [1, 1, 1] + position = (1, 1, 1) while True: - move = [-1, -1, -1] - while move == [-1, -1, -1]: + move = (-1, -1, -1) + while move == (-1, -1, -1): try: - coordinates = [int(item) for item in input(prompt).split(",")] - if len(coordinates) == 3: - move = coordinates - else: - raise ValueError + move = parse_move(input(prompt)) except (ValueError, IndexError): print("Please enter valid coordinates.") if ( @@ -58,14 +58,14 @@ def play_game(): 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] + move[0] not in [1, 2, 3] + or move[1] not in [1, 2, 3] + or move[2] not in [1, 2, 3] ): print("\nIllegal move. You lose") money = money - wager break - elif move == [3, 3, 3]: + elif move == (3, 3, 3): print("\nCongratulations!") money = money + wager break @@ -87,28 +87,32 @@ def play_game(): print("\nGoodbye.") -def main(): +def print_instructions(): + print("\nThis is a game in which you will be playing against the") + print("random decisions of the computer. The field of play is a") + print("cube of side 3. Any of the 27 locations can be designated") + print("by inputing three numbers such as 2,3,1. At the start,") + print("you are automatically at location 1,1,1. The object of") + print("the game is to get to location 3,3,3. One minor detail:") + print("the computer will pick, at random, 5 locations at which") + print("it will plant land mines. If you hit one of these locations") + print("you lose. One other detail: You may move only one space") + print("in one direction each move. For example: From 1,1,2 you") + print("may move to 2,1,2 or 1,1,3. You may not change") + print("two of the numbers on the same move. If you make an illegal") + print("move, you lose and the computer takes the money you may") + print("have bet on that round.\n") + print("When stating the amount of a wager, print only the number") + print("of dollars (example: 250) you are automatically started with") + print("500 dollars in your account.\n") + print("Good luck!") + + +def main() -> None: print(" " * 34 + "CUBE") print(" " * 15 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n") if input("Do you want to see the instructions ").lower().startswith("y"): - print("\nThis is a game in which you will be playing against the") - print("random decisions of the computer. The field of play is a") - print("cube of side 3. Any of the 27 locations can be designated") - print("by inputing three numbers such as 2,3,1. At the start,") - print("you are automatically at location 1,1,1. The object of") - print("the game is to get to location 3,3,3. One minor detail:") - print("the computer will pick, at random, 5 locations at which") - print("it will plant land mines. If you hit one of these locations") - print("you lose. One other detail: You may move only one space") - print("in one direction each move. For example: From 1,1,2 you") - print("may move to 2,1,2 or 1,1,3. You may not change") - print("two of the numbers on the same move. If you make an illegal") - print("move, you lose and the computer takes the money you may") - print("have bet on that round.\n") - print("When stating the amount of a wager, print only the number") - print("of dollars (example: 250) you are automatically started with") - print("500 dollars in your account.\n") - print("Good luck!") + print_instructions() keep_playing = True while keep_playing: diff --git a/34_Digits/python/Digits.py b/34_Digits/python/Digits.py index c6d10977..12aec85c 100644 --- a/34_Digits/python/Digits.py +++ b/34_Digits/python/Digits.py @@ -122,9 +122,8 @@ def main(): if s < s1: s = s1 my_guess = j - elif s1 == s: - if random.random() >= 0.5: - my_guess = j + elif s1 == s and random.random() >= 0.5: + my_guess = j result = "" diff --git a/39_Golf/python/golf.py b/39_Golf/python/golf.py index 0560724b..9339c236 100644 --- a/39_Golf/python/golf.py +++ b/39_Golf/python/golf.py @@ -595,19 +595,21 @@ class Golf: # if you're in the rough, or sand, you really should be using a wedge if ( - self.is_in_rough(self.BALL) - or self.is_in_hazard(self.BALL, GameObjType.SAND) - ) and not (clubIndex == 8 or clubIndex == 9): - if odds(40): - flags |= dub + ( + self.is_in_rough(self.BALL) + or self.is_in_hazard(self.BALL, GameObjType.SAND) + ) + and not (clubIndex == 8 or clubIndex == 9) + and odds(40) + ): + flags |= dub # trap difficulty if ( self.is_in_hazard(self.BALL, GameObjType.SAND) and self.player_difficulty == 4 - ): - if odds(20): - flags |= dub + ) and odds(20): + flags |= dub # hook/slice # There's 10% chance of a hook or slice @@ -675,9 +677,8 @@ class Golf: else: distance = clubAmt - if self.player_difficulty == 3: # poor distance - if odds(80): - distance = distance * 0.80 + if self.player_difficulty == 3 and odds(80): # poor distance + distance = distance * 0.80 if (flags & luck) == luck: distance = clubAmt @@ -696,9 +697,8 @@ class Golf: plot = self.plot_ball(self.BALL, distance, angle) # calculate a new location - if (flags & luck) == luck: - if plot.Y > 0: - plot.Y = 2 + if (flags & luck) == luck and plot.Y > 0: + plot.Y = 2 flags = self.find_ball( Ball(plot.X, plot.Y, plot.Offline, GameObjType.BALL), flags diff --git a/46_Hexapawn/python/hexapawn.py b/46_Hexapawn/python/hexapawn.py index 254b5f17..69ee11b4 100644 --- a/46_Hexapawn/python/hexapawn.py +++ b/46_Hexapawn/python/hexapawn.py @@ -138,10 +138,10 @@ class BoardLayout: self.moves = move_list def _check_match_no_mirror(self, cell_list): - for space_index, board_contents in enumerate(self.cells): - if board_contents != cell_list[space_index]: - return False - return True + return all( + board_contents == cell_list[space_index] + for space_index, board_contents in enumerate(self.cells) + ) def _check_match_with_mirror(self, cell_list): for space_index, board_contents in enumerate(self.cells): @@ -286,17 +286,11 @@ def is_legal_human_move(board, m1, m2): def player_piece_on_back_row(board): - for space in range(1, 4): - if board_contents(board, space) == HUMAN_PIECE: - return True - return False + return any(board_contents(board, space) == HUMAN_PIECE for space in range(1, 4)) def computer_piece_on_front_row(board): - for space in range(7, 10): - if board_contents(board, space) == COMPUTER_PIECE: - return True - return False + return any(board_contents(board, space) == COMPUTER_PIECE for space in range(7, 10)) def all_human_pieces_captured(board): diff --git a/50_Horserace/python/horserace.py b/50_Horserace/python/horserace.py index 428dbbcc..556beb21 100644 --- a/50_Horserace/python/horserace.py +++ b/50_Horserace/python/horserace.py @@ -140,8 +140,6 @@ def get_distance(odd): return 4 elif d < s + 77: return 5 - elif d < s + 77: - return 5 elif d < s + 92: return 6 else: @@ -233,12 +231,10 @@ def print_race_results(race_positions, odds, bets, player_names): # print the race positions first basic_print("THE RACE RESULTS ARE:") - position = 1 - for horse_idx in reversed(race_positions): + for position, horse_idx in enumerate(reversed(race_positions), start=1): line = f"{position} PLACE HORSE NO. {horse_idx} AT {odds[horse_idx]}:1" basic_print("") basic_print(line) - position += 1 # followed by the amount the players won winning_horse_idx = race_positions[-1] diff --git a/65_Nim/python/Traditional_NIM.py b/65_Nim/python/Traditional_NIM.py index ce00b40a..d1003f13 100644 --- a/65_Nim/python/Traditional_NIM.py +++ b/65_Nim/python/Traditional_NIM.py @@ -42,11 +42,7 @@ class NIM: return pile, num def _command_integrity(self, num, pile): - if pile <= 4 and pile >= 1: - if num <= self.piles[pile]: - return True - - return False + return pile <= 4 and pile >= 1 and num <= self.piles[pile] def print_pegs(self): for pile, peg in self.piles.items(): @@ -71,11 +67,7 @@ class NIM: for v in self.piles.values(): sum += v - if sum == 0: - return True - - else: - return False + return sum == 0 def main(): diff --git a/75_Roulette/python/roulette.py b/75_Roulette/python/roulette.py index 14690de9..204dcdd2 100644 --- a/75_Roulette/python/roulette.py +++ b/75_Roulette/python/roulette.py @@ -97,29 +97,23 @@ def bet_results(bet_IDs, bet_Values, result): total_winnings = 0 def get_modifier(id, num): - if id == 37 and num <= 12: + if ( + (id == 37 and num <= 12) + or (id == 38 and num > 12 and num <= 24) + or (id == 39 and num > 24 and num < 37) + or (id == 40 and num < 37 and num % 3 == 1) + or (id == 41 and num < 37 and num % 3 == 2) + or (id == 42 and num < 37 and num % 3 == 0) + ): return 2 - elif id == 38 and num > 12 and num <= 24: - return 2 - elif id == 39 and num > 24 and num < 37: - return 2 - elif id == 40 and num < 37 and num % 3 == 1: - return 2 - elif id == 41 and num < 37 and num % 3 == 2: - return 2 - elif id == 42 and num < 37 and num % 3 == 0: - return 2 - elif id == 43 and num <= 18: - return 1 - elif id == 44 and num > 18 and num <= 36: - return 1 - elif id == 45 and num % 2 == 0: - return 1 - elif id == 46 and num % 2 == 1: - return 1 - elif id == 47 and num in RED_NUMBERS: - return 1 - elif id == 48 and num not in RED_NUMBERS: + elif ( + (id == 43 and num <= 18) + or (id == 44 and num > 18 and num <= 36) + or (id == 45 and num % 2 == 0) + or (id == 46 and num % 2 == 1) + or (id == 47 and num in RED_NUMBERS) + or (id == 48 and num not in RED_NUMBERS) + ): return 1 elif id < 37 and id == num: return 35 diff --git a/77_Salvo/python/salvo.py b/77_Salvo/python/salvo.py index 113a97b3..91919fcb 100644 --- a/77_Salvo/python/salvo.py +++ b/77_Salvo/python/salvo.py @@ -297,9 +297,8 @@ def execute_shot(turn, board, x, y): global current_turn square = board[x - 1][y - 1] ship_hit = -1 - if square is not None: - if square >= 0 and square < len(SHIPS): - ship_hit = square + if square is not None and square >= 0 and square < len(SHIPS): + ship_hit = square board[x - 1][y - 1] = 10 + current_turn return ship_hit @@ -314,9 +313,8 @@ def calculate_shots(board): for x in range(BOARD_HEIGHT): for y in range(BOARD_WIDTH): square = board[x - 1][y - 1] - if square is not None: - if square >= 0 and square < len(SHIPS): - ships_found[square] = 1 + if square is not None and square >= 0 and square < len(SHIPS): + ships_found[square] = 1 shots = 0 for ship in range(len(ships_found)): if ships_found[ship] == 1: @@ -457,11 +455,10 @@ def execute_turn(turn): else: x, y = input_coord() square = board[x - 1][y - 1] - if square is not None: - if square > 10: - if turn == PLAYER: - print("YOU SHOT THERE BEFORE ON TURN", square - 10) - continue + if square is not None and square > 10: + if turn == PLAYER: + print("YOU SHOT THERE BEFORE ON TURN", square - 10) + continue shots.append((x, y)) valid_shot = True @@ -470,9 +467,8 @@ def execute_turn(turn): hit = execute_shot(turn, board, shot[0], shot[1]) if hit >= 0: hits.append(hit) - if turn == COMPUTER: - if print_computer_shots: - print(shot[0], shot[1]) + if turn == COMPUTER and print_computer_shots: + print(shot[0], shot[1]) for hit in hits: if turn == COMPUTER: diff --git a/84_Super_Star_Trek/python/superstartrek.py b/84_Super_Star_Trek/python/superstartrek.py index 01a0631b..578e1cda 100644 --- a/84_Super_Star_Trek/python/superstartrek.py +++ b/84_Super_Star_Trek/python/superstartrek.py @@ -260,14 +260,13 @@ def short_range_scan(): docked = False for i in (s1 - 1, s1, s1 + 1): for j in (s2 - 1, s2, s2 + 1): - if 0 <= i <= 7 and 0 <= j <= 7: - if compare_marker(i, j, ">!<"): - docked = True - cs = "DOCKED" - e, p = e0, p0 - print("SHIELDS DROPPED FOR DOCKING PURPOSES") - s = 0 - break + if 0 <= i <= 7 and 0 <= j <= 7 and compare_marker(i, j, ">!<"): + docked = True + cs = "DOCKED" + e, p = e0, p0 + print("SHIELDS DROPPED FOR DOCKING PURPOSES") + s = 0 + break else: continue break diff --git a/86_Target/python/target.py b/86_Target/python/target.py index 14b58df5..af158999 100644 --- a/86_Target/python/target.py +++ b/86_Target/python/target.py @@ -44,7 +44,7 @@ def print_instructions(): def prompt(): while True: response = input("INPUT ANGLE DEVIATION FROM X, DEVIATION FROM Z, DISTANCE? ") - if not ("," in response): + if "," not in response: continue terms = response.split(",") diff --git a/88_3-D_Tic-Tac-Toe/python/qubit.py b/88_3-D_Tic-Tac-Toe/python/qubit.py index da5a6c59..4081e70d 100644 --- a/88_3-D_Tic-Tac-Toe/python/qubit.py +++ b/88_3-D_Tic-Tac-Toe/python/qubit.py @@ -368,9 +368,8 @@ class Qubit: ] while True: - if not skipHuman: - if not self.humanMove(board): - break + if not skipHuman and not self.humanMove(board): + break skipHuman = False m = board.machineMove() diff --git a/89_Tic-Tac-Toe/python/tictactoe2.py b/89_Tic-Tac-Toe/python/tictactoe2.py index bd7ad9e1..519cd7d3 100755 --- a/89_Tic-Tac-Toe/python/tictactoe2.py +++ b/89_Tic-Tac-Toe/python/tictactoe2.py @@ -28,32 +28,26 @@ class Space(Enum): def line_170(board, g, h, j, k): - if g == OccupiedBy.Player: - if board[Space.MID_CENTER] == g: - if ( - board[Space.TOP_RIGHT] == g - and board[Space.BOTTOM_LEFT] is OccupiedBy.EMPTY - ): # Line 171 - return Space.BOTTOM_LEFT # Line 187 - elif ( - board[Space.BOTTOM_RIGHT] == g - and board[Space.TOP_LEFT] is OccupiedBy.EMPTY - ): # Line 172 - return Space.TOP_LEFT # Line 181 - elif ( - board[Space.BOTTOM_LEFT] == g - and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY - ): # Line 173 - return Space.TOP_RIGHT # Line 183 - elif ( - board[Space.BOTTOM_RIGHT] is OccupiedBy.PLAYER - and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY - ): # Line 174 - return Space.TOP_RIGHT # Line 189 - elif g is OccupiedBy.COMPUTER: - g = OccupiedBy.PLAYER - h = OccupiedBy.COMPUTER - return line_118(board, g, h, j, k) + if g == OccupiedBy.Player and board[Space.MID_CENTER] == g: + if ( + board[Space.TOP_RIGHT] == g and board[Space.BOTTOM_LEFT] is OccupiedBy.EMPTY + ): # Line 171 + return Space.BOTTOM_LEFT # Line 187 + elif ( + board[Space.BOTTOM_RIGHT] == g and board[Space.TOP_LEFT] is OccupiedBy.EMPTY + ): # Line 172 + return Space.TOP_LEFT # Line 181 + elif ( + board[Space.BOTTOM_LEFT] == g and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY + ) or ( + board[Space.BOTTOM_RIGHT] is OccupiedBy.PLAYER + and board[Space.TOP_RIGHT] is OccupiedBy.EMPTY + ): # Line 173 and 174 + return Space.TOP_RIGHT # Line 183 and Line 189 + elif g is OccupiedBy.COMPUTER: + g = OccupiedBy.PLAYER + h = OccupiedBy.COMPUTER + return line_118(board, g, h, j, k) def line_150(board, g, h, j, k): diff --git a/90_Tower/python/tower.py b/90_Tower/python/tower.py index 5935af38..9f41e444 100644 --- a/90_Tower/python/tower.py +++ b/90_Tower/python/tower.py @@ -91,8 +91,7 @@ class Game: w = int(input("WHICH DISK WOULD YOU LIKE TO MOVE\n")) if w in self.__sizes: return w - else: - raise Exception() + raise Exception() def pick_disk(self): which = None diff --git a/94_War/python/war.py b/94_War/python/war.py index 682771f8..78aa7a73 100755 --- a/94_War/python/war.py +++ b/94_War/python/war.py @@ -98,9 +98,8 @@ def play_game(): else: print("Tie. No score change.") cards_left -= 2 - if cards_left > 2: - if input("Do you want to continue ").lower().startswith("n"): - break + if cards_left > 2 and input("Do you want to continue ").lower().startswith("n"): + break if cards_left == 0: print( "\nWe have run out of cards. Final score: You:",