2016-03-01 143 views
0

我已经在pygame中编写了一个简单的突破游戏,并正在编写一个关卡编辑器。一切工作,直到我试图添加一个具有透明外观的选择矩形(就像我的桌面背景)。我可以得到一个矩形(多少),但其他一切都消失了,而且不是半透明的。pygame:用鼠标绘制一个选择矩形

代码:

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() 

矩形不透明,其他的东西都会消失在屏幕上?我哪里错了?

回答

0

我不确定.convert_alpha()是否会像您想象的那样创建透明屏幕。尝试明确设置上mousescreen阿尔法水平:

mousescreen = pygame.Surface((screen.get_size())) 
mousescreen.set_alpha(100) # this value doesn't have to be 100 

另一种方式来达到同样的效果是吸引你的矩形直接4线到,这意味着你不必有mousescreen在所有的屏幕。在您的更新屏功能:

if mousedrag: 
    mouseRectCorners = [mouseRect.topleft, 
         mouseRect.topright, 
         mouseRect.bottomright, 
         mouseRect.bottomleft] 
    pygame.draw.lines(screen, RED, True, mouseRectCorners, 50) 

只要确保你的任何其他对象后得出这些线路或者他们可能会隐藏。我不确定这个选项是否被认为是最佳实践,但总是有很好的选择。