您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關如何使用python實現詩歌游戲的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
內容如下
具體游戲有:根據上句猜下句、猜作者、猜朝代、猜詩名等
如果有更好玩兒的游戲,不妨自己寫一下
1.首先,先把搜集到的詩歌全部放到一個txt文件下,命名為poems.txt
2.其次,再定義一個poem類,執行的時候輸出詩歌的名字,作者,朝代等,代碼如下:
class Poem: def __init__(self): self.title = '' self.dynasty = '' self.author = '' self.sentences = [] def __str__(self): return '{}\n{}\n{}\n{}'.format( self.title, self.dynasty, self.author, '\n'.join(self.sentences))
3.加載出來詩歌的所有部分,代碼如下:
from enum import Enum from poem import Poem Poems = [] def load(): class ReadState(Enum): Nothing = 0 Title = 1 DynastyAndAuthor = 2 Sentences = 3 print('開始加載詩歌') f = open('poems.txt', encoding='utf-8') lines = f.readlines() state = ReadState.Title poem = None for ln in lines: line = ln.strip() if len(line) > 0: try: if line.startswith('-'): if poem is not None: Poems.append(poem) print('.', end='') poem = Poem() poem.title = line.lstrip('-') state = ReadState.DynastyAndAuthor continue if state == ReadState.DynastyAndAuthor: dynasty_author = line.split(' ') poem.dynasty = dynasty_author[0] poem.author = dynasty_author[-1] state = ReadState.Sentences continue if state == ReadState.Sentences: poem.sentences.append(line) except IndexError as e: print(line) print('\n共加載{}首詩歌'.format(len(Poems))) print() load()
4.下面開始寫具體的功能代碼,以猜朝代和猜下句為例。
(1)猜朝代代碼如下
# -*- coding: utf-8 -*- __author__ = 'wj' __date__ = '2018/7/20 9:54' from game import Game class DynastyGame(Game): def __init__(self, poems): super(DynastyGame, self).__init__(poems) self.name = '猜朝代' self.rules = '根據詩歌猜作者所處的朝代,猜對加10分,猜錯不扣分。' def design_question(self): """設計問題及答案""" self.answer = self.poem.dynasty # 打印題目 print(self.poem.title) print(self.poem.author) print() # enumerate() 會將列表中的索引和數據一一對應取出 # i 數據的索引 s數據 for i, s in enumerate(self.poem.sentences): print(s) if i > 5: print('...') break print() def get_answer(self): """獲取答案""" # 1.輸出問題 print('這首詩的作者是:{}'.format(self.poem.author)) while True: self.user_answer = input('請輸入他/她所在的朝代:') # 2.判斷是否輸入了內容 if self.user_answer: break def judge(self): """判斷答案""" is_ok = super(DynastyGame, self).judge() if is_ok: self.score += 10 print('回答正確!') else: print('回答錯誤!') print('{}所在的朝代是:{}'.format(self.poem.author, self.poem.dynasty)) print('您目前的得分為:{}'.format(self.score)) if __name__ == '__main__': from load_poems import Poems dynasty = DynastyGame(Poems) dynasty.run()
(2)根據上句猜出下一句的具體代碼如下:
# -*- coding: utf-8 -*- __author__ = 'wj' __date__ = '2018/7/20 10:45' from game import Game import random class FillGame(Game): def __init__(self, poems): super(FillGame, self).__init__(poems) self.name = '對下句' self.rules = '根據上一句,對出下一句,答對得10分,答錯不扣分' def design_question(self): # 隨機取出索引 index = random.randint(0, len(self.poem.sentences)-2) # 取出問題答案 answer = self.poem.sentences[index + 1] # 切片 切出不帶標點的詩句 self.answer = answer[:-1] # 題目 print('{}_____________'.format(self.poem.sentences[index])) print() def get_answer(self): while True: self.user_answer = input('請寫出這句詩的下一句:') if self.user_answer: break def judge(self): if super(FillGame, self).judge(): self.score += 10 print('回答正確!') else: print('回答錯誤!') print('正確答案是:{}'.format(self.answer)) Game.print_line() print('您目前的得分為:{}'.format(self.score)) if __name__ == '__main__': from load_poems import Poems fill = FillGame(Poems) fill.run()
注:猜作者游戲和猜詩名游戲的代碼和猜朝代類似
5.最后把所有游戲整合到一個py文件里(注意:一個游戲是一個py文件,自己在里邊聲明類,最后只需要調用一下就行),整合后的代碼如下所示:
from load_poems import Poems from game import Game from dynasty_game import DynastyGame from fill_game import FillGame from author_game import AuthorGame from title_game import TitleGame class PoemGame(object): """詩詞游戲""" def __init__(self): self.version = '1.0' self.games = [DynastyGame(Poems), FillGame(Poems),AuthorGame(Poems),TitleGame(Poems)] def list(self): """列出所有游戲玩法""" print('請選擇玩法:') Game.print_double_line() for i, g in enumerate(self.games): print('{:<10}{}'.format(i+1, g.name)) Game.print_line() def play(self): """根據用戶選擇的玩法執行游戲""" while True: self.list() idx = input('請輸入游戲編號,輸入q退出:') if idx == 'q': print('Bye Bye~') break Game.print_line() # 根據索引取出圖形對象 idx = int(idx) g = self.games[idx - 1] g.run() def run(self): """運行游戲""" print('歡迎來到詩詞詩詞大會') print('v{}'.format(self.version)) self.play() if __name__ == '__main__': g = PoemGame() g.run()
感謝各位的閱讀!關于“如何使用python實現詩歌游戲”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。