From: Skullheadx <704277@pdsb.net> Date: Wed, 25 Jan 2023 04:36:08 +0000 (-0500) Subject: add visuals X-Git-Url: http://git.skullheadx.com/nixos/projects.html?a=commitdiff_plain;h=06a1d0d655188248add7b3732d2b7098aad7598b;p=Sorting.git add visuals --- diff --git a/display.py b/display.py index 57b9e6c..66f1634 100644 --- a/display.py +++ b/display.py @@ -1,21 +1,28 @@ import pygame - pygame.init() +pygame.display.set_caption("sorting visuals") + BLACK = (0, 0, 0) GRAY = (128, 128, 128) WHITE = (255, 255, 255) class Display: - WIDTH, HEIGHT = 640, 640 + WIDTH, HEIGHT = 1080, 720 DIMENSIONS = (WIDTH, HEIGHT) - FPS = 60 + FPS = 0 + + DELAY_TIME = 0 - def __init__(self): + def __init__(self, frames): self.screen = pygame.display.set_mode(self.DIMENSIONS) self.clock = pygame.time.Clock() + self.frames = frames + self.index = 0 + self.time = 0 + def show(self): is_running = True @@ -33,6 +40,17 @@ class Display: def update(self): delta = self.clock.tick(self.FPS) + self.time += delta + if self.time > self.DELAY_TIME: + self.time = 0 + self.index = min(len(self.frames) - 1, self.index + 1) def draw(self, surf): - surf.fill(GRAY) + surf.fill(WHITE) + + width = self.WIDTH / len(self.frames[self.index]) + height = self.HEIGHT / max(self.frames[self.index]) + + for i, element in enumerate(self.frames[self.index]): + r = pygame.Rect(i * width, self.HEIGHT - element * height + 1, width + 1, element * height) + pygame.draw.rect(surf, BLACK, r) diff --git a/main.py b/main.py index cd3b9c2..f943f79 100644 --- a/main.py +++ b/main.py @@ -1,8 +1,11 @@ +import random from display import Display - +from sorting_algorithms.bubble_sort import bubble_sort, bubble_sort_frames def main(): - window = Display() + array = [random.randint(10, 50) for _ in range(75)] + frames = bubble_sort_frames(array) + window = Display(frames) window.show() diff --git a/sorting_algorithms/bubble_sort.py b/sorting_algorithms/bubble_sort.py index e387e2f..aa81519 100644 --- a/sorting_algorithms/bubble_sort.py +++ b/sorting_algorithms/bubble_sort.py @@ -1,5 +1,5 @@ # Bubble Sort (O(n^2)) -from utils import swap +from sorting_algorithms.utils import swap def bubble_sort(array): @@ -12,3 +12,15 @@ def bubble_sort(array): if is_sorted: # break out if already sorted break return array # return sorted array +def bubble_sort_frames(array): + frames = [] + for top in range(len(array) - 1, 0, -1): # loop through each element from end + is_sorted = True # to end early if already sorted + for index in range(top): # loop through each of elements until reach top + if array[index] > array[index + 1]: # if greater, swap + swap(array, index, index + 1) # swap with next + is_sorted = False # reset to not sorted + frames.append(array[:]) + if is_sorted: # break out if already sorted + break + return frames # return sorted array