Pythonゲーム作りの過程 その21

今回の目標

MROについて読み進める

今回の結果

MROについて読み進める
→未達成(312ページの内容が読み込めていない チャプター6を読まないといけない)

次回の目標

デコレータについて読み進める

 今日は参照透過性について調べていました。
 以下、今回のコードになります(変更箇所なし)

import subprocess
import time
import csv
from playsound import playsound #メモ windows11では古めのバージョンをインストールすること。pip install playsound==1.2.2
import pygame
import random
import sys
import string

class monster:#モンスターの設計。
    def __init__(self, level):
        self.level=level
        
# 問題の入った辞書を引数に、シャッフルした選択肢と解答のリスト
def get_answer(q):#関数定義
    shuffle_kouho=q['kouho']
    #print(shuffle_kouho) 230501 こちらのprint文は取り除きました。
    random.shuffle(shuffle_kouho)
    answer_str=shuffle_kouho.index(q['answer']) #インデックスを返す。
    return [shuffle_kouho,answer_str]

# 回答者が答えた選択肢の文字列a1(A,B,C,Dとか)と正解の選択肢のインデックス(0,1,2,3とか)を引数に、一致しているときはTrue,一致しないときはFalseを返す
def sf(a1,a2):#success,failuer
    if a1==chr(65+a2):
        return 1
    else:
        return 0

# CSVのファイル名を指定して、問題が格納されたリストを返す
def csv2list(file_path):
    questions =[]
    with open(file_path, 'r',encoding="UTF-8") as f:
        reader = csv.reader(f)
        for line in reader:#ここでCSV1行ごとの処理が行われる
            #print(line)
            kouho_array = line[1].split('/') #鯏/鯵/鱒/鱚
            dict = {'question':line[0],'kouho':kouho_array,'answer':line[2],'category':line[3],'level':line[4]}
            questions.append(dict)
        
        questions.pop(0)
    return questions

#引 数:出題する問題と全問題のディクショナリ
#戻り値:出題する問題のカテゴリにあった問題のみ
def categorize_questions(category,allquestions):#変数名が組み込み関数と一致していたので、tupleからquestion_tupleに変えました。
    categorized_questions=[]
    for question_tuple in allquestions:
        if category==question_tuple['category']:
            categorized_questions.append(question_tuple)
    return categorized_questions

#このbattleは1匹のモンスターとの戦闘に関わる関数
def battle():#戦闘時の関数定義  def battle(monster):
    i=0
    mhp=40 #主人公のHP
    ehp=50 #敵モンスターのHP

    pygame.mixer.init(frequency = 44100)
    bgm_sound = pygame.mixer.Sound("../素材/sound/battle.wav")
    bgm_sound2 = pygame.mixer.Sound("../素材/sound/quiz1.wav")
    bgm_sound3 = pygame.mixer.Sound("../素材/sound/quiz2.wav")
    bgm_sound4 = pygame.mixer.Sound("../素材/sound/madamada.mp3")
    bgm_sound5 = pygame.mixer.Sound("../素材/sound/kakugo.mp3")
    bgm_sound.play()

    #問題のデータベース。ここから問題がピックアップされて出題される。
    """
    questions =[
        {'question':"「洋琴」が表す楽器はどれ?",'kouho':['ピアノ','ギター','チェロ','ハープ'],'answer':"ピアノ",'category':'漢字'},
        {'question':"ラッコを漢字で書くとどれ?",'kouho':['海鼠','海獺','海狸','海犬'],'answer':"海獺",'category':'漢字'},
        {'question':"ガーナの首都は?",'kouho':['アクラ','アピア','アテネ','アンカラ'],'answer':"アクラ",'category':'地理'},
    ]"""
    
    questions = csv2list('Dict3.csv') #questionsが1匹のモンスターに相当する
    while len(questions)>0:
            # if i==0:
            #     ran = random.randint(1,3)
            #     if ran ==2 :
            #         bgm_sound5.play()  移転しました。

        if mhp<=0:
            bgm_sound4.play() 
            print("主人公は敗北した…")
            time.sleep(2)
            break
        elif ehp<=0:
            print("モンスターは倒れた!")
            break
        else:
            this_question = questions.pop(random.randint(0,len(questions)-1)) #questions[0] とかquestions[1]とか
            # this_question = questions[random.randint(0,2)] #questions[0] とかquestions[1]とか
            #print(this_question)
            #sys.exit( )
            """
            s1="漢字出題モンスターが現れた!"
            s2=s1.replace(s1,"")
            print(s1)
            time.sleep(2)
            print(s2)
            """
            #没になった。メモリ内容が変わるだけで、画面に出力したのは変わらない。
            
            
            #print(this_question['category'],end='')
            #print("出題モンスターが現れた!")
            #print("漢字出題モンスターが現れた!")
            if i==0:#初回のみモンスター名の表示するための変数
                ran = random.randint(1,3)
                if ran ==2 :
                    bgm_sound5.play()
                print(this_question['category']+"出題モンスターが現れた")#モンスターの名前の表示
                questions=categorize_questions(this_question['category'],questions)#questionsをカテゴリ統一したものに上書きする
                time.sleep(2)
                subprocess.run('CLS',shell=True)#2秒後に消す
            # if i>0:
            #     after_question= questions[t] 
            print("debug: ", end="")
            print(this_question['question'])#ここで表示された後にシャッフルされている!!
            #print(this_question['kouho'])
            ans_list=get_answer(this_question)
            #print(ans_list)
            #ans_list は次のような形 [['紋白蝶', '紋花蝦蛄', '秋刀魚', '背赤後家蜘蛛'], 1]
            print(ans_list[0])
            for j in range(0,len(ans_list[0])):
                print(chr(65+j)+': '+ans_list[0][j])#ASCIIコードで設定しました
            """
            for question_kouho in this_question['kouho']:
                print('候補: '+question_kouho)
            """
            
            
            # ans=input()
            # if ans=="A":
            #     bgm_sound2.play()
            #     print("モンスターは30のダメージを受けた!")
            #     #bgm_sound.stop()
            #     ehp=ehp-30
            #     time.sleep(1)
            #     break
            #ans=input()
            ans=input()#答えの入力を行わせる
            if sf(ans,ans_list[1]):#ans==chr(65+ans_list[1])
                bgm_sound2.play()
                print("正解!モンスターは30のダメージを受けた!")
                #bgm_sound.stop()
                ehp=ehp-30
                time.sleep(1)
                #break
            else:
                bgm_sound3.play()
                print("主人公は30のダメージを受けた!")
                mhp=mhp-30
                time.sleep(1)
            i=i+1
            time.sleep(2)
            subprocess.run('CLS',shell=True)
        if len(questions)<=0:
            print("問題数が不足しています。戦闘を中断します。")




battle()#確認用に呼び出し

"""
while my_hp :
    mondai = monster_attack(monster) #モンスターが出題する
    my_hp,monster_hp =player_attack(mondai,kaitou) #主人公が答える
    if monster_hp <= 0 :
        monster = monster_change()
  
"""

余談:料理について

 先週に久々に自分で夕飯を作りました。
 親の苦労はこうして徐々に学んでいくのだと思います。
 親の有難味(ありがたみ)が理解できる頃には、親元を離れて一人暮らしになっていると思います。