如何使鼠标事件的点击蒙面图像[Pygame]



我是一名编程新手,我正在制作一款类似于《Cookie Clicker》的游戏,但它带有一些变化(采矿)。它是在python/pygame中制作的。无论如何,我有一个巨石的图像,我想在每次点击它时添加一块岩石到我的游戏库存中。

有人帮我在课堂上设置了point_collision。我承认,我不完全明白它是如何工作的,但它应该检测我的鼠标是否在我的岩石图像的非透明部分。

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

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

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

点击将创建一个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

我也不明白point_collision()是如何工作的,我得到一个AttributeError: 'Rock'没有属性'mask'。因此,我将使用另一种可能性来检测是否点击了图像的非透明部分,使用colorkey。

colorkey定义了比特时的透明颜色。在我的例子中,它是白色的:

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

新版本point_collision ():

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

如何获得鼠标事件已经回答了

好了,我搞定了

如果有人想做类似的事情,我会在这里解释。

把下面的代码(这解决了问题'岩石没有属性掩码'错误我得到)

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)

现在结合这段代码与马吕斯,它的工作完美!

最新更新