[英]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.