메뉴 건너뛰기

OBG

Programming

MoA
조회 수 2672 추천 수 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 1732
287 API/MFC 후킹 링크 MoA 2013.07.28 419
286 Python 화면 캡쳐 소스 MoA 2014.01.14 974
285 API/MFC 프린터 출력하기 MoA 2013.10.16 3441
284 API/MFC 프로세스 - 생성과 종료 그리고 이것 저것 너울 2011.10.12 1834
283 API/MFC 프로그램 배포용으로 만드는 과정 너울 2012.01.20 488
282 Site 프로그래밍 관련 사이트 MoA 2012.08.02 256
281 C/C++ 파일 입출력 MoA 2013.07.28 494
280 Python 파이썬에서 C모듈 사용하기 MoA 2014.02.10 1921
279 Deeplearning 파이썬 머신러닝 무료 강의 (7시간) OBG 2022.07.06 99
278 Site 특정 자료형의 데이터를 binary(hex값, 2진수값)으로 변환 Naya 2012.11.15 565
277 Tool/etc 텍스트 에디터 Sublime Text 2 너울 2012.03.30 506
276 API/MFC 태스크 대화상자 (Task Dialog) MoA 2013.10.22 436
275 Algorithm 큰 수 구하기 알고리즘 Naya 2012.08.02 658
274 Tool/etc 쿠버네티스 클러스터 OBG 2022.11.11 114
273 C/C++ 코드 실행 시간 계산 Naya 2012.08.02 297
272 C/C++ 코드 실행 시간 계산 Naya 2012.09.27 494
271 Tool/etc 컨텍스트 스위칭 (Context Switching) MoA 2013.07.28 1039
270 Web 카카오톡 웹버전 만들기 OBG 2022.11.09 196
269 Deeplearning 추천(Recommendation) 시스템 - 알고리즘 Trend 정리 OBG 2021.08.03 134
268 Deeplearning 추천 시스템 OBG 2023.03.30 121
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 15 Next
/ 15
위로