gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:32:37 25 4
gpt4 key购买 nike

我使用 python pygame 库创建了一个 GameObject 类,它在屏幕上绘制一个矩形。 我想集成一个事件处理程序,它允许我在周围绘制矩形,但是游戏对象的单击事件没有注册。以下是该类中的几段代码:

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

我是否需要将矩形变成图像以便注册鼠标事件,或者是否有其他方法可以拖动此框?

最佳答案

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?

无需图像。解决方案:

注意:

  1. 您已经使用事件来获取 MOUSEMOTION,因此请使用事件的数据:事件中的 .pos 和 .button。

  2. 使用Color存储为单个变量的类:

    self.color_bg = 颜色(“蓝色”)self.color_fg = 颜色(20,20,20)打印 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)

关于pygame中的python点击事件范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5037080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com