2017-06-03 71 views
0

我想繪製5個矩形,我可以在屏幕上拖放所有的矩形。我正在使用pygame。我設法使1個矩形,我可以拖放,但我不能5.做這是我的代碼:5個矩形,你可以拖放

import pygame 
from pygame.locals import * 
from random import randint 


SCREEN_WIDTH = 1024 
SCREEN_HEIGHT = 768 

BLACK = ( 0, 0, 0) 
WHITE = (255, 255, 255) 
RED = (255, 0, 0) 
pygame.init() 

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) 
screen_rect = screen.get_rect() 

pygame.display.set_caption("Moving circles") 

rectangle = pygame.rect.Rect(20,20, 17, 17) 
rectangle_draging = False 


clock = pygame.time.Clock() 

running = True 

while running: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 

     elif event.type == pygame.MOUSEBUTTONDOWN: 
      if event.button == 1:    
       if rectangle.collidepoint(event.pos): 
        rectangle_draging = True 
        mouse_x, mouse_y = event.pos 
        offset_x = rectangle.x - mouse_x 
        offset_y = rectangle.y - mouse_y 

     elif event.type == pygame.MOUSEBUTTONUP: 
      if event.button == 1:    
       rectangle_draging = False 

     elif event.type == pygame.MOUSEMOTION: 
      if rectangle_draging: 
       mouse_x, mouse_y = event.pos 
       rectangle.x = mouse_x + offset_x 
       rectangle.y = mouse_y + offset_y 


    screen.fill(WHITE) 
    pygame.draw.rect(screen, RED, rectangle) 

    pygame.display.flip() 

clock.tick(FPS) 


pygame.quit() 

我想這是最重要的部分:

pygame.draw.rect(screen, RED, rectangle) 

每次我嘗試繪製其中的5個時,我都無法拖動它們中的任何一個。有沒有人有這個解決方案?

+0

你能展示其中一項失敗的工作嗎?我懷疑你可能試圖重用'rectangle'變量... –

+0

@GlennRogers是的,我嘗試過,因爲我不知道如何以任何其他方式做到這一點。 – Nenad

回答

1

您可以創建一個矩形列表和一個selected_rect變量,它指向當前選定的矩形。在事件循環中檢查其中一個矩陣是否與event.pos發生衝突,然後將selected_rect設置爲鼠標光標下方的矩形並將其移動。

對於offset,我使用pygame.math.Vector2來節省示例中的幾行內容。

import sys 
import pygame as pg 
from pygame.math import Vector2 


pg.init() 

WHITE = (255, 255, 255) 
RED = (255, 0, 0) 

screen = pg.display.set_mode((1024, 768)) 

selected_rect = None # Currently selected rectangle. 
rectangles = [] 
for y in range(5): 
    rectangles.append(pg.Rect(20, 30*y, 17, 17)) 
# As a list comprehension. 
# rectangles = [pg.Rect(20, 30*y, 17, 17) for y in range(5)] 

clock = pg.time.Clock() 
running = True 

while running: 
    for event in pg.event.get(): 
     if event.type == pg.QUIT: 
      running = False 
     elif event.type == pg.MOUSEBUTTONDOWN: 
      if event.button == 1: 
       for rectangle in rectangles: 
        if rectangle.collidepoint(event.pos): 
         offset = Vector2(rectangle.topleft) - event.pos 
         selected_rect = rectangle 
     elif event.type == pg.MOUSEBUTTONUP: 
      if event.button == 1: 
       selected_rect = None 
     elif event.type == pg.MOUSEMOTION: 
      if selected_rect: 
       selected_rect.topleft = event.pos + offset 

    screen.fill(WHITE) 
    for rectangle in rectangles: 
     pg.draw.rect(screen, RED, rectangle) 

    pg.display.flip() 
    clock.tick(30) 

pg.quit() 
sys.exit()