2012-04-16 7 views
6

저는 파이 게임 (pygame)에서 게임을 만들고 있습니다. 첫 번째 화면에는 (i) 게임을 시작하고, (ii) 지시 사항이있는 새 화면을로드하고, iii) 프로그램을 종료 할 수있는 버튼이 있어야합니다. .파이썬/파이 게임에서 버튼을 만드는 방법?

이 코드는 버튼 만들기 용으로 온라인에서 찾았지만 실제로 이해하지는 못합니다 (객체 지향 프로그래밍이 좋지 않습니다). 만약 내가하고있는 일에 대해 몇 가지 설명을 할 수 있다면 좋을 것입니다. 또한 파일 경로를 사용하여 컴퓨터에서 파일을 열려고하면 오류가 발생합니다. 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() 

나를 도울 수있는 사람을 이용해 주셔서 감사합니다.

답변

12

나는 당신을 위해 코드 예제를 가지고 있지 않지만, 내가 얼마나 그것을이다 : 생성자의 인수로 버튼을 이동하려면 텍스트,

  1. 는 Button 클래스를 확인
    1. 이미지의, 하나를 파이 게임 표면을 만들거나 사각형
    2. 작성 화면을 게임 블릿
  2. 파이 게임
  3. 에 Font.Render 물건 그것에 텍스트를 렌더링, 그 RECT를 저장합니다.
  4. 마우스 클릭시를 확인하면 mouse.get_pos()가 버튼의 블릿에서 주 표면으로 반환 한 rect 내의 일치 항목을 찾습니다.

다른 예는 비슷하지만 예와 비슷합니다.

+0

좋아요, 제가 도와 드리겠습니다. 감사합니다. – user1334014

0

온라인에서 찾은 '코드'가 좋지 않습니다. 버튼을 만드는 데 필요한 것은 바로 이것입니다. 코드 시작 부분 근처에 넣으십시오.

def Buttonify(Picture, coords, surface): 
    image = pygame.image.load(Picture) 
    imagerect = image.get_rect() 
    imagerect.topright = coords 
    surface.blit(image,imagerect) 
    return (image,imagerect) 

다음을 게임 루프에 넣으십시오. 또한 어딘가에 게임 루프 : 당신은 그래서

if event.type == MOUSEBUTTONDOWN and event.button == 1: 
    mouse = pygame.mouse.getpos 
    if Image[1].collidrect(mouse): 
     #code if button is pressed goes here 

for event in pygame.event.get을 수행, buttonify 버튼 될 이미지를로드 한 곳

Image = Buttonify('YOUR_PICTURE.png',THE_COORDS_OF_THE_BUTTON'S_TOP_RIGHT_CORNER, THE_NAME_OF_THE_SURFACE) 

또한 게임 루프에 넣고. 이 이미지는 .jpg 파일이거나 코드와 동일한 디렉토리에있는 다른 PICTURE 파일이어야합니다. 그림이 그 이름입니다. 이름 뒤에는 .jpg 또는 그 뒤에 다른 것이 있어야하며 이름은 따옴표로 묶어야합니다. Buttonify의 coords 매개 변수는 파이 게임에서 열리는 화면이나 창의 오른쪽 상단 좌표입니다.

blahblahblah = pygame.surface.set_mode((WindowSize)) 
/|\ 
    | 
    Surface's Name 

그래서 함수가 파이 게임 표면 인 '이미지'라는 것을 만들어, 그것은 그 위치에 그것을 설정하는 'imagerect을'(라고 주위에 두 번째의 사각형을두고 : 표면이 일이 매개 변수를 blitting 할 때), 그리고 나서 그것의 위치를 ​​설정하고, 두번째 줄 마지막 줄까지 blits합니다.

코드의 다음 비트는 '이미지'를 '이미지'와 '이미지 수정'의 튜플로 만듭니다.

마지막 코드는 기본적으로 왼쪽 마우스 버튼을 누르면 if event.type == MOUSEBUTTONDOWN and event.button == 1:입니다. 이 코드는 for event in pygame.event.get이어야합니다. 다음 줄은 마우스를 마우스 위치의 튜플로 만듭니다.마지막 줄은 마우스가 Image {1}과 충돌했는지를 확인합니다. 코드는 다음과 같습니다.

추가 설명이 필요하면 알려주십시오.

0

따라서 8 개의 매개 변수를받는 button이라는 함수를 만들어야합니다. 1) 버튼 메시지 2) 버튼 왼쪽 위 모서리의 X 위치 3) 버튼의 왼쪽 상단 모서리의 Y 위치 4) 버튼의 너비 5) 버튼의 높이 6) 비활성 색상 (배경색) 7) 활성 색상 (당신이 가져 색상) 당신이

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) 

을 perfom 할 작업의 8) 이름 그래서 버튼 기능 당신은 당신의 게임 루프를 작성하고 당신이 호출 할 때 : (

버튼을 "시작", 600, 120, 120, 25, 청색, 청록색, "시작")

관련 문제