pygame中的python点击事件范围问题

1 投票
1 回答
1066 浏览
提问于 2025-04-16 12:03

我创建了一个GameObject类,使用的是Python的pygame库,这个类可以在屏幕上画一个矩形。 我想加一个事件处理器,这样我就可以移动这个矩形了,但我发现点击事件没有被识别。 下面是这个类的一些代码片段:

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

我需要把这个矩形变成一张图片才能让鼠标事件被识别吗?还是说有其他方法可以让我拖动这个框?

1 个回答

1

我需要把这个矩形变成图片才能让鼠标事件生效吗?还是说有其他方法可以拖动这个框?

不需要图片。解决办法:

注意:

  1. 你已经在使用事件来获取鼠标移动,所以可以用事件的数据:.pos 和 .button。

  2. 使用 Color 类来把颜色存成一个变量:

    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

注意:我把一些代码写得稍微详细一点,这样更容易理解,比如你可以这样写:

# it uses
x,y = event.pos
if b.rect.collidepoint( (x,y) ):
# you could do (the same thing)
if b.rect.collidepoint( event.pos* ):

解决办法:

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)

撰写回答