메뉴 건너뛰기

OBG

Programming

MoA
조회 수 2635 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

10_main.png

 

드디어 마지막이다. 마지막 강좌는 내용이 좀 길다. 상점 하나 추가하는데 별거 있겠어 하고 생각하면 오산이다. 상점 인터페이스를 만들고 메뉴를 만들고 메뉴 선택 시 반응을 정의하는 등의 처리를 해야한다.

 

1. Shop 클래스 추가

 

 

class Shop(pygame.sprite.Sprite):

    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_img('scenery', 'shop.png')
        self.rect = self.image.get_rect()
        self.rect.topleft = x, y
        self.active = False
        self.selections = [["", # This first group is the seed purchase text
                            ""],
                           ["", # This second group is the wheat selling text
                            ""],
                           ""]  # This last string is the leaving text
        self.maxseeds = 0
        self.selection = 0

    def open(self):
        self.update()
        self.active = True
        self.selection = 0

    def close(self):
        self.active = False

    def update(self):
        self.maxseeds = int(farmer.gold/2)
        self.selections = [["Buy %d seeds" % (self.maxseeds),
                            "This will cost %d gold" % (self.maxseeds * 2)],
                           ["Sell %d wheat" % (farmer.wheat),
                            "You will gain %d gold" % (farmer.wheat * 3)],
                           "Leave shop (Esc)"]

    def up_selection(self):
        self.selection -= 1
        if self.selection < 0:
            self.selection = 2

    def down_selection(self):
        self.selection += 1
        if self.selection > 2:
            self.selection = 0

    def make_selection(self):
        if self.selection == 0:                    # If the player wishes to buy seeds (all or none, for now)
            farmer.gold -= self.maxseeds * 2
            farmer.seeds += self.maxseeds
            self.update()
        elif self.selection == 1:                # If the player wishes to sell wheat (all or none, for now)
            farmer.gold += farmer.wheat * 3
            farmer.wheat = 0
            self.update()
        elif self.selection == 2:                # If the player wishes to leave the shop
            self.close()

 

 

 

2. Farmer 클래스의 interact() 함수 업데이트

 

 

            elif entity.__class__.__name__ == 'Shop':
                shop = entity
                shop.open()

 

 

 

3. 상점 인터페이스 생성

 

 

    # 상점 인터페이스를 생성한다
    global shopinterface
    shopinterface = pygame.Surface((192, 256))
    shopinterface.convert()
    shopinterfaceimage = load_img("hud", "shop.png")
    shopinterface.blit(shopinterfaceimage, (0, 0))

 

 

 

4. 맵데이터 로드 부분 수정

 

 

            elif char == 'S':
                global shop
                shop = Shop(blockx, blocky)
                objectlist.append(shop)


5. 입력 체크 부분 수정

 

 

# 입력 체크
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if shop.active:
                        shop.close()
                    else:
                        return
                elif event.key == K_UP:
                    if shop.active:
                        shop.up_selection()
                    else:
                        farmer.move("up")
                elif event.key == K_DOWN:
                    if shop.active:
                        shop.down_selection()
                    else:
                        farmer.move("down")
                elif event.key == K_LEFT:
                    if shop.active:
                        pass
                    else:
                        farmer.move("left")
                elif event.key == K_RIGHT:
                    if shop.active:
                        pass
                    else:
                        farmer.move("right")
                elif event.key == K_SPACE:
                    if shop.active:
                        shop.make_selection()
                    else:
                        farmer.interact()
                elif event.key == K_TAB:
                    pass


6. 상점 텍스트 업데이트 함수 정의

 

 

 

 

 

 

def update_shop_text():
    font = pygame.font.SysFont('calibri', 20)
    textpos_base = pygame.Rect((0, 0), (160, 20))

    seed_text_color = (0,0,0)
    wheat_text_color = (0,0,0)
    leave_text_color = (0,0,0)
    if shop.selection == 0:
        seed_text_color = (120,120,230)
    elif shop.selection == 1:
        wheat_text_color = (120,120,230)
    elif shop.selection == 2:
        leave_text_color = (120,120,230)

    spacer = 0
    for line in shop.selections[0]:
        buy_seeds_text = font.render(line, 1, seed_text_color)
        buy_seeds_textpos = pygame.Rect((10, 60+spacer), (buy_seeds_text.get_width(), buy_seeds_text.get_height()))
        shopinterface.blit(buy_seeds_text, buy_seeds_textpos)
        spacer += 24

    spacer = 0
    for line in shop.selections[1]:
        buy_wheat_text = font.render(line, 1, wheat_text_color)
        buy_wheat_textpos = pygame.Rect((10, 140+spacer), (buy_wheat_text.get_width(), buy_wheat_text.get_height()))
        shopinterface.blit(buy_wheat_text, buy_wheat_textpos)
        spacer += 24

    leave_text = font.render(shop.selections[2], 1, leave_text_color)
    leave_textpos = pygame.Rect((10, 225), (leave_text.get_width(), leave_text.get_height()))
    shopinterface.blit(leave_text, leave_textpos)

 

 

 

7. 상점 여는 부분 작성

 

 

        # 상점을 연다
        if shop.active:
            screen.blit(shopinterface, (224, 144))
            shopinterface.blit(shopinterfaceimage, (0, 0))
            update_shop_text()
            pass

 

 

 

 

 

 

 

 

 

 

 

 

?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
공지 Tool/etc Programming 게시판 관련 2 MoA 2014.11.01 1591
282 JAVA/Android XML 파싱하기 MoA 2013.08.06 7042
281 API/MFC Visual C++ 시리얼 통신(RS-232) 강좌 (1) MoA 2013.07.28 6652
280 Library AS3 Code Library MoA 2013.10.11 4995
279 API/MFC Sleep() 함수 대신 프로그램 딜레이 시키기 (Wait) MoA 2013.07.28 4607
278 API/MFC Visual C++ 시리얼 통신(RS-232) 강좌 (2) 1 MoA 2013.07.28 4419
277 API/MFC MFC 리본 사용하기 (아이콘 제작 포함) 너울 2012.02.09 4304
276 JAVA/Android logcat 사용법 MoA 2013.05.28 3461
275 API/MFC 프린터 출력하기 MoA 2013.10.16 3383
274 Deeplearning 직접 보고 추천하는 머신러닝 & 딥러닝 & 수학 총정리(2022) OBG 2022.07.24 3096
273 Python [액션게임 만들기] 3. 클래스 다이어그램 기초 file OBG 2014.05.07 2668
272 API/MFC DLL 생성 시 주의 MoA 2013.08.22 2659
» Python [농장게임 만들기] 10. 상점을 추가하자 file MoA 2014.05.01 2635
270 API/MFC Thread와 SendMessage를 통해 DeadLock을 만드는 방법 MoA 2013.07.28 2600
269 API/MFC 다국어를 위한 StringTable, LoadString 1 MoA 2013.12.22 2389
268 C/C++ C 언어의 문자형 변수 char - 8비트 정수형 변수 MoA 2013.07.28 2169
267 Python [농장게임 만들기] 3. 배경을 그리자 6 file MoA 2014.04.28 2033
266 Python 파이썬에서 C모듈 사용하기 MoA 2014.02.10 1899
265 API/MFC 프로세스 - 생성과 종료 그리고 이것 저것 너울 2011.10.12 1807
264 Site 졸업작품 및 각종 과제물 프로그램은 어떻게 만들어야 하나? (윈도우즈 응용프로그램) MoA 2013.09.10 1611
263 API/MFC 다른 스레드에서 메인다이얼로그 포인터 받아오기 AfxGetMainWnd() 1 MoA 2013.07.28 1574
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 15 Next
/ 15
위로