2014-01-29 91 views
0

我一直在試圖製作一個移動到我的鼠標位置的矩形,但它似乎沒有工作。這裏是我的代碼:如何在pygame中自動移動到鼠標位置的矩形?

import random, pygame, sys, pickle, pygame.mouse, pygame.draw 
from pygame.locals import * 
pygame.mixer.init() 
#    R G B 
WHITE  = (255, 255, 255) 
BLACK  = ( 0, 0, 0) 
RED  = (255, 0, 0) 
GREEN  = ( 0, 255, 0) 
DARKGREEN = ( 0, 155, 0) 
DARKGRAY = (40, 40, 40) 
BGCOLOR = BLACK 

pygame.init() 

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) 
DISPLAYSURF.fill(BLACK) 
rectangle = pygame.draw.rect (DISPLAYSURF, DARKGREEN, Rect((100,100), (130,170))) 
pygame.display.update() 

while True: 
    DISPLAYSURF.fill(BLACK) 
    #print pygame.mouse.get_pos() 
    rectangle.move(pygame.mouse.get_pos()) 
    pygame.display.update() 
    for event in pygame.event.get(): 
      if event.type == QUIT: 
        pygame.mixer.music.stop() 
        pygame.quit() 
        sys.exit() 

我嘗試運行代碼,但我只看到一個毫秒的綠色矩形,然後消失。

回答

2

您沒有爲變量WINDOWWIDTHWINDOWHEIGHT分配任何值。我做了一些修改您的代碼,它很適合我:

import random, pygame, sys, pickle, pygame.mouse, pygame.draw 
from pygame.locals import * 
pygame.mixer.init() 
#    R G B 
WHITE  = (255, 255, 255) 
BLACK  = ( 0, 0, 0) 
RED  = (255, 0, 0) 
GREEN  = ( 0, 255, 0) 
DARKGREEN = ( 0, 155, 0) 
DARKGRAY = (40, 40, 40) 
BGCOLOR = BLACK 

pygame.init() 

WINDOWWIDTH = 500 
WINDOWHEIGHT = 400 
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) 
rectangle = Rect(0, 0, 130, 170) 

while True: 
    for event in pygame.event.get(): 
      if event.type == QUIT: 
        pygame.mixer.music.stop() 
        pygame.quit() 
        sys.exit() 
    DISPLAYSURF.fill(BLACK) 
    rectangle.center = pygame.mouse.get_pos() 
    pygame.draw.rect(DISPLAYSURF, DARKGREEN, rectangle) 
    pygame.display.update() 

我做了一個變量,名爲rectangle在我的矩形對象。然後在while循環中,我根據鼠標的位置更改了Rect對象的中心。由於背景顏色(黑色)填充整個窗口並隱藏矩形,因此每個循環都必須重繪矩形。

相關問題