메뉴 건너뛰기

OBG

Programming

MoA
조회 수 2671 추천 수 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 1714
27 Tool/etc 자바스크립트 물리엔진 ㄷㄷ MoA 2014.03.10 614
26 API/MFC 작업자 스레드(Worker Thread) 와 사용자 인터페이스 스레드(User Interface Thread) MoA 2013.07.28 447
25 Tool/etc 잡담) AWS에 서버 띄워 놓으니 벼라별 리퀘스트가 다 날아 오네요 OBG 2023.03.11 91
24 C/C++ 정신나간 정렬 알고리즘 file MoA 2015.10.13 573
23 STL/Boost 정적 배열과 STL vector 속도 비교 MoA 2013.07.28 558
22 Site 졸업작품 및 각종 과제물 프로그램은 어떻게 만들어야 하나? (윈도우즈 응용프로그램) MoA 2013.09.10 1644
21 Deeplearning 직접 보고 추천하는 머신러닝 & 딥러닝 & 수학 총정리(2022) OBG 2022.07.24 3328
20 Deeplearning 추천 시스템 OBG 2023.03.30 120
19 Deeplearning 추천(Recommendation) 시스템 - 알고리즘 Trend 정리 OBG 2021.08.03 134
18 Web 카카오톡 웹버전 만들기 OBG 2022.11.09 193
17 Tool/etc 컨텍스트 스위칭 (Context Switching) MoA 2013.07.28 1039
16 C/C++ 코드 실행 시간 계산 Naya 2012.08.02 297
15 C/C++ 코드 실행 시간 계산 Naya 2012.09.27 493
14 Tool/etc 쿠버네티스 클러스터 OBG 2022.11.11 112
13 Algorithm 큰 수 구하기 알고리즘 Naya 2012.08.02 658
12 API/MFC 태스크 대화상자 (Task Dialog) MoA 2013.10.22 436
11 Tool/etc 텍스트 에디터 Sublime Text 2 너울 2012.03.30 505
10 Site 특정 자료형의 데이터를 binary(hex값, 2진수값)으로 변환 Naya 2012.11.15 562
9 Deeplearning 파이썬 머신러닝 무료 강의 (7시간) OBG 2022.07.06 97
8 Python 파이썬에서 C모듈 사용하기 MoA 2014.02.10 1919
Board Pagination Prev 1 ... 6 7 8 9 10 11 12 13 14 ... 15 Next
/ 15
위로