메뉴 건너뛰기

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 LLM [번역]거대언어모델(LLM) 가이드 OBG 2023.07.20 71
26 Deeplearning Top 3 most used Pytorch Ecosystem Libraries you should Know about OBG 2023.08.02 86
25 Deeplearning LSTM-AE를 이용한 시퀀스 데이터 이상 탐지 OBG 2023.08.14 74
24 Deeplearning 내 마음대로 선정한 머신러닝/딥러닝 학습 추천 서적 OBG 2023.08.14 72
23 Deeplearning 마이크로소프트가 공개한 무료 AI 코스들 OBG 2023.11.28 56
22 Site 모든 개발자를위한 10 가지 특별한 GitHub 리포지토리 OBG 2023.12.28 110
21 Site 10 Useful/Fun/Weird Github Repos You Have to Play Around With OBG 2023.12.28 94
20 Tool/etc How to stop programmers to copy the code from GitHub when they leave the company? OBG 2024.01.02 114
19 Deeplearning [ifkakao] 추천 시스템: 맥락과 취향 사이 줄타 OBG 2024.01.10 30
18 서버 멀티-플레이어 게임 서버와 레이턴시 보상 테크닉 OBG 2024.01.16 41
17 Deeplearning Using Machine Learning to Predict Customers’ Next Purchase Day OBG 2024.02.27 40
16 LLM [12월 1주] 떠오르는 '미스트랄 7B'...'라마 2' 이어 한국어 모델 세대교체 주도 OBG 2024.03.05 34
15 LLM A Beginner's Guide to Prompt Engineering with GitHub Copilot OBG 2024.04.04 19
14 LLM 만능 프롬프트 OBG 2024.04.07 26
13 LLM How LLMs Work ? Explained in 9 Steps — Transformer Architecture OBG 2024.04.11 21
12 LLM Getting Started with Sentiment Analysis using Python OBG 2024.04.11 28
11 LLM Real-Time Stock News Sentiment Prediction with Python OBG 2024.04.11 29
10 LLM ChatGPT의 강력한 경쟁 언어모델 등장!, Mixtral 8x7B OBG 2024.04.14 22
9 LLM Mixture of Experts - Part 2 OBG 2024.04.14 22
8 LLM The difference between quantization methods for the same bits OBG 2024.04.14 25
Board Pagination Prev 1 ... 6 7 8 9 10 11 12 13 14 ... 15 Next
/ 15
위로