【发布时间】:2022-08-14 15:58:53
【问题描述】:
我正在尝试制作一个 python 程序来绘制一条线并使用 pygame 将它变成一个带有动画的圆圈,但我什至还没有完成绘图线代码。我注意到python正在更改列表中的错误或两个项目,该列表包含用户按下左键时的起点,存储为第一项,用户鼠标的当前点作为第二项。
这通常是我想要它做的:https://youtu.be/vlqZ0LubXCA
以下是有和没有更新第二项的行的结果:
和:
没有:
如您所见,或在描述中阅读,该行是覆盖前一帧所必需的。
我用箭头标记了改变结果的行:
import pygame, PIL, random
print(\'\\n\')
#data
bubbles = []
color_options = [[87, 184, 222]]
pressed = False
released = False
bubline_start = []
background = [50, 25, 25]
size = [500, 500]
#pygame
display = pygame.display.set_mode(size)
pygame.init()
#functions
def new_bub_color():
color_index = random.randint(0, len(color_options)-1)
lvl = random.randrange(85, 115)
bub_color = []
for val in color_options[color_index]:
bub_color.append(val*(lvl/100))
return bub_color
def bubble_line():
global display, pressed, bubline_start, released, bubbles, color_options
if len(bubbles) > 0:
if not bubbles[-1][0] == 0:
#first frame of click
bub_color = new_bub_color()
bubbles.append([0, bub_color, [bubline_start, list(pygame.mouse.get_pos())]])
pygame.draw.line(display, bub_color, bubline_start, pygame.mouse.get_pos())
else:
#draw after drags
pygame.draw.line(display, bubbles[-1][1], bubbles[-1][2][0], list(pygame.mouse.get_pos()))
bubbles[-1][2][1] = list(pygame.mouse.get_pos())# <-- HERE
else:
#first bubble
bub_color = new_bub_color()
bubbles.append([0, bub_color, [bubline_start, list(pygame.mouse.get_pos())]])
pygame.draw.line(display, bub_color, bubline_start, pygame.mouse.get_pos())
if released:
bubbles[-1][0] = 1
bubbles[-1][2][1] = list(pygame.mouse.get_pos())# <-- HERE
released = False
def cover_prev_frame():
global bubbles, background, size
min_pos = []
max_pos = []
for bubble in bubbles:
min_pos = bubble[2][0]
max_pos = bubble[2][0]
for point in bubble[2]:
#x min and max
if point[0] < min_pos[0]:
min_pos[0] = point[0]
elif point[0] > max_pos[0]:
max_pos[0] = point[0]
#y min and max
if point[1] < min_pos[1]:
min_pos[1] = point[1]
elif point[1] > max_pos[1]:
max_pos[1] = point[1]
max_pos = [max_pos[0]-min_pos[0]+1, max_pos[1]-min_pos[1]+1]
if type(background) == str:
#image background
later = True
elif type(background) == list:
#solid color background
pygame.draw.rect(display, background, pygame.Rect(min_pos, max_pos))
while True:
pygame.event.pump()
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN and not pressed:
bubline_start = list(pygame.mouse.get_pos())
pressed = True
elif event.type == pygame.MOUSEBUTTONUP and pressed:
pressed = False
released = True
cover_prev_frame()
if pressed or released:
bubble_line()
try:
pygame.display.update()
except:
break
-
您的代码中只有一个
bubline_start列表。bubbles数组中的每个条目都有一个对该列表的引用。如果您更改bubline_start,则会更改列表中的每个条目。我怀疑你想让bubline_start[:]制作一个新副本。 -
我不知道 python 做到了,我假设是 3.x 的一部分。但是问题仍然存在,我标记的行仍在更改列表中第一项的值,当我写它来更改第二项时,只有第二项。
-
FWIW,这就是 Python 从一开始就工作的方式。这是最常见的 Python 程序员错误之一。您可能会考虑创建一个
class Bubble来保存所有气泡状态信息,这样您就不必执行[-1][2][1]。 -
你要这个画什么?
标签: python list pygame nested-lists