Last active
February 11, 2024 12:16
-
-
Save alanbchristie/716596cd8d174beeb62a4fd67fd3a70f to your computer and use it in GitHub Desktop.
Code generator for key code locks from BorgLocks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Simple class to generate keypad codes for Borg door locks. | |
Run this code to generate random 4 and 5 digit codes. | |
Each random code is generated once with, and once without using the X and Z buttons. | |
See https://borglocks.co.uk | |
""" | |
import random | |
class BorgCode: | |
def __init__(self) -> None: | |
self._key_choice = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] | |
def generate_code( | |
self, | |
*, | |
length: int = 4, | |
include_xz: bool = True, | |
render_vertical_sequence: bool = True, | |
) -> str: | |
key_choice = self._key_choice.copy() | |
code = [] | |
for _ in range(length): | |
choice = random.choice(key_choice) | |
code.append(choice) | |
key_choice.remove(choice) | |
if render_vertical_sequence: | |
# Move the sequence so it reflects the position | |
# on a typical 12-button lock i.e. top to bottom and left to right: - | |
# 1 | 6 | |
# 2 | 7 | |
# 3 | 8 | |
# 4 | 9 | |
# 5 | 0 | |
# So, when we generate the code '4589X' (for example) we should | |
# present it to the user as '8495X'? | |
for digit in ["1", "6", "2", "7", "3", "8", "4", "9", "5", "0"]: | |
if digit in code: | |
code.remove(digit) | |
code.append(digit) | |
else: | |
# Numerical order, zero at the end. | |
code.sort() | |
if "0" in code: | |
code.remove("0") | |
code.append("0") | |
# If including 'x' and 'z'? | |
# do this at random (50:50) | |
if include_xz: | |
code.append(random.choice(["X", "Z"])) | |
# Return the code. | |
# Codes always begin with "C" (clear) | |
return f"C{''.join(code)}" | |
if __name__ == "__main__": | |
borg_code = BorgCode() | |
print("---") | |
print(borg_code.generate_code(include_xz=False)) | |
print(borg_code.generate_code()) | |
print(borg_code.generate_code(length=5)) | |
print(borg_code.generate_code(length=5, include_xz=False)) | |
# And some 'naturally' ordered codes | |
print("---") | |
print(borg_code.generate_code(render_vertical_sequence=False)) | |
print(borg_code.generate_code(include_xz=False, render_vertical_sequence=False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment