お店

[記事全体の目次へ移動](https://qiita.com/hijpa/items/056acaa13e935590fdc2)

# お知らせ

お店(売り買い)で売りに来たを選んだあと、Ｘキーで戻って、また売りに来たを選ぶと、エラーが出ていました。修正しました。

# GIF

<details><summary>ここをクリックしてください</summary>

![無題の動画 ‐ Clipchampで作成 (1).gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3874121/819f8e58-4988-6e8f-f616-bdf2f8301d5e.gif)

</details>

# お店(買うだけ)

<details><summary>ここをクリックしてください</summary>

Zキーで決定、Ｘキーで取り消しです。
アイテムを売ることはできません。買うだけです。

必要なもの
- フォントファイル
- キャラクター画像ふたつ
- ボタン音
- カーソル画像　[カーソル画像作成コード](#カーソル画像作成)

FileNotFoundError:
こういうエラーが出たら、パスの前に r をつけましょう。

```python:
import pygame
from pygame.locals import *
import sys

GS = 32
DOWN,LEFT,RIGHT,UP = 0,1,2,3

def split_image(image):
    """32x128のキャラクターイメージを32x32の4枚のイメージに分割
    分割したイメージを格納したリストを返す"""
    imageList = []
    for i in range(0, 128, GS):
        for j in range(0, 128, GS):
            surface = pygame.Surface((GS,GS))
            surface.blit(image, (0,0), (j, i,GS,GS))
            surface.set_colorkey(surface.get_at((0,0)), RLEACCEL)
            surface.convert()
            imageList.append(surface)
    return imageList


pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption('お店')
text_window = False
chara_dict  = {"3,2":"item_shop"}
#ここにフォントのパスを貼り付ける
font = pygame.font.Font(パス, 20)        
#ここにキャラクターのパスを貼り付ける
playerImgList = split_image(pygame.image.load(パス)) 
#ここにキャラクターのパスを貼り付ける
playerImgList2 = split_image(pygame.image.load(パス)) 
#ここにボタン音のパスを貼り付ける
sound = pygame.mixer.Sound(パス)
#ここにカーソル画像のパスを貼り付ける
cursor = pygame.image.load(パス)

x,y = 0,0
x2,y2 = 3,2
cx,cy = 0,0
chara_pos = 0
cursor_y = 26
cursor_x = 388
a = 0
direction = DOWN
direction2 = DOWN
animcycle = 24  
frame = 0
clock = pygame.time.Clock()

Gold = 200
item_list = []
buy_list = ["やくそう","どくけし","てんしのつばさ","高級やくそう","万能薬","テント","たいまつ"]
price_dict = {"やくそう": 10,"どくけし": 20,"てんしのつばさ": 30,"高級やくそう": 50,"万能薬": 70,"テント": 100,"たいまつ": 15}
message_window = False
choose = False
buysell_window = False
buy_window = False
sell_window = False
buy,sell = 0,1
shop_action = buy
none_shop,item_shop = 0,1
shop = none_shop
cmd = 0
num = 0
 
while True:
    clock.tick(60)
    screen.fill((128,128,128))
    # 経過フレーム数に応じて表示する画像を変える
    frame += 1
    player = playerImgList[int(direction*4+frame/animcycle%4)]
    player2 = playerImgList2[int(direction2*4+frame/animcycle%4)]
    if a == 0:
        message = "ここはおみせです"
    screen.blit(player, (x*GS, y*GS))
    screen.blit(player2, (x2*GS, y2*GS))
    #メッセージウィンドゥ
    if message_window == True:
        pygame.draw.rect(screen, (0, 0, 0), Rect(70, 320, 500, 140))
        pygame.draw.rect(screen, (255, 255, 255), Rect(70, 320, 500, 140), 5)
        text = font.render(message, True, (255,255,255))
        screen.blit(text, (90, 350))

    #"はい"と"いいえ"の枠
    if choose == True:
        pygame.draw.rect(screen, (0, 0, 0), Rect(485, 5, 150, 100))
        pygame.draw.rect(screen, (255, 255, 255), Rect(485, 5, 150, 100), 3)
        text = font.render("はい", True, (255,255,255))                
        screen.blit(text, (513, 28))
        text1 = font.render("いいえ", True, (255,255,255))                
        screen.blit(text1, (513, 58))
    #"売り買い"の枠
    if buysell_window == True:
        a = 1
        pygame.draw.rect(screen, (0, 0, 0), Rect(385, 5, 250, 100))
        pygame.draw.rect(screen, (255, 255, 255), Rect(385, 5, 250, 100), 3)
        text = font.render("買いに来た", True, (255,255,255))                
        screen.blit(text, (413, 28))
        text1 = font.render("売りに来た", True, (255,255,255))                
        screen.blit(text1, (413, 58))
        
    #アイテム項目の枠(250*246)7個
    if buy_window == True:
        pygame.draw.rect(screen, (0, 0, 0), Rect(320, 60, 250, 246))
        pygame.draw.rect(screen, (255, 255, 255), Rect(320, 60, 250, 246), 3)
        if shop == item_shop  and shop_action == buy:
            text = font.render(buy_list[0], True, (255,255,255))                
            screen.blit(text, (348, 83))
            text = font.render(buy_list[1], True, (255,255,255))                
            screen.blit(text, (348, 113))
            text = font.render(buy_list[2], True, (255,255,255))
            screen.blit(text, (348, 143))
            text = font.render(buy_list[3], True, (255,255,255))
            screen.blit(text, (348, 173))
            text = font.render(buy_list[4], True, (255,255,255))
            screen.blit(text, (348, 203))
            text = font.render(buy_list[5], True, (255,255,255))
            screen.blit(text, (348, 233))
            text = font.render(buy_list[6], True, (255,255,255))
            screen.blit(text, (348, 263))
    if choose or buysell_window or buy_window:
        screen.blit(cursor,(cursor_x, cursor_y))    
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type==KEYDOWN:
            if event.key==K_SPACE:
                pygame.quit()
                sys.exit()

            elif  event.key==K_DOWN and shop != item_shop:
                direction = DOWN
                y += 1      
            elif  event.key==K_UP and shop != item_shop:
                direction = UP
                y -= 1
            elif event.key==K_RIGHT and shop != item_shop:
                direction = RIGHT
                x += 1
            elif  event.key==K_LEFT and shop != item_shop:
                direction = LEFT
                x -= 1

            elif event.key == K_z:
                if shop != item_shop: 
                    if  direction == DOWN:
                        cx = x
                        cy = y + 1
                    elif  direction == UP:
                        cx = x
                        cy = y - 1
                    elif  direction == RIGHT:
                        cx = x + 1
                        cy = y
                    elif  direction == LEFT:
                        cx = x - 1
                        cy = y

                chara_pos = f"{cx},{cy}"
                if chara_pos in chara_dict and shop != item_shop:
                    message_window = True
                    if chara_dict[chara_pos] == "item_shop":
                        shop = item_shop
                        buysell_window = True
                        
        #道具屋
                if shop == item_shop:
                    #道具　買う
                    if shop_action == buy:
                        if cmd == 0 and a == 1:                                
                            a = 2
                            cursor_x = 325
                            cursor_y = 81
                            message = "なにを　かっていかれますか？"
                            buy_window = True
                            buysell_window = False

                    #商品を決定した時
                        elif a == 2:
                            sound.play()
                            buy_window = False
                            choose = True
                            a = 3
                            cursor_x = 488
                            cursor_y = 26
                            message = f"{price_dict[buy_list[num]]}ゴールド　になりますが？"
                            item_name = buy_list[cmd]
                    #値段を聞かれて、”はい”を選んだ時
                        elif cmd == 0 and a == 3 and Gold >= price_dict[buy_list[num]]:                                
                            choose = False
                            a = 4
                            item_list.append(buy_list[num])
                            Gold -= price_dict[buy_list[num]]
                            message = "またおこしくださいませ"
                        elif cmd == 0 and a == 3 and Gold < price_dict[buy_list[num]]:                                
                            choose = False
                            a = 3
                            message = "おかねがたりません"
                            cmd = 1

                    #値段を聞かれて、”いいえ”を選んだ時
                    #アイテム項目に戻る
                        elif cmd == 1 and a == 3:
                            sound.play()
                            message = "なにを　かっていかれますか？"
                            choose = False
                            buy_window = True
                            a = 2
                            cmd = 0                                        
                            cursor_x = 325
                            cursor_y = 81
                            num = 0
                            
                    #またおこしくださいませの後、閉じる
                        elif a == 4:                             
                            a = 0
                            message_window = False
                            cmd = 0
                            cursor_y = 26
                            cursor_x = 388
                            shop = none_shop
                            num = 0

                        

            elif event.key == K_DOWN:
                if choose == True and cmd == 0:
                    cmd = 1
                    cursor_y += 30
                elif buysell_window == True and cmd == 0:
                    cmd = 1
                    cursor_y += 30
                    shop_action = sell
                elif buy_window == True and num < 6:
                    num += 1
                    buy_list[num]
                    cursor_y += 30
            elif event.key == K_UP:
                if choose == True and cmd == 1:
                    cmd = 0
                    cursor_y -= 30
                elif buysell_window == True and cmd == 1:
                    cmd = 0
                    cursor_y -= 30
                    shop_action = buy
                elif buy_window == True and num > 0:
                    num -= 1
                    buy_list[num]
                    cursor_y -= 30
            elif event.key == K_x:
                if a == 2:
                    sound.play()
                    message = "ここはどうぐやです"
                    buy_window = False
                    buysell_window = True
                    a = 1
                    cmd = 0                                        
                    num = 0
                    cursor_x = 388
                    cursor_y = 26
                elif a == 1:
                    message_window = False
                    buysell_window = False
                    shop = none_shop
                    a = 0
                    cmd = 0
                    num = 0
                    cursor_x = 388
                    cursor_y = 26

                    
```
</details>

 
# カーソル画像作成

<details><summary>ここをクリックしてください</summary>

```python:
import numpy as np
import cv2

# キャンバスのサイズ
canvas_size = (25, 25)

# キャンバスを作成（透明にするためにアルファチャンネルを使用）
canvas = np.zeros((canvas_size[1], canvas_size[0], 4), dtype=np.uint8)

# 三角形の頂点座標
triangle_vertices = np.array([[12, 5], [5, 15], [19, 15]], np.int32)
triangle_vertices = triangle_vertices.reshape((-1, 1, 2))

# 三角形を描画（白色で）色の指定が右端と左端でpygameとは逆になってる
cv2.fillPoly(canvas, [triangle_vertices], (255, 255, 255, 255))
rotated_cw90 = cv2.rotate(canvas, cv2.ROTATE_90_CLOCKWISE)
# 画像を保存
output_path = "cursor.png"
cv2.imwrite(output_path, rotated_cw90)

print(f"画像が{output_path}に保存されました。")


```

cv2.fillPoly(canvas, [triangle_vertices], (255, 255, 255, 255))
cv2の色の順序はBGR
pygameの色の順序はRGB
透明度もcv2は０ではなく２５５が透明

</details> 

# お店(売り買い)

<details><summary>ここをクリックしてください</summary>

```python
import pygame
from pygame.locals import *
import sys

GS = 32
DOWN,LEFT,RIGHT,UP = 0,1,2,3

def split_image(image):
    imageList = []
    for i in range(0, 128, GS):
        for j in range(0, 128, GS):
            surface = pygame.Surface((GS,GS))
            surface.blit(image, (0,0), (j, i,GS,GS))
            surface.set_colorkey(surface.get_at((0,0)), RLEACCEL)
            surface.convert()
            imageList.append(surface)
    return imageList


pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption('お店(売り買い)')

#ロード

#ここにフォントのパスを貼り付ける
font = pygame.font.Font(パス, 20)        
#ここにキャラクターのパスを貼り付ける
playerImgList = split_image(pygame.image.load(パス)) 
#ここにキャラクターのパスを貼り付ける
playerImgList2 = split_image(pygame.image.load(パス)) 
#ここにボタン音のパスを貼り付ける
sound = pygame.mixer.Sound(パス)
#ここにカーソル画像のパスを貼り付ける
cursor = pygame.image.load(パス)

chara_dict  = {"3,2":"item_shop"}
x,y = 0,0
x2,y2 = 3,2
cx,cy = 0,0
chara_pos = 0
cursor_y = 26
cursor_x = 388
a = 0
direction = DOWN
direction2 = DOWN
animcycle = 24  
frame = 0
clock = pygame.time.Clock()

#お店

Gold = 200
item_list = []
buy_list = ["やくそう","どくけし","てんしのつばさ","高級やくそう","万能薬","テント","たいまつ"]
price_dict = {"やくそう": 10,"どくけし": 20,"てんしのつばさ": 30,"高級やくそう": 50,"万能薬": 70,"テント": 100,"たいまつ": 15}
message_window = False
choose = False
buysell_window = False
shop_window = False
buy,sell = 0,1
shop_action = buy
none_shop,item_shop = 0,1
shop = none_shop
cmd = 0
num = 0

item_index1 = 0
item_index2 = 1
item_index3 = 2
item_index4 = 3
item_index5 = 4
item_index6 = 5
item_index7 = 6


white = (255,255,255)
 
while True:
    clock.tick(60)
    screen.fill((128,128,128))
    
    frame += 1
    player = playerImgList[int(direction*4+frame/animcycle%4)]
    player2 = playerImgList2[int(direction2*4+frame/animcycle%4)]
    if a == 0:
        message = "ここはおみせです"
    screen.blit(player, (x*GS, y*GS))
    screen.blit(player2, (x2*GS, y2*GS))
    #メッセージウィンドゥ
    if message_window == True:
        pygame.draw.rect(screen, (0, 0, 0), Rect(70, 320, 500, 140))
        pygame.draw.rect(screen, white, Rect(70, 320, 500, 140), 5)
        text = font.render(message, True, white)
        screen.blit(text, (90, 350))

    #"はい"と"いいえ"の枠
    if choose == True:
        pygame.draw.rect(screen, (0, 0, 0), Rect(485, 5, 150, 100))
        pygame.draw.rect(screen, white, Rect(485, 5, 150, 100), 3)
        text = font.render("はい", True, white)                
        screen.blit(text, (513, 28))
        text1 = font.render("いいえ", True, white)                
        screen.blit(text1, (513, 58))
    #"売り買い"の枠
    if buysell_window == True:
        a = 1
        pygame.draw.rect(screen, (0, 0, 0), Rect(385, 5, 250, 100))
        pygame.draw.rect(screen, white, Rect(385, 5, 250, 100), 3)
        text = font.render("買いに来た", True, white)                
        screen.blit(text, (413, 28))
        text1 = font.render("売りに来た", True, white)                
        screen.blit(text1, (413, 58))
        
    #アイテム項目の枠(250*246)7個
    if shop_window == True:
        pygame.draw.rect(screen, (0, 0, 0), Rect(320, 60, 250, 246))
        pygame.draw.rect(screen, white, Rect(320, 60, 250, 246), 3)
        if shop == item_shop  and shop_action == buy:
            text = font.render(buy_list[0], True, white)                
            screen.blit(text, (348, 83))
            text = font.render(buy_list[1], True, white)                
            screen.blit(text, (348, 113))
            text = font.render(buy_list[2], True, white)
            screen.blit(text, (348, 143))
            text = font.render(buy_list[3], True, white)
            screen.blit(text, (348, 173))
            text = font.render(buy_list[4], True, white)
            screen.blit(text, (348, 203))
            text = font.render(buy_list[5], True, white)
            screen.blit(text, (348, 233))
            text = font.render(buy_list[6], True, white)
            screen.blit(text, (348, 263))
        if shop == item_shop  and shop_action == sell:
            if len(item_list) >= 1:
                text = font.render(item_list[item_index1], True, white)      
                screen.blit(text, (348, 83))
            if len(item_list) >= 2:
                text = font.render(item_list[item_index2], True, white)      
                screen.blit(text, (348, 113))
            if len(item_list) >= 3:
                text = font.render(item_list[item_index3], True, white)      
                screen.blit(text, (348, 143))
            if len(item_list) >= 4:
                text = font.render(item_list[item_index4], True, white)      
                screen.blit(text, (348, 173))
            if len(item_list) >= 5:
                text = font.render(item_list[item_index5], True, white)      
                screen.blit(text, (348, 203))
            if len(item_list) >= 6:
                text = font.render(item_list[item_index6], True, white)      
                screen.blit(text, (348, 233))
            if len(item_list) >= 7:
                text = font.render(item_list[item_index7], True, white)      
                screen.blit(text, (348, 263))
                
    if choose or buysell_window or shop_window:
        screen.blit(cursor,(cursor_x, cursor_y))    
    pygame.display.update()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type==KEYDOWN:
            if event.key==K_SPACE:
                pygame.quit()
                sys.exit()

            elif  event.key==K_DOWN and shop != item_shop:
                direction = DOWN
                y += 1      
            elif  event.key==K_UP and shop != item_shop:
                direction = UP
                y -= 1
            elif event.key==K_RIGHT and shop != item_shop:
                direction = RIGHT
                x += 1
            elif  event.key==K_LEFT and shop != item_shop:
                direction = LEFT
                x -= 1

            elif event.key == K_z:
                if shop != item_shop: 
                    if  direction == DOWN:
                        cx = x
                        cy = y + 1
                    elif  direction == UP:
                        cx = x
                        cy = y - 1
                    elif  direction == RIGHT:
                        cx = x + 1
                        cy = y
                    elif  direction == LEFT:
                        cx = x - 1
                        cy = y

                chara_pos = f"{cx},{cy}"
                if chara_pos in chara_dict and shop != item_shop:
                    sound.play()
                    message_window = True
                    if chara_dict[chara_pos] == "item_shop":
                        shop = item_shop
                        buysell_window = True
                        
        #道具屋
                if shop == item_shop:
            #アイテム買う
                    if shop_action == buy:
                        if cmd == 0 and a == 1:
                            sound.play()
                            shop_window = True
                            buysell_window = False
                            a = 2
                            cursor_x = 325
                            cursor_y = 81
                            message = "なにを　かっていかれますか？"

                    #商品を決定した時
                        elif a == 2:
                            sound.play()
                            choose = True
                            shop_window = False
                            a = 3
                            cursor_x = 488
                            cursor_y = 26
                            message = f"{price_dict[buy_list[num]]}ゴールド　になりますが？"
                            
                    #値段を聞かれて、”はい”を選んだ時
                        elif cmd == 0 and a == 3 and Gold >= price_dict[buy_list[num]]:                                
                            sound.play()
                            choose = False
                            a = 4
                            message = "またおこしくださいませ"
                            item_list.append(buy_list[num])
                            Gold -= price_dict[buy_list[num]]
                        elif cmd == 0 and a == 3 and Gold < price_dict[buy_list[num]]:                                
                            sound.play()
                            choose = False
                            a = 3
                            cmd = 1
                            message = "おかねがたりません"

                    #値段を聞かれて、”いいえ”を選んだ時
                    #アイテム項目に戻る
                        elif cmd == 1 and a == 3:
                            sound.play()
                            choose = False
                            shop_window = True
                            a = 2
                            cmd = 0                                        
                            num = 0
                            cursor_x = 325
                            cursor_y = 81
                            message = "なにを　かっていかれますか？"
                            
                    #またおこしくださいませの後、閉じる
                        elif a == 4:                             
                            sound.play()
                            message_window = False
                            a = 0
                            cmd = 0
                            num = 0
                            cursor_y = 26
                            cursor_x = 388
                            shop = none_shop

                        
            #アイテム売る            
                    if shop_action == sell:
                        if cmd == 1 and a == 1 and 0 != len(item_list): 
                            sound.play()
                            shop_window = True
                            buysell_window = False
                            a = 2
                            cmd = 0
                            cursor_x = 325
                            cursor_y = 81
                            message = "なにを　うっていかれますか？"
                            #sell_item = True
                            shop_action = sell
                            
                    #商品を決定した時
                        elif a == 2:
                            sound.play()
                            choose = True
                            shop_window = False
                            a = 3
                            cursor_x = 488
                            cursor_y = 26
                            message = f"{price_dict[item_list[num]] // 2}ゴールド　になりますが？"

                    #値段を聞かれて、”はい”を選んだ時
                        elif cmd == 0 and a == 3:                                
                            sound.play()
                            choose = False
                            a = 4
                            message = "またおこしくださいませ"
                            Gold += price_dict[item_list[num]] // 2
                            del item_list[num]

                    #値段を聞かれて、”いいえ”を選んだ時
                    #アイテム項目に戻る
                        elif cmd == 1 and a == 3:
                            sound.play()
                            choose = False
                            shop_window = True
                            a = 2
                            cmd = 0                                        
                            num = 0
                            cursor_x = 325
                            cursor_y = 81
                            message = "なにを　うっていかれますか？"
                            
                    #またおこしくださいませの後、閉じる
                        elif a == 4:                             
                            sound.play()
                            message_window = False
                            a = 0
                            cmd = 0
                            num = 0
                            cursor_y = 26
                            cursor_x = 388
                            shop_action = buy
                            shop = none_shop
                            
            elif event.key == K_DOWN:
                if choose == True and cmd == 0:
                    sound.play()
                    cmd = 1
                    cursor_y += 30
                    
                elif buysell_window == True and cmd == 0:
                    sound.play()
                    cmd = 1
                    cursor_y += 30
                    shop_action = sell
                    
                elif shop_action == buy and num < 6:
                    sound.play()
                    num += 1
                    cursor_y += 30
                    buy_list[num]
                    
                elif shop_action == sell and num < len(item_list) - 1:
                    if cursor_y != 261:
                        sound.play()
                        num += 1
                        cursor_y += 30
                        
                    elif cursor_y == 261 and num < len(item_list) - 1:
                        sound.play()
                        num += 1
                        item_index1 += 1
                        item_index2 += 1
                        item_index3 += 1
                        item_index4 += 1
                        item_index5 += 1
                        item_index6 += 1
                        item_index7 += 1
                        
            elif event.key == K_UP:
                if choose == True and cmd == 1:
                    sound.play()
                    cmd = 0
                    cursor_y -= 30
                    
                elif buysell_window == True and cmd == 1:
                    sound.play()
                    cmd = 0
                    cursor_y -= 30
                    shop_action = buy
                    
                elif shop_action == buy and num > 0:
                    sound.play()
                    num -= 1
                    cursor_y -= 30
                    buy_list[num]
                    
                elif shop_action == sell:
                    if cursor_y != 81:
                        sound.play()
                        num -= 1
                        cursor_y -= 30
                        
                    elif cursor_y == 81 and num > 0:
                        sound.play()
                        num -= 1
                        item_index1 -= 1
                        item_index2 -= 1
                        item_index3 -= 1
                        item_index4 -= 1
                        item_index5 -= 1
                        item_index6 -= 1
                        item_index7 -= 1

            elif event.key == K_x:
                if a == 2:
                    sound.play()
                    message = "ここはどうぐやです"
                    shop_window = False
                    buysell_window = True
                    a = 1
                    cmd = 0                                        
                    num = 0
                    cursor_x = 388
                    cursor_y = 26
                    shop_action = buy
                    item_index1 = 0
                    item_index2 = 1
                    item_index3 = 2
                    item_index4 = 3
                    item_index5 = 4
                    item_index6 = 5
                    item_index7 = 6
                    
                elif a == 1:
                    sound.play()
                    buysell_window = False
                    message_window = False
                    a = 0
                    cmd = 0
                    num = 0
                    cursor_x = 388
                    cursor_y = 26
                    shop = none_shop


```

エラーの修正

elif event.key == K_x:のところに

item_index1 = 0
item_index2 = 1
item_index3 = 2
item_index4 = 3
item_index5 = 4
item_index6 = 5
item_index7 = 6

を追加しました。

</details> 
#

<details><summary>ここをクリックしてください</summary>

```python:


```
</details> 
#

<details><summary>ここをクリックしてください</summary>

```python:


```
</details> 
#

<details><summary>ここをクリックしてください</summary>

```python:


```
</details>