[英]pygame: drawing a selection rectangle with the mouse
我已经在pygame中编写了一个简单的突破游戏,并且正在编写一个关卡编辑器。 一切正常,直到我尝试添加一个具有透明外观的选择矩形(例如桌面背景上的矩形)。 我可以得到一个矩形(sorta),但其他所有元素都消失了,并且不是半透明的。
码:
pygame.init()
screen = pygame.display.set_mode(size)
mousescreen = pygame.Surface((screen.get_size())).convert_alpha()
...
在设计循环中:
global xpos, ypos, theBricks, clock, mousedrag, mouseRect
global designing, titles
global theLevels, level, cur_max_level, max_level
mousedrag = False
mouseRect = None
mouseDown = False
while designing:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouseDown = True
mpos = pygame.mouse.get_pos()
x_position = mpos[0]
y_position = mpos[1]
xpos = ((x_position-left)/BRW) * BRW + left
ypos = ((y_position-top)/BRH) * BRH + top
elif event.type == MOUSEMOTION:
if mouseDown:
newx_pos = mpos[0]
newy_pos = mpos[1]
mousedrag = True
if mousedrag:
mouseRect = Rect(newx_pos, newy_pos, xpos, ypos)
elif event.type == MOUSEBUTTONUP:
if mousedrag:
mousedrag = False
else:
if is_a_brick(xpos, ypos):
del_brick(xpos, ypos)
else:
make_brick(xpos, ypos)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
designing = False
titles = True
...
在更新屏幕功能中:
for bricks in theBricks:
pygame.draw.rect(screen, GREEN, bricks.rect)
if mousedrag:
pygame.draw.rect(mousescreen, RED, mouseRect, 50)
screen.blit(mousescreen, (0,0))
pygame.draw.rect(screen, WHITE, (xpos, ypos, BRW, BRH))
pygame.display.update()
矩形不是透明的,其他所有内容都从屏幕上消失了吗? 我要去哪里错了?
我不确定.convert_alpha()是否会像您想象的那样创建透明屏幕。 尝试在鼠标屏幕上明确设置Alpha级别:
mousescreen = pygame.Surface((screen.get_size()))
mousescreen.set_alpha(100) # this value doesn't have to be 100
实现相同效果的另一种方法是将您的rect作为4条线直接绘制到屏幕上,这意味着您根本不需要鼠标屏幕。 在更新屏幕功能中:
if mousedrag:
mouseRectCorners = [mouseRect.topleft,
mouseRect.topright,
mouseRect.bottomright,
mouseRect.bottomleft]
pygame.draw.lines(screen, RED, True, mouseRectCorners, 50)
只需确保在其他任何对象之后绘制这些线,否则它们可能会被隐藏。 我不确定该选项是否真的被认为是最佳实践,但是拥有选项总是很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.