Skip to content

Commit

Permalink
Reformatted some line lengths
Browse files Browse the repository at this point in the history
  • Loading branch information
davecom committed Jul 14, 2024
1 parent 424c83a commit 149e255
Show file tree
Hide file tree
Showing 23 changed files with 213 additions and 141 deletions.
3 changes: 2 additions & 1 deletion Brainfuck/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
if __name__ == "__main__":
# Parse the file argument
file_parser = ArgumentParser("NanoBASIC")
file_parser.add_argument("brainfuck_file", help="A text file containing Brainfuck source code.")
file_parser.add_argument("brainfuck_file",
help="A file containing Brainfuck source code.")
arguments = file_parser.parse_args()
Brainfuck(arguments.brainfuck_file).execute()
4 changes: 2 additions & 2 deletions Brainfuck/brainfuck.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def execute(self):
instruction_index = self.find_bracket_match(instruction_index, False)
instruction_index += 1

# Find the location of the corresponding matching bracket to the one at *start*
# Find the location of the corresponding bracket to the one at *start*
# If *forward* is true go to the right looking for a matching "]"
# Otherwise do the reverse
def find_bracket_match(self, start: int, forward: bool) -> int:
Expand All @@ -66,7 +66,7 @@ def find_bracket_match(self, start: int, forward: bool) -> int:
in_between_brackets += 1
location += direction
# Didn't find a match
print(f"Error: could not find matching bracket for {start_bracket} at {start}.")
print(f"Error: could not find match for {start_bracket} at {start}.")
return start


Expand Down
11 changes: 7 additions & 4 deletions Chip8/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@
def run(program_data: bytes, name: str):
# Startup Pygame, create the window, and load the sound
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SCALED)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT),
pygame.SCALED)
pygame.display.set_caption(f"Chip8 - {os.path.basename(name)}")
bee_sound = pygame.mixer.Sound(os.path.dirname(os.path.realpath(__file__)) + "/bee.wav")
bee_sound = pygame.mixer.Sound(os.path.dirname(os.path.realpath(__file__))
+ "/bee.wav")
currently_playing_sound = False
vm = VM(program_data) # Load the virtual machine with the program data
timer_accumulator = 0.0 # Used to limit the timer to 60 Hz
Expand Down Expand Up @@ -63,7 +65,7 @@ def run(program_data: bytes, name: str):

# Handle timing
frame_end = timer()
frame_time = frame_end - frame_start # time it took for this iteration in seconds
frame_time = frame_end - frame_start # time it took in seconds
timer_accumulator += frame_time
# Every 1/60 of a second decrement the timers
if timer_accumulator > TIMER_DELAY:
Expand All @@ -79,7 +81,8 @@ def run(program_data: bytes, name: str):
if __name__ == "__main__":
# Parse the file argument
file_parser = ArgumentParser("Chip8")
file_parser.add_argument("rom_file", help="A file containing a Chip-8 game.")
file_parser.add_argument("rom_file",
help="A file containing a Chip-8 game.")
arguments = file_parser.parse_args()
with open(arguments.rom_file, "rb") as fp:
file_data = fp.read()
Expand Down
22 changes: 13 additions & 9 deletions Chip8/vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ def __init__(self, program_data: bytes):
# ours can just be unlimited and expand/contract as needed
self.stack = []
# Graphics buffer for the screen - 64 x 32 pixels
self.display_buffer = np.zeros((SCREEN_WIDTH, SCREEN_HEIGHT), dtype=np.uint32)
self.display_buffer = np.zeros((SCREEN_WIDTH, SCREEN_HEIGHT),
dtype=np.uint32)
self.needs_redraw = False
# Timers - really simple registers that count down to 0 at 60 hertz
self.delay_timer = 0
Expand All @@ -100,9 +101,9 @@ def decrement_timers(self):
def play_sound(self) -> bool:
return self.sound_timer > 0

# Draw a sprite at *x*, *y* using data at *i* and with a height of *height*
# Draw a sprite at *x*, *y* using data at *i* with a height of *height*
def draw_sprite(self, x: int, y: int, height: int):
flipped_black = False # did drawing this flip any pixels from white to black?
flipped_black = False # did drawing this flip any pixels?
for row in range(0, height):
row_bits = self.ram[self.i + row]
for col in range(0, SPRITE_WIDTH):
Expand All @@ -112,11 +113,13 @@ def draw_sprite(self, x: int, y: int, height: int):
continue # Ignore off-screen pixels
new_bit = (row_bits >> (7 - col)) & 1
old_bit = self.display_buffer[px, py] & 1
if new_bit & old_bit: # If both are set, they will get flipped white -> black
if new_bit & old_bit: # If both set, flip white -> black
flipped_black = True
new_pixel = new_bit ^ old_bit # Chip 8 draws by XORing, which flips everything
# Chip 8 draws by XORing, which flips everything
new_pixel = new_bit ^ old_bit
self.display_buffer[px, py] = WHITE if new_pixel else BLACK
self.v[0xF] = 1 if flipped_black else 0 # set flipped flag for collision detection
# set flipped flag for collision detection
self.v[0xF] = 1 if flipped_black else 0

def step(self):
# we look at the opcode in terms of its nibbles (4 bit pieces)
Expand All @@ -139,7 +142,7 @@ def step(self):
self.pc = self.stack.pop()
jumped = True
case (0x0, n1, n2, n3): # call program
self.pc = concat_nibbles(n1, n2, n3) # go to program start
self.pc = concat_nibbles(n1, n2, n3) # go to start
# clear registers
self.delay_timer = 0
self.sound_timer = 0
Expand All @@ -153,7 +156,7 @@ def step(self):
self.pc = concat_nibbles(n1, n2, n3)
jumped = True
case (0x2, n1, n2, n3): # call subroutine
self.stack.append(self.pc + 2) # return location onto the stack
self.stack.append(self.pc + 2) # put return place on stack
self.pc = concat_nibbles(n1, n2, n3) # goto subroutine
jumped = True
case (0x3, x, _, _): # conditional skip v[x] equal last2
Expand Down Expand Up @@ -261,7 +264,8 @@ def step(self):
for r in range(0, x + 1):
self.v[r] = self.ram[self.i + r]
case _:
print(f"Unknown opcode {(hex(first), hex(second), hex(third), hex(fourth))}!")
print(f"Unknown opcode {(hex(first), hex(second),
hex(third), hex(fourth))}!")

if not jumped:
self.pc += 2 # increment program counter
12 changes: 6 additions & 6 deletions Impressionist/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@
if __name__ == "__main__":
# Parse the file argument
argument_parser = ArgumentParser("Impressionist")
argument_parser.add_argument("image_file", help="The input image to be painted.")
argument_parser.add_argument("output_file", help="The final resulting abstract art image.")
argument_parser.add_argument("image_file", help="The input image")
argument_parser.add_argument("output_file", help="The resulting abstract art")
argument_parser.add_argument('-t', '--trials', type=int, default=10000,
help='The number of trials to run (default 10000).')
argument_parser.add_argument('-m', '--method', choices=['random', 'average', 'common'],
default='average',
argument_parser.add_argument('-m', '--method',
choices=['random', 'average', 'common'], default='average',
help='Shape color determination method (default average).')
argument_parser.add_argument('-s', '--shape', choices=['ellipse', 'triangle',
'quadrilateral', 'line'], default='ellipse',
help='The shape type to use (default ellipse).')
'quadrilateral', 'line'],
default='ellipse', help='The shape type (default ellipse).')
argument_parser.add_argument('-l', '--length', type=int, default=256,
help='The length of the final image in pixels (default 256).')
argument_parser.add_argument('-v', '--vector', default=False, action='store_true',
Expand Down
2 changes: 1 addition & 1 deletion Impressionist/impressionist.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def experiment() -> bool:
return False

if experiment():
# Try expanding every direction, keep expanding in any directions that are better
# Try expanding every direction, keep going in better directions
for index in range(len(coordinates)):
for amount in (-1, 1):
while True:
Expand Down
3 changes: 2 additions & 1 deletion Impressionist/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ def __init__(self, width: int, height: int, background_color: tuple[int, int, in

def draw_ellipse(self, x1: int, y1: int, x2: int, y2: int, color: tuple[int, int, int]):
self.content += f'<ellipse cx="{(x1 + x2) // 2}" cy="{(y1 + y2) // 2}" ' \

Check failure on line 25 in Impressionist/svg.py

View workflow job for this annotation

GitHub Actions / build (3.12)

Object of type "str" is not callable   Attribute "__call__" is unknown (reportCallIssue)
f'rx="{abs(x1 - x2) // 2}" ry="{abs(y1 - y2) // 2}" fill="rgb{color}" />\n'
(f'rx="{abs(x1 - x2) // 2}" ry="{abs(y1 - y2) // 2}'
f'" fill="rgb{color}" />\n')

def draw_line(self, x1: int, y1: int, x2: int, y2: int, color: tuple[int, int, int]):
self.content += f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="rgb{color}" ' \
Expand Down
9 changes: 6 additions & 3 deletions KNN/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,16 @@

def run():
# Create a 2D array of pixels to represent the digit
digit_pixels = np.zeros((PIXEL_HEIGHT, PIXEL_WIDTH, 3), dtype=np.uint32)
digit_pixels = np.zeros((PIXEL_HEIGHT, PIXEL_WIDTH, 3),
dtype=np.uint32)
# Load the training data
os.chdir(os.path.dirname(os.path.abspath(__file__)))
digits_knn = KNN(Digit, './datasets/digits/digits.csv', has_header=False)
digits_knn = KNN(Digit, './datasets/digits/digits.csv',
has_header=False)
# Startup Pygame, create the window
pygame.init()
screen = pygame.display.set_mode(size=(PIXEL_WIDTH, PIXEL_HEIGHT), flags=pygame.SCALED | pygame.RESIZABLE)
screen = pygame.display.set_mode(size=(PIXEL_WIDTH, PIXEL_HEIGHT),
flags=pygame.SCALED | pygame.RESIZABLE)
pygame.display.set_caption("Digit Recognizer")
while True:
pygame.surfarray.blit_array(screen, digit_pixels)
Expand Down
6 changes: 4 additions & 2 deletions KNN/fish.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def from_string_data(cls, data: list[str]) -> Self:
height=float(data[5]), width=float(data[6]))

def distance(self, other: Self) -> float:
return ((self.length1 - other.length1) ** 2 + (self.length2 - other.length2) ** 2 +
(self.length3 - other.length3) ** 2 + (self.height - other.height) ** 2 +
return ((self.length1 - other.length1) ** 2 +
(self.length2 - other.length2) ** 2 +
(self.length3 - other.length3) ** 2 +
(self.height - other.height) ** 2 +
(self.width - other.width) ** 2) ** 0.5
14 changes: 9 additions & 5 deletions KNN/knn.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ def distance(self, other: Self) -> float: ...


class KNN[DP: DataPoint]:
def __init__(self, data_point_type: type[DP], file_path: str, has_header: bool = True) -> None:
def __init__(self, data_point_type: type[DP], file_path: str,
has_header: bool = True) -> None:
self.data_point_type = data_point_type
self.data_points = []
self._read_csv(file_path, has_header)
Expand All @@ -41,9 +42,10 @@ def _read_csv(self, file_path: str, has_header: bool) -> None:
if has_header:
_ = next(reader)
for row in reader:
self.data_points.append(self.data_point_type.from_string_data(row))
self.data_points.append(
self.data_point_type.from_string_data(row))

# Find the k nearest neighbors of a given data point based on the distance method
# Find the k nearest neighbors of a given data point
def nearest(self, k: int, data_point: DP) -> list[DP]:
return sorted(self.data_points, key=data_point.distance)[:k]

Expand All @@ -57,10 +59,12 @@ def classify(self, k: int, data_point: DP) -> str:
# Find the average of that property from the neighbors and return it
def predict(self, k: int, data_point: DP, property_name: str) -> float:
neighbors = self.nearest(k, data_point)
return sum([getattr(neighbor, property_name) for neighbor in neighbors]) / len(neighbors)
return (sum([getattr(neighbor, property_name) for neighbor in neighbors])
/ len(neighbors))

# Predict a NumPy array property of a data point based on the k nearest neighbors
# Find the average of that property from the neighbors and return it
def predict_array(self, k: int, data_point: DP, property_name: str) -> np.ndarray:
neighbors = self.nearest(k, data_point)
return np.sum([getattr(neighbor, property_name) for neighbor in neighbors], axis=0) / len(neighbors)
return (np.sum([getattr(neighbor, property_name) for neighbor in neighbors], axis=0)
/ len(neighbors))
3 changes: 2 additions & 1 deletion NESEmulator/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ def run(rom: ROM, name: str):
if __name__ == "__main__":
# Parse the file argument
file_parser = ArgumentParser("NESEmulator")
file_parser.add_argument("rom_file", help="A file containing an NES game in iNES format.")
file_parser.add_argument("rom_file",
help="An NES game file in iNES format.")
arguments = file_parser.parse_args()
game = ROM(arguments.rom_file)
run(game, arguments.rom_file)
Loading

0 comments on commit 149e255

Please sign in to comment.