如何在pygame中制作一个自动移动到鼠标位置的矩形?

时间:2014-01-29 01:08:58

标签: python python-2.7 pygame mouse

我一直试图制作一个移动到我鼠标位置的矩形,但它似乎不起作用。这是我的代码:

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

我尝试运行代码,但我只看到一个绿色矩形一毫秒,然后它就消失了。

1 个答案:

答案 0 :(得分: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的变量,其中我的Rect对象是。然后在while循环中,我根据鼠标的位置改变了Rect对象的中心。你必须重新绘制每个循环的矩形,因为背景颜色(黑色)填充整个窗口并隐藏你的矩形。