如何为蒙版图像上的点击制作鼠标事件[Pygame]

时间:2014-07-28 01:55:07

标签: python python-3.x pygame

所以我真的很喜欢编程,而且我正在开发一种类似Cookie Clicker的游戏,但有一个扭曲(挖掘)。它是用python / pygame制作的。无论如何我有一块巨石的形象,我想在每次点击它时在游戏中添加一块石头。

有人帮我在课堂上设置了point_collide。我会承认并说我不完全理解它是如何工作的,但它应该检测我的鼠标是否在我的摇滚图像的非透明部分。

我希望游戏只给你一块石头,如果你点击巨石图像的非透明部分我已经穿透到屏幕中间。

简短问题:如何设置游戏以仅在我的蒙面图像上注册点击?

PS:我知道首先要学习编程的基础知识会更好,但是我已经学到了很多东西,只需直接进入一个项目(它让我继续前进,然后阅读一本书会更有趣)。

代码链接:https://www.refheap.com/88634

守则:

import pygame, sys
from pygame.locals import *
from datetime import datetime

if (__name__ == "__main__"):

pygame.init()
pygame.font.init()
pygame.display.set_caption("Miner Click")

clock = pygame.time.Clock()
screen = pygame.display.set_mode((960,600))
width = 960
height = 600

GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
BROWN = (84,27,1) 
GREY = (198,198,198)

greenbg = pygame.image.load("greenbg.jpg").convert()
rockbutton = pygame.image.load("rockbutton.png").convert_alpha()
woodbutton = pygame.image.load("woodbutton.png").convert_alpha()

pygame.mouse.set_visible(True)
pick = pygame.image.load("pick.png").convert_alpha()
axe = pygame.image.load("axesmall.png").convert_alpha()

rockwidth = 544
rockheight = 274

clicks = 0
wood = 0

stonefont = pygame.font.SysFont("verdana", 29, True)
woodfont = pygame.font.SysFont("verdana", 29, True)
clicktext = stonefont.render('Rock: ' +str(clicks), 2, (GREY))
woodtext = woodfont.render('Wood: ' +str(wood), 2, (BROWN))
boxsize = clicktext.get_rect()
RocksX = 125
WoodX = 113

class Rock(pygame.sprite.Sprite):

def __init__(self, color = BLUE, width = 544, height = 274):
    super(Rock, self ).__init__()

    self.image = pygame.Surface((width, height))
    self.set_properties()
    self.image.fill(color)

def set_properties(self):
    self.rect = self.image.get_rect()
    self.origin_x = self.rect.centerx
    self.origin_y = self.rect.centery

def set_position(self, x, y):
    self.rect.x = 250
    self.rect.y = 230

def set_image(self, filename = None):
    if (filename != None):
        self.image = pygame.image.load(filename).convert_alpha()

def point_collide(self, point):
    x, y = point
    x -= self.rect.x
    y -= self.rect.y
    try:
        return self.mask.get_at((x,y))
    except IndexError:
        return False

#below is my clueless attempt at getting it to work
def checkForCursorPressed(x,y):
    if pygame.mouse.get_pressed() and pygame.mouse.get_pos() == (x,y):
        clicks+=1

coordfont = pygame.font.SysFont("verdana", 12, True)
rock_group = pygame.sprite.Group()
rock = Rock()
rock.set_image("rock.png")
rock.set_position(width/2, height/2)
rock_group.add(rock)

while True:
    clock.tick(60)
    screen.fill((255,255,255))
    screen.blit(greenbg, (0,0))
    x,y = pygame.mouse.get_pos()
    coords = x,y
    now = datetime.now()
    date = '%s/%s/%s' % (now.month, now.day, now.year)
    label = coordfont.render("Coordinates: "+str(coords), 1, (GREY))
    date = coordfont.render("Date: "+str(date), 1, (GREY))
    screen.blit(date, (650,10))
    screen.blit(label, (790, 10))
    screen.blit(rockbutton, (25,25))
    screen.blit(woodbutton, (25,100))
    clicktext = stonefont.render(' ' +str(clicks), 2, (GREY))
    woodtext = woodfont.render(' ' +str(wood), 2, (BROWN))
    screen.blit(clicktext, [RocksX,38])
    screen.blit(woodtext, [139,WoodX])
    rock_group.draw(screen)
    screen.blit(pick, (x-10,y-50))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           sys.exit()
        elif event.type == KEYDOWN and event.key == K_ESCAPE: 
           sys.exit()


        pygame.display.update()

   #in case i need the below again
   #if x>249 and x<(795) and y>210 and y<(484): 

3 个答案:

答案 0 :(得分:0)

单击将创建一个MOUSEBUTTONDOWN事件,因此您应该能够处理事件处理循环中的点击,例如:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
       sys.exit()
    elif event.type == KEYDOWN and event.key == K_ESCAPE:
       sys.exit()
    elif event.type == MOUSEBUTTONDOWN:
        click_position = event.pos
        if rock.point_collide(click_position):
            print('Clicked within the rock')
            clicks += 1
            # Any other events that have to happen
            #   when the rock is clicked

答案 1 :(得分:0)

我也不了解point_collide()是如何工作的,我得到了一个AttributeError:&#39; Rock&#39;没有属性&#39; mask&#39;。 所以我会使用另一种可能性来检测是否有人使用colorkey点击了图像的非透明部分。

colorkey定义blitting时的透明色。就我而言,它是白色的:

def set_image(self, filename = None):
    ...
    #sets colorkey to white, depends on the image
    self.image.set_colorkey((255,255,255))

point_collide()的新版本:

def point_collide(self, point):
   x, y = point
   x -= self.rect.x
   y -= self.rect.y
   #detects if click hits the image
   if 0 <= x < self.image.get_width():
       if 0 <= y < self.image.get_height():
           #detects if color at clicking position != colorkey-color(transparent)
           if self.image.get_at((x,y))[0:3] != self.image.get_colorkey()[0:3]:
               return True
   return False

如何获取鼠标事件已经得到解答。

答案 2 :(得分:0)

好的我工作了:))

如果其他人试图做类似的事情我会在这里解释。

将以下内容放入您的代码中(这解决了问题&#39; Rock没有属性掩码&#39;我得到的错误)

self.mask = pygame.mask.from_surface(self.image)

这是我把它放在我的代码中(在我的set_image def中)

def set_image(self, filename = None):
    if (filename != None):
        self.image = pygame.image.load(filename).convert_alpha()
        self.mask = pygame.mask.from_surface(self.image)

现在将此代码与Marius结合使用,效果非常好!