我现在正在用Python 3和Pygame编写一个跳跃式fun。这一次,我试着用我的旧功能做一个“按钮”类,以使游戏更易读,并获得更好的性能。这是我的旧密码:
def button(msg,x,y,w,h,ic,ac,action=None):
time.sleep(0)
mouse=pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(screen,black,(x,y,w,h),2)
pygame.draw.rect(screen, ac,(x,y,w,h))
noevent = False
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen,black,(x,y,w,h),4)
pygame.draw.rect(screen, ic,(x,y,w,h))
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
screen.blit(textSurf, textRect)现在我开始用它写一门课:
class buttons():
def __init__(self,sort,msg,x,y,w,h,ic,ac,action=None):
self.type=sort
self.msg=msg
self.x=x
self.y=y
self.w=w
self.h=h
self.ic=ic
self.ac=ac
self.action=action
self.mouse=pygame.mouse.get_pos()
self.click = pygame.mouse.get_pressed()
self.noevent = False
def render(self):
if self.x+self.w > self.mouse[0] > self.x and self.y+self.h > self.mouse[1] > self.y:
pygame.draw.rect(screen,black,(self.x,self.y,self.w,self.h),2)
pygame.draw.rect(screen, self.ac,(self.x,self.y,self.w,self.h))
if click[0] == 1 and action != None:
self.action()
else:
pygame.draw.rect(screen,black,(self.x,self.y,self.w,self.h),4)
pygame.draw.rect(screen, self.ic,(self.x,self.y,self.w,self.h))
self.textSurf, self.textRect = text_objects(self.msg, smallText)
self.textRect.center = ( (self.x+int(self.w/2)), (self.y+int(self.h/2)))
screen.blit(self.textSurf, self.textRect)但它也给了我同样的问题:
pygame.draw.rect(screen,black,(self.x,self.y,self.w,self.h),4)
TypeError: Rect argument is invalid我现在不知道该怎么办了。我还阅读了关于Stackoverflow这个主题的其他问题。我搞不懂这个问题。
发布于 2017-01-05 20:39:52
pygame.draw.rect()期望pygame.Rect()对象不是元组(x, y, w, h)
所以保持pygame.Rect()的大小和位置
self.rect = pygame.Rect()
self.rect.x = x
self.rect.y = y
self.rect.width = w
self.rect.height = h或者更短
self.rect = pygame.Rect(x, y, w, h)你不需要所有这些self.x,self.y,等等。
pygame.draw.rect(screen, black, self.rect, 4)
screen.blit(self.image, self.rect)你可以检查鼠标在上面的按钮
if self.rect.collidepoint(self.mouse):而不是
if self.x+self.w > self.mouse[0] > self.x and self.y+self.h > self.mouse[1] > self.y:您也可以使用
self.rect.right而不是self.x+self.wself.rect.bottom而不是self.y+self.hself.rect.centerx而不是self.x+(self.w/2)self.rect.centery而不是self.y+(selfh./2)您可以在按钮上将文本居中。
self.textRect.center = self.rect.center而不是
self.textRect.center = ( (self.x+int(self.w/2)), (self.y+int(self.h/2)) )参见PyGame doc:pygame.Rect()
BTW: 按钮代码示例
BTW:使代码更具可读性,使用类的CamelCase名称( class Button )和函数/方法的lower_case名称以及变量( self.text_image,self.text_rect )
https://stackoverflow.com/questions/41492817
复制相似问题