python实现诗歌游戏(类继承)实现诗歌游戏(类继承)
主要为大家详细介绍了python实现诗歌游戏,根据上句猜下句、猜作者、猜朝代、猜诗名,具有一定的参考价
值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了python实现诗歌游戏的具体代码,供大家参考,具体内容如下
具体游戏有:根据上句猜下句、猜作者、猜朝代、猜诗名等
如果有更好玩儿的游戏,不妨自己写一下
1.首先,先把搜集到的诗歌全部放到一个txt文件下,命名为poems.txt
2.其次,再定义一个poem类,执行的时候输出诗歌的名字,作者,朝代等,代码如下:
class Poem:
def __init__(self):
self.title = ''
self.dynasty = ''
self.author = ''
self.sentences = []
def __str__(self):
return '{}{}{}{}'.format(
self.title, self.dynasty, self.author, ''.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('共加载{}首诗歌'.format(len(Poems)))
print()
load()