(pos[0] + r, pos[1]),
(pos[0], pos[1] + r),
(pos[0] - r, pos[1]),
- )
+ ),
)
for x, col in enumerate(pa):
for y in range(len(col)):
pa[x][y] = pygame.Color(
- y // 2, y // 2, y // 2, 255 - (y, x)[i] * 255 // max(size),
+ y // 2,
+ y // 2,
+ y // 2,
+ 255 - (y, x)[i] * 255 // max(size),
)
return overlay_surfs
super().__init__(parent)
self.rect = rect
self.radii = (378, min(rect.size) // 2)
- self.radii_squared = tuple(r ** 2 for r in self.radii)
+ self.radii_squared = tuple(r**2 for r in self.radii)
self.avg_radius = sum(self.radii) / len(self.radii)
self.hue_circle = self.render_hue_circle()
self.hue_angle = 0
sz = rotated_hue_surf.get_size()
self.surf.blit(
rotated_hue_surf,
- (self.rect.centerx - sz[0] // 2, self.rect.centery - sz[1] // 2)
+ (self.rect.centerx - sz[0] // 2, self.rect.centery - sz[1] // 2),
)
sz = self.hue_surf_rect.size
self,
pygame.Rect(
(label_right, hue_slider.rect.top),
- (label_width, button_height)
+ (label_width, button_height),
),
"H",
Label.HAlign.CENTER,
value_spinner,
),
(self.color_circle,),
- (self.hs_map, value_slider2,),
+ (
+ self.hs_map,
+ value_slider2,
+ ),
),
)
if sender != self.color_circle:
self.color_circle.hue_angle = values["h"] * tau / 255
sz = self.color_circle.hue_surf_rect.size
- self.color_circle.sv_pos = (values["s"] * sz[0] / 255, values["v"] * sz[1] / 255)
+ self.color_circle.sv_pos = (
+ values["s"] * sz[0] / 255,
+ values["v"] * sz[1] / 255,
+ )
if sender != self.hs_map:
...
kwargs["color"] = color
elif dest in self.HSV_LETTERS:
hsv_controls = [
- next(
- d for d in self.channel_slots[c] if not isinstance(d, Slider)
- )
+ next(d for d in self.channel_slots[c] if not isinstance(d, Slider))
for c in self.HSV_LETTERS
]
index = self.HSV_LETTERS.index(dest)
else:
try:
color = pygame.Color(color_like)
- except:
+ except ValueError:
color = pygame.Color(f"0x{color_like}")
self.parent.draw_image.color = color
self.update_controls()
self.dot(self.image, ev.pos)
return
if self.stroke_method is self.StrokeMethod.ROUND:
- StrokeRoundLine(
- self.prev_pos, ev.pos, self.line_width
- ).draw(self.image, self.color)
+ StrokeRoundLine(self.prev_pos, ev.pos, self.line_width).draw(
+ self.image, self.color
+ )
elif self.stroke_method is self.StrokeMethod.SQUARE:
- StrokeSquareLine(
- self.prev_pos, ev.pos, self.line_width
- ).draw(self.image, self.color)
+ StrokeSquareLine(self.prev_pos, ev.pos, self.line_width).draw(
+ self.image, self.color
+ )
elif self.stroke_method is self.StrokeMethod.PYGAME:
pygame.draw.line(
self.image, self.color, self.prev_pos, ev.pos, self.line_width
y = self.base_rect.top
self.label = Label(
self,
- pygame.Rect((self.base_rect.left, y), (self.base_rect.width, button_height)),
+ pygame.Rect(
+ (self.base_rect.left, y), (self.base_rect.width, button_height)
+ ),
"",
Label.HAlign.CENTER,
)
self,
pygame.Rect((x, y), (button_width, button_height)),
value,
- callback
+ callback,
)
x += button_width
pygame.K_PAGEDOWN: partial(nav, nav=BookManager.Nav.NEXT),
pygame.K_END: partial(nav, nav=BookManager.Nav.LAST),
pygame.K_n: partial(nav, nav=BookManager.Nav.NEW),
- }
+ },
}
class WinMessage(MessageBox):
- root: "ConnectFour"
+ root: "Root"
def __init__(self, parent, rect):
super().__init__(parent, rect, "")
(self.rect.width, self.rect.height + self.part_size[1]),
)
self.part_radius = int(self.RADIUS * min(self.part_size))
- self.field = [
- [0] * self.FIELD_SIZE[0] for _ in range(self.FIELD_SIZE[1])
- ]
+ self.field = [[0] * self.FIELD_SIZE[0] for _ in range(self.FIELD_SIZE[1])]
self.adding = None
self.drop_y = 0
self.current_player = 0
self,
pygame.Rect(
(size[0] // 6, size[1] * 3 // 8), (size[0] * 2 // 3, size[1] // 4)
- )
+ ),
)
self.top_button = ColorButton(
self,
self.surf,
self.PLAYER_COLORS[self.current_player],
(
- self.rect.left + self.part_size[0] * (x + .5),
+ self.rect.left + self.part_size[0] * (x + 0.5),
self.rect.top - self.part_size[1] // 2 + drop_y,
),
self.part_radius,
)
pygame.draw.circle(
surf,
- (
- pygame.Color(0, 0, 0, 0), *self.PLAYER_COLORS
- )[self.field[y][x]],
+ (pygame.Color(0, 0, 0, 0), *self.PLAYER_COLORS)[self.field[y][x]],
part_rect.center,
self.part_radius,
)
return surf
def draw_adding(self):
- StrokeCircleSegment(
- self.adding[1:], self.PULL_DOWN, 0, pi, 16
- ).draw(self.surf, "darkgray")
+ StrokeCircleSegment(self.adding[1:], self.PULL_DOWN, 0, pi, 16).draw(
+ self.surf, "darkgray"
+ )
def draw(self):
self.surf.fill("black")
if 0 not in self.field[0]:
return None
for y, row in zip(
- range(self.top_row, self.FIELD_SIZE[1]), self.field[self.top_row:]
+ range(self.top_row, self.FIELD_SIZE[1]), self.field[self.top_row :]
):
for x, v in enumerate(row):
if self.has_won_at(x, y):
HANDS = (
(-1 / 16, 3 / 16), # fullday
(-1 / 16, 7 / 16), # hour
- (-1 / 16, 3 / 4), # minute
+ (-1 / 16, 3 / 4), # minute
(-1 / 8, 13 / 16), # second
)
WIDTHS = (
- 0.0325, # fullday
+ 0.0325, # fullday
0.02625, # hour
- 0.0175, # minute
- 0.005, # second
+ 0.0175, # minute
+ 0.005, # second
)
def __init__(self, parent, rect):
(points[0][0] + offset[0], points[0][1] + offset[1]),
(points[1][0] + offset[0], points[1][1] + offset[1]),
(points[1][0] - offset[0], points[1][1] - offset[1]),
- ]
+ ],
)
class Config:
def __init__(self, base):
- self.path = Path(
- os.environ.get(
- "XDG_CONFIG_HOME", f"{os.path.expanduser('~')}{os.pathsep}.config"
+ self.path = (
+ Path(
+ os.environ.get(
+ "XDG_CONFIG_HOME", f"{os.path.expanduser('~')}{os.pathsep}.config"
+ )
)
- ) / "zenbook_gui" / f"{base}.json"
+ / "zenbook_gui"
+ / f"{base}.json"
+ )
self.loaded = None
def load(self):
("F11", Key.f11),
("F12", Key.f12),
"\n",
- ("§", KeyCode.from_vk(0xa7), {"x_hint": 1.5}),
+ ("§", KeyCode.from_vk(0xA7), {"x_hint": 1.5}),
("1", KeyCode.from_vk(0x31)),
("2", KeyCode.from_vk(0x32)),
("3", KeyCode.from_vk(0x33)),
("9", KeyCode.from_vk(0x39)),
("0", KeyCode.from_vk(0x30)),
("'", KeyCode.from_vk(0x27)),
- ("^", KeyCode.from_vk(0xfe52)),
+ ("^", KeyCode.from_vk(0xFE52)),
("←", Key.backspace, {"x_hint": 1.5}),
"\n",
("Tab", Key.tab, {"x_hint": 2}),
("E", KeyCode.from_vk(0x65)),
("R", KeyCode.from_vk(0x72)),
("T", KeyCode.from_vk(0x74)),
- ("Z", KeyCode.from_vk(0x7a)),
+ ("Z", KeyCode.from_vk(0x7A)),
("U", KeyCode.from_vk(0x75)),
("I", KeyCode.from_vk(0x69)),
- ("O", KeyCode.from_vk(0x6f)),
+ ("O", KeyCode.from_vk(0x6F)),
("P", KeyCode.from_vk(0x70)),
- ("ü", KeyCode.from_vk(0xfc)),
- ("¨", KeyCode.from_vk(0xfe57)),
+ ("ü", KeyCode.from_vk(0xFC)),
+ ("¨", KeyCode.from_vk(0xFE57)),
("$", KeyCode.from_vk(0x24)),
"\n",
("CpsLk", Key.caps_lock, {"x_hint": 2.5, "led_mask": 1}),
("F", KeyCode.from_vk(0x66)),
("G", KeyCode.from_vk(0x67)),
("H", KeyCode.from_vk(0x68)),
- ("J", KeyCode.from_vk(0x6a)),
- ("K", KeyCode.from_vk(0x6b)),
- ("L", KeyCode.from_vk(0x6c)),
- ("ö", KeyCode.from_vk(0xf6)),
- ("ä", KeyCode.from_vk(0xe4)),
+ ("J", KeyCode.from_vk(0x6A)),
+ ("K", KeyCode.from_vk(0x6B)),
+ ("L", KeyCode.from_vk(0x6C)),
+ ("ö", KeyCode.from_vk(0xF6)),
+ ("ä", KeyCode.from_vk(0xE4)),
("↵", Key.enter, {"x_hint": 1.5}),
"\n",
("↑", Key.shift, {"x_hint": 2}),
- ("<", KeyCode.from_vk(0x3c)),
+ ("<", KeyCode.from_vk(0x3C)),
("Y", KeyCode.from_vk(0x79)),
("X", KeyCode.from_vk(0x78)),
("C", KeyCode.from_vk(0x63)),
("V", KeyCode.from_vk(0x76)),
("B", KeyCode.from_vk(0x62)),
- ("N", KeyCode.from_vk(0x6e)),
- ("M", KeyCode.from_vk(0x6d)),
- (",", KeyCode.from_vk(0x2c)),
- (".", KeyCode.from_vk(0x2e)),
- ("-", KeyCode.from_vk(0x2d)),
+ ("N", KeyCode.from_vk(0x6E)),
+ ("M", KeyCode.from_vk(0x6D)),
+ (",", KeyCode.from_vk(0x2C)),
+ (".", KeyCode.from_vk(0x2E)),
+ ("-", KeyCode.from_vk(0x2D)),
("↑", Key.shift, {"x_hint": 2}),
"\n",
("Ctrl", Key.ctrl_l, {"x_hint": 2}),
("Alt", Key.alt_l),
("␣", Key.space, {"x_hint": 7}),
("⚙", "Settings"),
- ("AltGr", KeyCode.from_vk(0xfe03)),
+ ("AltGr", KeyCode.from_vk(0xFE03)),
("Ctrl", Key.ctrl_r, {"x_hint": 2}),
)
KEYPAD_KEYS = (
("NUM", Key.num_lock, {"led_mask": 2}),
- ("/", KeyCode.from_vk(0xffaf)),
- ("*", KeyCode.from_vk(0xffaa)),
- ("-", KeyCode.from_vk(0xffad)),
+ ("/", KeyCode.from_vk(0xFFAF)),
+ ("*", KeyCode.from_vk(0xFFAA)),
+ ("-", KeyCode.from_vk(0xFFAD)),
"\n",
- ("7", KeyCode.from_vk(0xffb7)),
- ("8", KeyCode.from_vk(0xffb8)),
- ("9", KeyCode.from_vk(0xffb9)),
- ("+", KeyCode.from_vk(0xffab), {"y_hint": 2}),
+ ("7", KeyCode.from_vk(0xFFB7)),
+ ("8", KeyCode.from_vk(0xFFB8)),
+ ("9", KeyCode.from_vk(0xFFB9)),
+ ("+", KeyCode.from_vk(0xFFAB), {"y_hint": 2}),
"\n",
- ("4", KeyCode.from_vk(0xffb4)),
- ("5", KeyCode.from_vk(0xffb5)),
- ("6", KeyCode.from_vk(0xffb6)),
+ ("4", KeyCode.from_vk(0xFFB4)),
+ ("5", KeyCode.from_vk(0xFFB5)),
+ ("6", KeyCode.from_vk(0xFFB6)),
"\n",
- ("1", KeyCode.from_vk(0xffb1)),
- ("2", KeyCode.from_vk(0xffb2)),
- ("3", KeyCode.from_vk(0xffb3)),
- ("Enter", KeyCode.from_vk(0xff8d), {"y_hint": 2}),
+ ("1", KeyCode.from_vk(0xFFB1)),
+ ("2", KeyCode.from_vk(0xFFB2)),
+ ("3", KeyCode.from_vk(0xFFB3)),
+ ("Enter", KeyCode.from_vk(0xFF8D), {"y_hint": 2}),
"\n",
- ("0", KeyCode.from_vk(0xffb0), {"x_hint": 2}),
- (".", KeyCode.from_vk(0xffae)),
+ ("0", KeyCode.from_vk(0xFFB0), {"x_hint": 2}),
+ (".", KeyCode.from_vk(0xFFAE)),
)
self.touch_key = None
# sounds from https://freesoundsite.com/sound-collections/click-sound-effects/
self.sounds = (
- pygame.mixer.Sound(Path(__file__).parent / "sounds" / "Flicker_Sound_Effect.mp3"),
+ pygame.mixer.Sound(
+ Path(__file__).parent / "sounds" / "Flicker_Sound_Effect.mp3"
+ ),
pygame.mixer.Sound(Path(__file__).parent / "sounds" / "Clutch.mp3"),
)
for sound in self.sounds:
key[0],
callback,
data=key[1],
- led_mask=led_mask
+ led_mask=led_mask,
)
)
x += key_width
os.execl(
sys.executable,
executable,
- *sys.orig_argv[sys.orig_argv[0] == executable:],
+ *sys.orig_argv[sys.orig_argv[0] == executable :],
)
if not self.pushed or self.touch_key is None:
return
if (
- (event.touch_id, event.finger_id) == self.touch_key
- and not self.rect.collidepoint(
- MultitouchHandler.map_coords((event.x, event.y), self.surf.get_size())
- )
+ event.touch_id,
+ event.finger_id,
+ ) == self.touch_key and not self.rect.collidepoint(
+ MultitouchHandler.map_coords((event.x, event.y), self.surf.get_size())
):
self.touch_key = None
self.pushed = False
def check_has_pkg(pkg):
- return f"No module named {pkg}.__main__;".encode() in run_cmd(
- (executable, "-m", pkg), 1
- ).stderr
+ return (
+ f"No module named {pkg}.__main__;".encode()
+ in run_cmd((executable, "-m", pkg), 1).stderr
+ )
def get_ipv4_is_connected():
with open("/proc/net/route") as fh:
for line in fh:
fields = line.rstrip().split("\t")
- if fields[1] == '00000000' and int(fields[3], 16) & 2:
+ if fields[1] == "00000000" and int(fields[3], 16) & 2:
return True
return False
def walk_outer(path):
return (
path,
- *(
- base / ent
- for base, dirs, files in path.walk()
- for ent in (*dirs, *files)
- )
+ *(base / ent for base, dirs, files in path.walk() for ent in (*dirs, *files)),
)
def get_venv_environ(venv_dir):
new_env = {"VIRTUAL_ENV": str(venv_dir)}
venv_bin_str = str(venv_dir / "bin")
- if venv_bin_str not in os.environ['PATH'].split(os.pathsep):
+ if venv_bin_str not in os.environ["PATH"].split(os.pathsep):
new_env["PATH"] = f"{venv_bin_str}{os.pathsep}{os.environ['PATH']}"
return new_env
raise SystemError("'venv' is not a directory.")
run_cmd((sys.executable, "-m", "venv", str(venv_dir)))
os.environ.update(get_venv_environ(venv_dir))
- has_pkgs = (venv_dir_is_dir and all(check_has_pkg(pkg) for pkg in pkgs))
+ has_pkgs = venv_dir_is_dir and all(check_has_pkg(pkg) for pkg in pkgs)
if get_ipv4_is_connected():
yesterday = time() - 86400
if not has_pkgs or all(
os.execl(
sys.executable,
executable,
- *sys.orig_argv[sys.orig_argv[0] == executable:],
+ *sys.orig_argv[sys.orig_argv[0] == executable :],
)
exit(1)
if pkg == "pygame":
self.inputs = [
TextInput(
self,
- pygame.Rect((int(self.lw / 2), 288), (int(self.lw * .8), 128)),
+ pygame.Rect((int(self.lw / 2), 288), (int(self.lw * 0.8), 128)),
partial(self.set_player_name, 0),
),
TextInput(
self,
- pygame.Rect((int(self.lw / 2), 288 + 144), (int(self.lw * .8), 128)),
+ pygame.Rect((int(self.lw / 2), 288 + 144), (int(self.lw * 0.8), 128)),
partial(self.set_player_name, 1),
),
]
)
Button(
self,
- pygame.Rect((int(self.lw * 1.5), 288), (self.lw * .8, 144)).inflate(-16, -16),
+ pygame.Rect((int(self.lw * 1.5), 288), (self.lw * 0.8, 144)).inflate(
+ -16, -16
+ ),
"START GAME",
- self.deactivate
+ self.deactivate,
)
self.player_names = []
TextInput(
self,
pygame.Rect(
- (int(self.lw / 2), 288 + 144 * num), (int(self.lw * .8), 128)
+ (int(self.lw / 2), 288 + 144 * num), (int(self.lw * 0.8), 128)
),
- partial(self.set_player_name, num)
+ partial(self.set_player_name, num),
)
)
self.add_button.rect.top += 144
if len(winners) == 1:
self.labels[0].value = f"WINNER: {str(winners[0])} !!!"
else:
- self.labels[0].value = (
- f"WINNERS: {', '.join(str(winner) for winner in winners)} !!!"
- )
+ self.labels[
+ 0
+ ].value = f"WINNERS: {', '.join(str(winner) for winner in winners)} !!!"
def draw_modal(self):
super().draw_modal()
self.current_player = 0
self.name_menu = NameMenu(self)
size = self.surf.get_size()
- thirds = (size[0] // 3, size[1] //3)
+ thirds = (size[0] // 3, size[1] // 3)
self.end_game_menu = EndGameMenu(self, pygame.Rect(thirds, thirds))
self.cards = []
initial_cards = []
self,
pygame.Rect((512, 144), (self.surf.get_width() - 1024, 128)),
"",
- self.next_turn
+ self.next_turn,
)
self.turn_done = False
self.name_menu.activate()
self.rps_buttons = (
RPSButton(
self,
- pygame.Rect((0, size[1] // 2), (size[0] // 2, size[1] // 2)).inflate(-256, -256),
+ pygame.Rect((0, size[1] // 2), (size[0] // 2, size[1] // 2)).inflate(
+ -256, -256
+ ),
192,
partial(self.finger_push, 0),
),
RPSButton(
self,
- pygame.Rect((size[0] // 2, size[1] // 2), (size[0] // 2, size[1] // 2)).inflate(-256, -256),
+ pygame.Rect(
+ (size[0] // 2, size[1] // 2), (size[0] // 2, size[1] // 2)
+ ).inflate(-256, -256),
192,
partial(self.finger_push, 1),
),
)
self.reset_button = FingerButton(
self,
- pygame.Rect(
- (size[0] // 2 - 256, size[1] * 3 // 4), (512, 256)
- ).inflate(-32, -32),
+ pygame.Rect((size[0] // 2 - 256, size[1] * 3 // 4), (512, 256)).inflate(
+ -32, -32
+ ),
"Reset",
self.reset,
)
mask = int(self.v1 is not None) | (int(self.v2 is not None) << 1)
fs = self.big_font.render(str(self.p1), True, "yellow")
fs_size = fs.get_size()
- self.surf.blit(fs, (center[0] - half_radius - fs_size[0] // 2, center[1] - half_radius - fs_size[1] // 2))
+ self.surf.blit(
+ fs,
+ (
+ center[0] - half_radius - fs_size[0] // 2,
+ center[1] - half_radius - fs_size[1] // 2,
+ ),
+ )
fs = self.big_font.render(str(self.p2), True, "yellow")
- self.surf.blit(fs, (center[0] + half_radius - fs_size[0] // 2, center[1] - half_radius - fs_size[1] // 2))
+ self.surf.blit(
+ fs,
+ (
+ center[0] + half_radius - fs_size[0] // 2,
+ center[1] - half_radius - fs_size[1] // 2,
+ ),
+ )
if mask & 1:
- pygame.draw.circle(self.surf, "cyan", (center[0] - half_radius, center[1] + half_radius), radius // 3)
+ pygame.draw.circle(
+ self.surf,
+ "cyan",
+ (center[0] - half_radius, center[1] + half_radius),
+ radius // 3,
+ )
if mask & (1 << 1):
- pygame.draw.circle(self.surf, "cyan", (center[0] + half_radius, center[1] + half_radius), radius // 3)
+ pygame.draw.circle(
+ self.surf,
+ "cyan",
+ (center[0] + half_radius, center[1] + half_radius),
+ radius // 3,
+ )
if mask == 3:
fs = self.font.render(str(self.v1), True, "black")
fs_size = fs.get_size()
- self.surf.blit(fs, (center[0] - half_radius - fs_size[0] // 2, center[1] + half_radius - fs_size[1] // 2))
+ self.surf.blit(
+ fs,
+ (
+ center[0] - half_radius - fs_size[0] // 2,
+ center[1] + half_radius - fs_size[1] // 2,
+ ),
+ )
fs = self.font.render(str(self.v2), True, "black")
fs_size = fs.get_size()
- self.surf.blit(fs, (center[0] + half_radius - fs_size[0] // 2, center[1] + half_radius - fs_size[1] // 2))
+ self.surf.blit(
+ fs,
+ (
+ center[0] + half_radius - fs_size[0] // 2,
+ center[1] + half_radius - fs_size[1] // 2,
+ ),
+ )
def finger_push(self, player, value):
setattr(self, "v1" if player == 0 else "v2", value)
16,
).draw(self.surf, "darkgray")
i = next_i
- rots = (-60, 0, 60, -60)[value["flipped"]:]
+ rots = (-60, 0, 60, -60)[value["flipped"] :]
for rot, part, label in zip(rots, (1, -3, 5), value["labels"]):
fs = self.font.render(label, True, "white")
if rot != 0:
Button(
self,
pygame.Rect(
- (rect.left, rect.bottom + i * rect.height), rect.size,
+ (rect.left, rect.bottom + i * rect.height),
+ rect.size,
),
entry,
partial(self.choose, i),
def draw(self):
surf_size = self.surf.get_size()
- fs = self.font.render(
- f"{int(self.current_fps)} FPS", True, self.FPS_COLOR
- )
+ fs = self.font.render(f"{int(self.current_fps)} FPS", True, self.FPS_COLOR)
fs_size = fs.get_size()
self.surf.blit(
fs, (surf_size[0] - fs_size[0] - 7, surf_size[1] - fs_size[1] - 7)
def get_blit_pos_center(self):
fs_size = self.font.size(self.value)
return (
- self.rect.centerx - fs_size[0] // 2, self.rect.centery - fs_size[1] // 2
+ self.rect.centerx - fs_size[0] // 2,
+ self.rect.centery - fs_size[1] // 2,
)
def get_blit_pos_right(self):
def __init__(self, device):
self.device = device
- self.touch_id = int(self.device.path[self.device.path.find("event") + 5:])
+ self.touch_id = int(self.device.path[self.device.path.find("event") + 5 :])
x_info = self.device.absinfo(ecodes.ABS_MT_POSITION_X)
y_info = self.device.absinfo(ecodes.ABS_MT_POSITION_Y)
self.info = {
def push_event(self, event_type, finger_new, finger_old):
x_info = self.info[ecodes.ABS_MT_POSITION_X]
y_info = self.info[ecodes.ABS_MT_POSITION_Y]
- x = (finger_new.get(self.x_lookup, x_info[1]) - x_info[0]) / (x_info[1] - x_info[0])
- y = (finger_new.get(self.y_lookup, x_info[1]) - y_info[0]) / (y_info[1] - y_info[0])
+ x = (finger_new.get(self.x_lookup, x_info[1]) - x_info[0]) / (
+ x_info[1] - x_info[0]
+ )
+ y = (finger_new.get(self.y_lookup, x_info[1]) - y_info[0]) / (
+ y_info[1] - y_info[0]
+ )
pygame.event.post(
pygame.event.Event(
event_type,
"y": y,
**(
{
- "dx": x - (
- finger_old.get(self.x_lookup, x_info[1]) - x_info[0]
- ) / x_info[1],
- "dy": y - (
- finger_old.get(self.y_lookup, y_info[1]) - y_info[0]
- ) / y_info[1],
- } if finger_old is not None else {"dx": 0.0, "dy": 0.0}
+ "dx": x
+ - (finger_old.get(self.x_lookup, x_info[1]) - x_info[0])
+ / x_info[1],
+ "dy": y
+ - (finger_old.get(self.y_lookup, y_info[1]) - y_info[0])
+ / y_info[1],
+ }
+ if finger_old is not None
+ else {"dx": 0.0, "dy": 0.0}
),
"evdev_event": finger_new.copy(),
**({"dropped": True} if self.dropped else {}),
- }
+ },
)
)
def handle_abs(self, event):
if event.code == ecodes.ABS_MT_SLOT:
self.slot = event.value
- elif event.code == ecodes.ABS_MT_TRACKING_ID and event.value == -1:
+ elif event.code == ecodes.ABS_MT_TRACKING_ID and event.value == -1:
self.current_finger().clear()
return
self.current_finger()[self.get_lookup(ecodes.ABS, event.code)] = event.value
code = ecodes.ABS[event.code]
elif event.type == ecodes.EV_MSC:
code = ecodes.MSC[event.code]
- elif event.type == ecodes.EV_KEY and event.code in {
- *ecodes.KEY, *ecodes.BTN
- }:
- code = ecodes.KEY.get(
- event.code, ecodes.BTN[event.code]
- )
+ elif event.type == ecodes.EV_KEY and event.code in {*ecodes.KEY, *ecodes.BTN}:
+ code = ecodes.KEY.get(event.code, ecodes.BTN[event.code])
else:
code = f"{ecodes.EV[event.type]}[{event.code}]"
print(ecodes.EV[event.type], code, event.value)
"pos": (
ev.pos[0] - self.rect.left + self.scroll_x,
ev.pos[1] - self.rect.top + self.scroll_y,
- )
+ ),
},
)
super().handle_event(ev)
(
min(self.rect.width, size[0] - self.scroll_x),
min(self.rect.height, size[1] - self.scroll_y),
- )
+ ),
)
)
super().__init__(parent)
self.rect = rect
self.direction = direction
- self.extent = (
- self._get_extent_base() - (1 if handle_size is None else handle_size)
+ self.extent = self._get_extent_base() - (
+ 1 if handle_size is None else handle_size
)
self.value = value
self.handle_size = handle_size
value = -value
limited = True
if value > self.extent:
- value = self.extent ** 2 // value
+ value = self.extent**2 // value
limited = True
return value, limited
button_size = (rect.height // 2, rect.height // 2)
self.text_input = TextInput(
self,
- pygame.Rect(
- rect.topleft, (rect.width - button_size[0], rect.height)
- ),
+ pygame.Rect(rect.topleft, (rect.width - button_size[0], rect.height)),
self.call_callback,
str(value),
re.compile(r"[-+]?\d*").fullmatch,
st = x * 2
st1 = st - 1
sgn = (st >= 1) * 2 - 1
- return (
- 2 ** (-sgn * 10 * st1 - 1)
- * sin((st1 - self.s) * tau / self.p)
- * sgn
- + (sgn > 0)
+ return 2 ** (-sgn * 10 * st1 - 1) * sin((st1 - self.s) * tau / self.p) * sgn + (
+ sgn > 0
)
self.surf,
pygame.Color(*(int(x * 255) for x in rgb)),
(base_left + eased_current * movement_width, self.rect.top + base_radius),
- base_radius
+ base_radius,
)
def set_value(self, value):
fs = self.font.render(self.value, True, "gray")
fs, self.offset, x = self.maybe_scroll_font_surface(
self.font,
- self.value[:self.cursor.pos],
+ self.value[: self.cursor.pos],
fs,
*self.padded_rect.size,
)
def key_delete(self):
value = self.value
if self.cursor.pos < len(value):
- self.value = f"{value[:self.cursor.pos]}{value[self.cursor.pos + 1:]}"
+ self.value = f"{value[: self.cursor.pos]}{value[self.cursor.pos + 1 :]}"
def filter_value(self, value):
if not self.value_filter:
def key_printable_unicode(self, unicode):
len_old_value = len(self.value)
- value = f"{self.value[:self.cursor.pos]}{unicode}{self.value[self.cursor.pos:]}"
+ value = (
+ f"{self.value[: self.cursor.pos]}{unicode}{self.value[self.cursor.pos :]}"
+ )
result = self.filter_value(value)
if isinstance(result, str):
value = result
def get_points(self):
return [
- (self.center[0] + cos(a) * self.radius, self.center[1] + sin(a) * self.radius)
+ (
+ self.center[0] + cos(a) * self.radius,
+ self.center[1] + sin(a) * self.radius,
+ )
for a in self.get_angle_segments(
self.start_angle,
self.end_angle,
- StrokeRoundLine.corners_needed_to_appear_round((self.radius + self.width / 2)),
+ StrokeRoundLine.corners_needed_to_appear_round(
+ (self.radius + self.width / 2)
+ ),
)
]
Enclose a rectangle fitted between two points with a regular, non-rotated n-gon
that should be visually indistinguishable with a half circle
"""
+
def __init__(self, p1, p2, width):
self.p1 = p1
self.p2 = p2
initial_corner = opposing_corner = num_vertices
back = (0, 0)
else:
- initial_corner = ceil(
- atan2(-delta[0], delta[1]) * num_vertices / tau
- )
+ initial_corner = ceil(atan2(-delta[0], delta[1]) * num_vertices / tau)
opposing_corner = (
floor(atan2(delta[0], -delta[1]) * num_vertices / tau) - initial_corner
) % num_vertices
return points
@staticmethod
- def corners_needed_to_appear_round(radius, threshold=.5):
+ def corners_needed_to_appear_round(radius, threshold=0.5):
return ceil(pi / acos(1 - threshold / radius))
def fit(self, pos, unit):
"""
Rotate a rectangle along the direction in which we're drawing.
"""
+
def __init__(self, p1, p2, width):
self.p1 = p1
self.p2 = p2
)
len_teams = len(self.teams)
# fits one column of memory destinations (todo)
- #assert len_teams < 15 and len_teams % 2 == 0, len_teams
+ # assert len_teams < 15 and len_teams % 2 == 0, len_teams
self.num_pairs = len_teams // 2
self.failed = 0
self.successful = 0
self.num_pairs_label.enabled = False
self.num_pairs.enabled = False
available_teams = list(self.teams)
- for child in self.memory_destinations[:2 * self.num_pairs.value]:
+ for child in self.memory_destinations[: 2 * self.num_pairs.value]:
child.enabled = True
child.highlight = False
child.team = choice(available_teams)
self.place_memory_card(memory_card.rect)
while any(
c.rect.colliderect(memory_card.rect)
- for c in self.memory_cards if c != memory_card
+ for c in self.memory_cards
+ if c != memory_card
):
self.place_memory_card(memory_card.rect)
self.dirty = True
from math import cos, pi, sin, tau
from vectors import (
- Polygon, Rect, Shapes, StrokeCircleSegment, StrokeRoundLine, StrokeSquareLine
+ Polygon,
+ Rect,
+ Shapes,
+ StrokeCircleSegment,
+ StrokeRoundLine,
+ StrokeSquareLine,
)
1,
),
StrokeCircleSegment(
- (4, 13), FINGER_RADIUS, tau * 3 / 8, tau * 7 / 8, 1,
+ (4, 13),
+ FINGER_RADIUS,
+ tau * 3 / 8,
+ tau * 7 / 8,
+ 1,
),
StrokeRoundLine(
(
StrokeCircleSegment((8.25, 6), FINGER_RADIUS, pi, tau, 1),
StrokeRoundLine((9.5, 6), (9.5, 11), 1),
StrokeCircleSegment(
- (11, 11.5), FINGER_RADIUS, tau * 5 / 8, tau * 7 / 8, 1,
+ (11, 11.5),
+ FINGER_RADIUS,
+ tau * 5 / 8,
+ tau * 7 / 8,
+ 1,
),
StrokeCircleSegment(
- (13.25, 12), FINGER_RADIUS, tau * 5 / 8, tau * 7 / 8, 1,
+ (13.25, 12),
+ FINGER_RADIUS,
+ tau * 5 / 8,
+ tau * 7 / 8,
+ 1,
),
StrokeCircleSegment(
- (15.5, 12.5), FINGER_RADIUS, tau * 5 / 8, tau, 1,
+ (15.5, 12.5),
+ FINGER_RADIUS,
+ tau * 5 / 8,
+ tau,
+ 1,
),
StrokeRoundLine((16.75, 12.5), (17, 16), 1),
StrokeCircleSegment((8.25, 6), 3, pi, tau, 1),
MM_SIZE_PATTERN = re.compile(r"(\d+)mm x (\d+)mm")
DIRECTIONS = ("normal", "left", "inverted", "right", "invalid direction")
REFLECTIONS = (
- "none", "[Xx] axis", "[Yy] axis", "X and Y axis", "invalid reflection"
+ "none",
+ "[Xx] axis",
+ "[Yy] axis",
+ "X and Y axis",
+ "invalid reflection",
)
DIRECTIONS_REFLECTIONS_PATTERN = re.compile(
f"({'|'.join(DIRECTIONS)})( {'|'.join(REFLECTIONS)})? \\("
{
"name": name,
"size": cls.int_tuple(cls.strip_each(size.split("x"))),
- } for name, size in (
+ }
+ for name, size in (
cls.strip_each(p.split(" ", 1))
for p in cls.strip_each(sizes.split(","))
)
name, connected, rest = self.strip_each(line.split(" ", 2))
output = {
"name": name,
- "connected": self.CONNECTED_MAPPING.get(
- connected, "unknown connection"
- ),
+ "connected": self.CONNECTED_MAPPING.get(connected, "unknown connection"),
}
if output["connected"] is False:
return output
if self.simple or resolution is None:
return output
parsed = self.int_tuple(resolution.group(i) for i in range(1, 5))
- direction_reflection = (
- self.DIRECTIONS_REFLECTIONS_PATTERN.search(rest)
- )
+ direction_reflection = self.DIRECTIONS_REFLECTIONS_PATTERN.search(rest)
end = direction_reflection.end()
output.update(
{
"available_rotations_reflections": [
m.group(0)
for m in self.AVAILABLE_DIRECTIONS_REFLECTIONS_PATTERN.finditer(
- rest[end:rest.find(")", end)]
+ rest[end : rest.find(")", end)]
)
],
- "modes": []
+ "modes": [],
}
)
mm_size = self.MM_SIZE_PATTERN.search(rest)
if mm_size:
- output["mm_size"] = (
- int(mm_size.group(1)), int(mm_size.group(2))
- )
+ output["mm_size"] = (int(mm_size.group(1)), int(mm_size.group(2)))
return output
@classmethod
def get_conf(self):
screens = []
current_screen = None
- lines = subprocess.check_output(
- ["xrandr", "--verbose"], text=True
- ).split(os.linesep)
+ lines = subprocess.check_output(["xrandr", "--verbose"], text=True).split(
+ os.linesep
+ )
for i, line in enumerate(lines):
if not line:
continue
output = screens[current_screen]["outputs"][-1]
if line[3] == " " or "modes" not in output:
continue
- output["modes"].append(self.parse_mode(*lines[i:i + 3]))
+ output["modes"].append(self.parse_mode(*lines[i : i + 3]))
return screens
@classmethod
def call(cls, output, *args, **kwargs):
args = [f"--{arg}" for arg in args]
for key, value in kwargs.items():
- args.extend((f"--{key.replace("_", "-")}", value))
+ args.extend((f"--{key.replace('_', '-')}", value))
return subprocess.run(["xrandr", "--output", cls.OUTPUTS[output], *args])
def renew(self):
self,
pygame.Rect((128, 612), (256, 128)),
self.bluetooth_conf.update,
- self.bluetooth_conf.conf
+ self.bluetooth_conf.conf,
)
touch_switch = Switch(
self,
laptop_single.fit((100, top + 32), (16, 16)),
pygame.Rect((68, top), (416, 416)),
None,
- partial(
- self.laptop_cb, "single", bt_switch, touch_switch, stylus_switch
- ),
+ partial(self.laptop_cb, "single", bt_switch, touch_switch, stylus_switch),
self.xrandr_conf.is_active("single"),
)
self.double_button = IconButton(
laptop_double.fit((600, top + 32), (16, 16)),
pygame.Rect((568, top), (416, 416)),
None,
- partial(
- self.laptop_cb, "double", bt_switch, touch_switch, stylus_switch
- ),
+ partial(self.laptop_cb, "double", bt_switch, touch_switch, stylus_switch),
self.xrandr_conf.is_active("double"),
)
self.vertical_button = IconButton(
self,
pygame.Rect((784, touch_switch.rect.top), (384, 128)),
"Re-apply",
- partial(self.xinput_conf.reapply_by_type, "touchpad")
+ partial(self.xinput_conf.reapply_by_type, "touchpad"),
)
Button(
self,
pygame.Rect((784, stylus_switch.rect.top), (384, 128)),
"Re-apply",
- partial(self.xinput_conf.reapply_by_type, "stylus")
+ partial(self.xinput_conf.reapply_by_type, "stylus"),
)
Button(
self,