【问题标题】:I want to make a sorting Visualizer, the sort works but visualizer doesnot我想做一个排序可视化器,排序有效,但可视化器没有
【发布时间】:2020-09-30 17:58:42
【问题描述】:

正如标题所说,我想用 python 和 pygame 创建一个可视化的冒泡排序。排序工作完美,但在将其可视化时,它永远不会得到正确的输出。

排序工作完美,但屏幕栏不会交换。 我还添加了一些颜色以更好地理解代码...

代码:-

import pygame
import random

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

L = []
rect = []
n = 10  # n belongs till [50,220]
WidthOfEachBar = 800 // (n + 1)


class Rect:
    def __init__(self, x, y, width, height):
        self.X = x
        self.Y = y
        self.width = width
        self.height = height
        self.colour = BLACK

    def show(self):
        pygame.draw.rect(screen, self.colour, (self.X, self.Y, self.width, self.height))

    def changeCol(self, colour):
        self.colour = colour


def array(n_):
    global L
    arr = [(3 * i) for i in range(1, n_ + 1)]
    for a in range(n_):
        random_no = random.choice(arr)
        L.append(random_no + 10)
        arr.remove(random_no)


array(n)

for i in range(n):
    x = 50 + (i + 1) * (1 + WidthOfEachBar)
    y = 680 - L[i]
    rect.append(Rect(x, y, WidthOfEachBar, L[i]))


def swap(a, b):
    global rect
    rect[a], rect[b] = rect[b], rect[a]


def bubble_sort():
    global n, rect
    for ii1 in range(n):
        for j in range(n - 1):
            rect[j].colour = GREEN
            rect[j + 1].colour = GREEN

            if rect[j].height > rect[j + 1].height:
                # print(r[j].X, r[j + 1].X)
                swap(j, j + 1)
                # print(r[j].X, r[j + 1].X)
                for amb in range(n):
                    print(rect[amb].height, end=" ")
                print()
            screen.fill(WHITE)
            for no1 in range(n):
                rect[no1].show()
            pygame.time.delay(0)
            pygame.display.update()
            rect[j].colour = BLACK
            rect[j + 1].colour = BLACK


pygame.init()
screen = pygame.display.set_mode((1000, 700))
pygame.display.set_caption("SORTING VISUALS")
is_sorted = False
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill(WHITE)
    if not is_sorted:
        bubble_sort()
    pygame.display.update()

这里的屏幕每次都会更新,但我无法理解问题所在。 代码很可疑,我知道,但任何帮助都会很棒

【问题讨论】:

    标签: python pygame bubble-sort


    【解决方案1】:

    您的代码中的问题是您正在交换列表中的元素,但相应的矩形并没有改变它们的位置。你应该改变你的swap 函数:

    def swap(a, b):
        global rect
        rect[a], rect[b] = rect[b], rect[a]
        rect[a].X, rect[b].X = rect[b].X, rect[a].X
    

    现在这将交换列表中的元素以及交换其对应矩形的位置。

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 2021-12-31
      • 2022-01-23
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      相关资源
      最近更新 更多