Python Pygame按钮getRect碰撞点不工作?
我已经完成了游戏的主代码,并开始制作菜单屏幕。我可以在屏幕上很好地显示按钮,但当我单击某个位置时,我会看到: 我怎样才能着手解决这个问题?如果我在这个问题上没有说清楚,请告诉我,这样我可以澄清。谢谢 以下是我的菜单屏幕代码:Python Pygame按钮getRect碰撞点不工作?,python,button,menu,pygame,Python,Button,Menu,Pygame,我已经完成了游戏的主代码,并开始制作菜单屏幕。我可以在屏幕上很好地显示按钮,但当我单击某个位置时,我会看到: 我怎样才能着手解决这个问题?如果我在这个问题上没有说清楚,请告诉我,这样我可以澄清。谢谢 以下是我的菜单屏幕代码: import pygame import random import time pygame.init() #colours white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,155,0)
import pygame
import random
import time
pygame.init()
#colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
blue = (50,50,155)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Numeracy Ninjas')
clock = pygame.time.Clock()
#Fonts
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 75)
#Sprites
img_button_start = pygame.image.load('Sprites/Buttons/button_start.png')
img_button_options = pygame.image.load('Sprites/Buttons/button_options.png')
gameDisplay.fill(white)
pygame.display.update()
class Button(pygame.sprite.Sprite):
def __init__(self, image, buttonX, buttonY):
super().__init__()
gameDisplay.blit(image, (buttonX, buttonY))
pygame.display.update()
selfrect = image.get_rect()
def wasClicked(event):
if selfrect.collidepoint(event.pos):
return True
def gameIntro():
buttons = pygame.sprite.Group()
button_start = Button(img_button_start, 27, 0)
button_options = Button(img_button_options, 27, 500)
buttons.add(button_start)
buttons.add(button_options)
print(buttons)
#main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
print(event.pos)
#check for every button whether it was clicked
for btn in buttons:
print('forbtninbuttons')
if btn.wasClicked():
print('clicked!')
if event.type == pygame.QUIT:
pygame.quit()
您没有为类声明任何属性,只有局部变量。尝试执行
self.selfrect=image.get_rect()
在初始值设定项和wasClicked(事件)
方法中执行:
def wasClicked(self, event):
if self.selfrect.collidepoint(event.pos):
return True
不过,将rect变量命名为rect通常是惯例
以后,请确保在问题中写入错误,而不是链接到错误的图像。链接到图像会降低搜索能力,使有屏幕阅读器的人无法听到错误。谢谢你的回答。我仍然得到基本相同的错误,只是这次它说“NameError:name'self'未定义”,而不是“NameError:name'selfrect'未定义”。哦,对不起,忘了将self放在方法参数中。现在它应该可以工作了:)我把“self”放在方法参数中,但是现在我得到了这个错误:“TypeError:wasClicked()缺少一个必需的位置参数:'self'”。Button类中是否有
wasClicked(self,event)
方法?在事件循环中,是否在参数中传递事件变量?在那里,应该可以这样做:。我重命名了一些变量,使它们遵循命名约定()并删除了不必要的代码。
class Button(pygame.sprite.Sprite):
def __init__(self, image, buttonX, buttonY):
super().__init__()
# This code doesn't make sense here. It should be inside your game loop.
# gameDisplay.blit(image, (buttonX, buttonY))
# pygame.display.update()
self.image = image # It's usually good to have a reference to your image.
self.rect = image.get_rect()
def wasClicked(self, event):
if self.rect.collidepoint(event.pos):
return True
else:
return False