Skip to content

Commit

Permalink
Fix pylint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Pbatch committed Jun 17, 2024
1 parent 8e5027d commit 4aa2558
Show file tree
Hide file tree
Showing 15 changed files with 730 additions and 105 deletions.
648 changes: 648 additions & 0 deletions .pylintrc

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clashroyalebuildabot/bot/pete/pete_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def _calculate_spell_score(self, units):
C is the negative distance to the furthest unit
"""
score = [0, 0, 0]
for k, v in units["enemy"].items():
for v in units["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
# Assume the unit will move down a space
Expand Down
2 changes: 1 addition & 1 deletion clashroyalebuildabot/bot/pete/pete_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def _preprocess(self):
Estimate the tile of each unit to be the bottom of their bounding box
"""
for side in ["ally", "enemy"]:
for k, v in self.state["units"][side].items():
for v in self.state["units"][side].values():
for unit in v["positions"]:
bbox = unit["bounding_box"]
bbox[0] *= DISPLAY_WIDTH / SCREENSHOT_WIDTH
Expand Down
4 changes: 2 additions & 2 deletions clashroyalebuildabot/bot/standard/standard_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _calculate_minions_score(self, state):
Only play minions on top of enemy units
"""
score = [0] if state["numbers"]["elixir"]["number"] != 10 else [0.5]
for k, v in state["units"]["enemy"].items():
for v in state["units"]["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
distance = self._distance(
Expand Down Expand Up @@ -101,7 +101,7 @@ def _calculate_archers_score(self, state):
Play the archers in the center, vertically aligned with the troop
"""
score = [0] if state["numbers"]["elixir"]["number"] != 10 else [0.5]
for k, v in state["units"]["enemy"].items():
for v in state["units"]["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if self.tile_y < tile_y <= 14:
Expand Down
122 changes: 54 additions & 68 deletions clashroyalebuildabot/bot/two_six_hog_cycle/two_six_hog_cycle_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,14 @@ class TwoSixHogCycleAction(Action):
def _distance(x1, y1, x2, y2):
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5

def _calculate_enemy_troops(self, state):
for k, v in state["units"]["enemy"].items():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if self.tile_y < tile_y <= 14:
if (
tile_x > 8
and self.tile_x == 9
or tile_x <= 8
and self.tile_x == 8
):
return True
return False

def _calculate_hog_rider_score(self, state):
"""
If there are no enemy troops on our side of the arena and
the player has 7 elixir or more
Place hog rider on the bridge as high up as possible
Try to target the lowest hp tower
"""
for k, v in state["units"]["enemy"].items():
for v in state["units"]["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if self.tile_y < tile_y <= 14:
Expand All @@ -40,97 +26,94 @@ def _calculate_hog_rider_score(self, state):
or tile_x <= 8
and self.tile_x == 7
):
score = [0]
return score
return [0]

if state["numbers"]["elixir"]["number"] >= 7:
left_hp, right_hp = [
state["numbers"][f"{direction}_enemy_princess_hp"]["number"]
for direction in ["left", "right"]
]

score = [0]
if self.tile_x == 3:
score = [1, self.tile_y, left_hp != -1, left_hp <= right_hp]
elif self.tile_x == 14:
score = [1, self.tile_y, right_hp != -1, right_hp <= left_hp]
return score
return [1, self.tile_y, left_hp != -1, left_hp <= right_hp]

if self.tile_x == 14:
return [1, self.tile_y, right_hp != -1, right_hp <= left_hp]

return [0]

def _calculate_cannon_score(self, state):
"""
If there are ground troops place the cannon in the middle of the arena
:param state:
:return:
"""
if self.tile_x != 9 or self.tile_y != 10:
return [0]

score = [0]
for side in ["ally", "enemy"]:
for k, v in state["units"][side].items():
for v in state["units"][side].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if v["transport"] == "ground":
if tile_y >= 10:
if 8 < self.tile_x < 10:
if self.tile_y == 10:
score = [2]
return score
tile_y = unit["tile_xy"][1]
if v["transport"] == "ground" and tile_y >= 10:
return [2]

return [0]

def _calculate_musketeer_score(self, state):
"""
If there are flying troops
Place musketeer at 7 tiles in front of the enemies
That should be just within her range and not too close to the enemy
"""
score = [0]
for side in ["ally", "enemy"]:
for k, v in state["units"][side].items():
for v in state["units"][side].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
tile_y = unit["tile_xy"][1]
if v["transport"] == "air" and self.tile_y == tile_y - 7:
score = [2]
return score
return [2]

return [0]

def _calculate_ice_golem_score(self, state):
"""
If there is a ground troop on the bridge place the ice golem in the middle of the
arena one tile away from the enemy
"""
score = [0]
if self.tile_y != 4:
return [0]

for side in ["ally", "enemy"]:
for k, v in state["units"][side].items():
for v in state["units"][side].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if (18 >= tile_y >= 15) and (v["transport"] == "ground"):
if tile_x > 8:
if self.tile_y == 14 and self.tile_x == 8:
score = [2]
if tile_x <= 8:
if self.tile_y == 14 and self.tile_x == 9:
score = [2]
if not (18 >= tile_y >= 15) or v["transport"] != "ground":
continue

return score
lhs = tile_x <= 8 and self.tile_x == 9
rhs = tile_x > 8 and self.tile_x == 8
if lhs or rhs:
return [2]

return [0]

def _calculate_ice_spirit_score(self, state):
"""
Place the ice spirit in the middle of the arena when a ground troop is on the bridge
"""
score = [0] if state["numbers"]["elixir"]["number"] != 10 else [0.5]
score = [0]
if self.tile_y != 10:
return [0]

for side in ["ally", "enemy"]:
for k, v in state["units"][side].items():
for v in state["units"][side].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if (18 >= tile_y >= 15) and (v["transport"] == "ground"):
if tile_x > 8:
if self.tile_y == 10 and self.tile_x == 8:
score = [2]
if tile_x <= 8:
if self.tile_y == 10 and self.tile_x == 9:
score = [2]
if not (18 >= tile_y >= 15) or v["transport"] != "ground":
continue

return score
if (tile_x <= 8 and self.tile_x == 8) or (
tile_x > 8 and self.tile_x == 9
):
return [2]

return [0]

def _calculate_spell_score(self, units, radius, min_to_hit):
"""
Expand All @@ -142,7 +125,7 @@ def _calculate_spell_score(self, units, radius, min_to_hit):
C is the negative distance to the furthest unit
"""
score = [0, 0, 0]
for k, v in units["enemy"].items():
for v in units["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
# Assume the unit will move down a few spaces
Expand All @@ -168,7 +151,7 @@ def _calculate_log_score(self, state):
"""
units = state["units"]
score = [0]
for k, v in units["enemy"].items():
for v in units["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if tile_y <= 8 and v["transport"] == "ground":
Expand All @@ -182,13 +165,16 @@ def _calculate_fireball_score(self, state):
Play the fireball card if it will hit flying units
"""
units = state["units"]
for k, v in units["enemy"].items():
for v in units["enemy"].values():
for unit in v["positions"]:
tile_x, tile_y = unit["tile_xy"]
if v["transport"] == "air":
if self.tile_y == tile_y - 4 and self.tile_x == tile_x:
score = [1]
return score
if (
v["transport"] == "air"
and self.tile_y == tile_y - 4
and self.tile_x == tile_x
):
return [1]

return self._calculate_spell_score(
state["units"], radius=2.5, min_to_hit=3
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def _preprocess(self):
Estimate the tile of each unit to be the bottom of their bounding box
"""
for side in ["ally", "enemy"]:
for k, v in self.state["units"][side].items():
for v in self.state["units"][side].values():
for unit in v["positions"]:
bbox = unit["bounding_box"]
bbox[0] *= DISPLAY_WIDTH / SCREENSHOT_WIDTH
Expand Down
9 changes: 0 additions & 9 deletions clashroyalebuildabot/data/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,12 @@
from clashroyalebuildabot.data.cards import Cards
from clashroyalebuildabot.data.units import Units

"""
Miscellaneous
"""
# Directories
SRC_DIR = os.path.dirname(os.path.dirname(__file__))
DATA_DIR = os.path.join(SRC_DIR, "data")
SCREENSHOTS_DIR = os.path.join(SRC_DIR, "screenshots")
LABELS_DIR = os.path.join(SRC_DIR, "labels")

"""
Click config
"""
# Display dimensions
DISPLAY_WIDTH = 720
DISPLAY_HEIGHT = 1280
Expand Down Expand Up @@ -79,9 +73,6 @@
DISPLAY_CARD_HEIGHT = 147
DISPLAY_CARD_DELTA_X = 136

"""
Detector config
"""
# Cards
HAND_SIZE = 5
DECK_SIZE = 8
Expand Down
8 changes: 4 additions & 4 deletions clashroyalebuildabot/screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def __init__(self):
config_path = os.path.join(
os.path.dirname(__file__), "config", "config.yml"
)
with open(config_path, "r") as file:
with open(config_path, encoding="utf-8") as file:
config = yaml.safe_load(file)

adb_config = config["adb"]
Expand All @@ -27,11 +27,11 @@ def __init__(self):
self.device.connect()
window_size = self.device.shell("wm size")
window_size = window_size.replace("Physical size: ", "")
self.size = tuple([int(i) for i in window_size.split("x")])
self.size = tuple(int(i) for i in window_size.split("x"))
except Exception as e:
logger.critical(f"Error getting screen size: {e}")
logger.critical("Exiting due to device connection error.")
raise SystemExit()
raise SystemExit() from e

def click(self, x, y):
self.device.shell(f"input tap {x} {y}")
Expand Down Expand Up @@ -66,7 +66,7 @@ def _take_screenshot(self):

image = image.convert("RGB")
image = image.resize(
(SCREENSHOT_WIDTH, SCREENSHOT_HEIGHT), Image.BILINEAR
(SCREENSHOT_WIDTH, SCREENSHOT_HEIGHT), Image.Resampling.BILINEAR
)

return image
Expand Down
4 changes: 2 additions & 2 deletions clashroyalebuildabot/state/card_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def _calculate_multi_hash(self, image):
def _calculate_hash(self, image):
return np.array(
image.resize(
(self.hash_size, self.hash_size), Image.BILINEAR
(self.hash_size, self.hash_size), Image.Resampling.BILINEAR
).convert("L"),
dtype=np.float32,
).ravel()
Expand All @@ -43,7 +43,7 @@ def _calculate_cards_and_card_hashes(self):
dtype=np.float32,
)
i = 0
with open(os.path.join(DATA_DIR, "cards.csv")) as f:
with open(os.path.join(DATA_DIR, "cards.csv"), encoding="utf-8") as f:
for line in f:
name, _, cost, type_, target, _ = (
line.strip().replace('"', "").split(",")
Expand Down
6 changes: 4 additions & 2 deletions clashroyalebuildabot/state/debugger.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def _write_label(image, state, basename):
label = f"{unit_name} {xc} {yc} {w} {h}"
labels.append(label)

with open(os.path.join(LABELS_DIR, f"{basename}.txt"), "w") as f:
with open(
os.path.join(LABELS_DIR, f"{basename}.txt"), "w", encoding="utf-8"
) as f:
f.write("\n".join(labels))

def _draw_text(self, d, bbox, text, rgba=(0, 0, 0, 255)):
Expand All @@ -64,7 +66,7 @@ def _draw_text(self, d, bbox, text, rgba=(0, 0, 0, 255)):

def _write_image(self, image, state, basename):
d = ImageDraw.Draw(image, "RGBA")
for k, v in state["numbers"].items():
for v in state["numbers"].values():
d.rectangle(tuple(v["bounding_box"]))
self._draw_text(d, v["bounding_box"], str(v["number"]))

Expand Down
2 changes: 1 addition & 1 deletion clashroyalebuildabot/state/number_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _calculate_confidence_and_number(self, pred):
int(number) if number else -1
)

def _post_process(self, pred, **kwargs):
def _post_process(self, pred):
clean_pred = {}
for p, (name, x, y) in zip(pred, NUMBER_CONFIG):
confidence, number = self._calculate_confidence_and_number(p)
Expand Down
4 changes: 0 additions & 4 deletions clashroyalebuildabot/state/onnx_detector.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import numpy as np
import onnxruntime
from PIL import ImageOps


class OnnxDetector:
Expand Down Expand Up @@ -57,8 +56,5 @@ def fix_bboxes(self, x, width, height, padding):
def _infer(self, x):
return self.sess.run([self.output_name], {self.input_name: x})[0]

def _post_process(self, pred):
raise NotImplementedError

def run(self, image):
raise NotImplementedError
Loading

0 comments on commit 4aa2558

Please sign in to comment.