python click event scope issue in pygame
I've created a GameObject class, using the python pygame library, which draws a rectangle on the screen. I would like to integrate an event handler which would allow me to draw the rectangle around, however the click events for the GameObject are not registering. Here are a couple snippets of code from the class:
def on_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
print "I'm a mousedown event!"
self.down = True
self.prev_x=pygame.mouse.get_pos(开发者_如何学Python0)
self.prev_y=pygame.mouse.get_pos(1)
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.down = False
def on_draw(self, surface):
#paints the rectangle the particular color of the square
pygame.draw.rect(surface, pygame.Color(self.red, self.green, self.blue), self.geom)`
Do I need to make the rect into an image for the mouse events to register, or is there some other way I can drag this box around?
Do I need to make the rect into an image for the mouse events to register, or is there some other way I can drag this box around?
No image required. Solution:
Note:
You already use event to get MOUSEMOTION, so use event's data: .pos, and .button from the event.
use Color class to store as a single variable:
self.color_bg = Color("blue") self.color_fg = Color(20,20,20) print self.color_bg.r, self.color_bg.g, self.color_bg.b
Note: I kept some code slightly more verbose to make it easier to read, ex: you could do:
# it uses
x,y = event.pos
if b.rect.collidepoint( (x,y) ):
# you could do (the same thing)
if b.rect.collidepoint( event.pos* ):
Solution:
import pygame
from pygame.locals import *
from random import randint
class Box(object):
"""simple box, draws rect and Color"""
def __init__(self, rect, color):
self.rect = rect
self.color = color
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
class Game(object):
def __init__(self):
# random loc and size boxes
# target = box to move
self.target = None
for i in range(5):
x,y = randint(0, self.width), randint(0, self.height)
size = randint(20, 200)
r = Rect(0,0,0,0)
# used 0 because: will be using propery, but have to create it first
r.size = (size, size)
r.center = (x, y)
self.boxes.append( Box(r, Color("red") ))
def draw(self):
for b in self.boxes: b.draw()
def on_event(self, event):
# see: http://www.pygame.org/docs/ref/event.html
if event.type == MOUSEBUTTONDOWN and event.button = 1:
# LMB down = target if collide
x,y = event.pos
for b in self.boxes:
if b.rect.collidepoint( (x,y) ): self.target = b
elif event.type == MOUSEBUTTONUP and event.button = 1:
# LMB up : untarget
self.target = None
elif event.type == MOUSEMOTION:
x,y = event.pos
# is a valid Box selected?
if self.target is not None:
self.target.rect.center = (x,y)
精彩评论