9

私は pygame でゲームを作成しています。最初の画面に、(i) ゲームを開始する、(ii) 新しい画面に指示をロードする、(iii) プログラムを終了するために押すことができるボタンが必要です。

ボタン作成用のこのコードをオンラインで見つけましたが、よくわかりません (私はオブジェクト指向プログラミングが得意ではありません)。それが何をしているのかについて説明を得ることができれば、それは素晴らしいことです。また、それを使用してファイル パスを使用してコンピューター上のファイルを開こうとすると、エラー sh: filepath :Permission denied が表示されますが、これは解決方法がわかりません。

#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()

私を助けることができる人に感謝します。

4

6 に答える 6

12

コード例はありませんが、次のようにします。

  1. コンストラクター引数としてボタンに表示するテキストを使用して、Button クラスを作成します。
    1. 画像または塗りつぶされた Rect のいずれかの PyGame サーフェスを作成します
    2. Pygame の Font.Render でテキストをレンダリングします。
  2. ゲーム画面にブリットし、その矩形を保存します。
  3. マウス クリックで、mouse.get_pos() がメイン サーフェスへのボタンのブリットによって返された rect の座標と一致することを確認します。

それはあなたの例がやっていることと似ていますが、まだ異なります。

于 2012-04-16T05:26:51.140 に答える
0

これは、非常によく似た (しかし閉じられた) 質問で私のために働いた他の誰かによって投稿されたクラスの修正版です。

class Button():
    def __init__(self, color, x,y,width,height, text=''):
        self.color = color
        self.ogcol = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self,win,outline=None):
        #Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
            
        pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
        
        if self.text != '':
            font = pygame.font.SysFont('Consolas', 24)
            text = font.render(self.text, 1, (0,0,0))
            win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

    def isOver(self, pos):
        global STATE
        #Pos is the mouse position or a tuple of (x,y) coordinates
        if pos[0] > self.x and pos[0] < self.x + self.width:
            if pos[1] > self.y and pos[1] < self.y + self.height:
                self.color = (128,128,128)
            else:
                self.color = self.ogcol
        else:
            self.color = self.ogcol
        global ev
        for event in ev:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if pos[0] > self.x and pos[0] < self.x + self.width:
                    if pos[1] > self.y and pos[1] < self.y + self.height:
                        return True

変数evはイベント リスト ( pygame.event.get()) になります。構文の例は次のとおりです。

#class up here
btn = Button((255,0,0),100,100,200,50,text="print hi")
#do above before you start the loop
#all of the pygame init and loop
#Define screen as the window

btn.draw(screen)
if btn.isOver(pygame.mouse.get_pos()) == True:
    print("hi")
pygame.display.update()
于 2021-10-17T18:40:08.403 に答える
0

これは私が何年も前に作ったボタンのクラスです :使用しているコンピューターにpygameがないため、最近テストできました。お役に立てれば!

于 2017-07-20T09:46:48.143 に答える
0

したがって、8 つのパラメーターを受け取る button という名前の関数を作成する必要があります。1) ボタンのメッセージ 2) ボタンの左上隅の X 位置 3) ボタンの左上隅の Y 位置 4) ボタンの幅 5) ボタンの高さ 6) 非アクティブな色 (背景色) 7) アクティブな色(ホバー時の色) 8)実行したいアクションの名前

def button (msg, x, y, w, h, ic, ac, action=None ):
    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(watercycle, CYAN, (x, y, w, h))
        if (click[0] == 1 and action != None):
            if  (action == "Start"):
                game_loop()
            elif  (action == "Load"):
                 ##Function that makes the loading of the saved file##
            elif  (action == "Exit"):
                pygame.quit()

    else:
        pygame.draw.rect(watercycle, BLUE, (x, y, w, h))
        smallText = pygame.font.Font("freesansbold.ttf", 20)
        textSurf, textRect = text_objects(msg, smallText)
        textRect.center = ( (x+(w/2)), (y+(h/2)) )
        watercycle.blit(textSurf, textRect)

したがって、ゲーム ループを作成してボタン関数を呼び出すと、次のようになります。

ボタン (「開始」、600、120、120、25、BLUE、CYAN、「開始」)

于 2017-07-20T00:42:37.120 に答える