我正在pygame制作一个游戏,在第一个屏幕上我希望有按钮可以按下(i)启动游戏,(ii)加载带有说明的新屏幕,以及(iii)退出程序.
我已经在网上找到了这个用于按钮制作的代码,但我并不是真的理解它(我在面向对象编程方面并不擅长).如果我能得到一些关于它正在做什么的解释那将是伟大的.此外,当我使用它并尝试使用文件路径在我的计算机上打开文件时,我得到错误sh:filepath:权限被拒绝,我不知道如何解决.
#load_image is used in most pygame programs for loading images def load_image(name,colorkey=None): fullname = os.path.join('data',name) try: image = pygame.image.load(fullname) except pygame.error,message: print 'Cannot load image:',fullname raise SystemExit,message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey,RLEACCEL) return image,image.get_rect() class Button(pygame.sprite.Sprite): """Class used to create a button,use setCords to set position of topleft corner. Method pressed() returns a boolean and should be called inside the input loop.""" def __init__(self): pygame.sprite.Sprite.__init__(self) self.image,self.rect = load_image('button.png',-1) def setCords(self,x,y): self.rect.topleft = x,y def pressed(self,mouse): if mouse[0] > self.rect.topleft[0]: if mouse[1] > self.rect.topleft[1]: if mouse[0] < self.rect.bottomright[0]: if mouse[1] < self.rect.bottomright[1]: return True else: return False else: return False else: return False else: return False def main(): button = Button() #Button class is created button.setCords(200,200) #Button is displayed at 200,200 while 1: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() if button.pressed(mouse): #Button's pressed method is called print ('button hit') if __name__ == '__main__': main()
感谢能帮助我的人.