python实现诗歌游戏(类继承)


Posted in Python onFebruary 26, 2019

本文实例为大家分享了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 相关文章推荐
快速了解Python相对导入
Jan 12 Python
Python使用Selenium模块实现模拟浏览器抓取淘宝商品美食信息功能示例
Jul 18 Python
基于Python实现用户管理系统
Feb 26 Python
详解python做UI界面的方法
Feb 27 Python
python使用phoenixdb操作hbase的方法示例
Feb 28 Python
Python匿名函数/排序函数/过滤函数/映射函数/递归/二分法
Jun 05 Python
python日期与时间戳的各种转换示例
Feb 12 Python
keras的三种模型实现与区别说明
Jul 03 Python
如何用Python绘制3D柱形图
Sep 16 Python
如何用python 操作zookeeper
Dec 28 Python
python基于tkinter实现gif录屏功能
May 19 Python
python 办公自动化——基于pyqt5和openpyxl统计符合要求的名单
May 25 Python
Python实现简单查找最长子串功能示例
Feb 26 #Python
基于Python实现用户管理系统
Feb 26 #Python
python selenium firefox使用详解
Feb 26 #Python
Django实现学员管理系统
Feb 26 #Python
Python实现读取txt文件中的数据并绘制出图形操作示例
Feb 26 #Python
Django实现学生管理系统
Feb 26 #Python
python爬取微信公众号文章的方法
Feb 26 #Python
You might like
关于php fread()使用技巧
2010/01/22 PHP
ThinkPHP查询返回简单字段数组的方法
2014/08/25 PHP
javascript FormatNumber函数实现方法
2008/12/30 Javascript
获取当前点击按钮的id用this.id实现
2014/03/17 Javascript
Javascript中对象继承的实现小例
2014/05/12 Javascript
php常见的页面跳转方法汇总
2015/04/15 Javascript
AngularJS实现元素显示和隐藏的几个案例
2015/12/09 Javascript
jQuery实现TAB选项卡切换特效简单演示
2016/03/04 Javascript
JS基于递归算法实现1,2,3,4,5,6,7,8,9倒序放入数组中的方法
2017/01/03 Javascript
利用nodejs监控文件变化并使用sftp上传到服务器
2017/02/18 NodeJs
实现微信小程序的wxml文件和wxss文件在webstrom的支持
2017/06/12 Javascript
javascript中神奇的 Date对象小结
2017/10/12 Javascript
javascript获取图片的top N主色值方法详解
2018/01/26 Javascript
详解javascript 正则表达式之分组与前瞻匹配
2018/05/30 Javascript
JavaScript实现多态和继承的封装操作示例
2018/08/20 Javascript
Vue跨域请求问题解决方案过程解析
2020/08/07 Javascript
[03:54]Ehome出征西雅图 回顾2016国际邀请赛晋级之路
2016/08/02 DOTA
python基于socket实现网络广播的方法
2015/04/29 Python
python 求某条线上特定x值或y值的点坐标方法
2019/07/09 Python
python下PyGame的下载与安装过程及遇到问题
2019/08/04 Python
python 利用turtle库绘制笑脸和哭脸的例子
2019/11/23 Python
Python+opencv+pyaudio实现带声音屏幕录制
2019/12/23 Python
Python内置函数locals和globals对比
2020/04/28 Python
Python3爬虫里关于Splash负载均衡配置详解
2020/07/10 Python
WINDOWS域的具体实现方式是什么
2014/02/20 面试题
团组织关系介绍信
2014/01/12 职场文书
春节活动策划方案
2014/01/24 职场文书
上班打牌检讨书
2014/02/07 职场文书
2014党员批评和自我批评思想汇报
2014/09/21 职场文书
领导班子个人对照检查剖析材料
2014/09/29 职场文书
党的群众路线教育实践活动学习计划
2014/11/03 职场文书
2015年秋季学校开学标语
2015/07/16 职场文书
我爱我班主题班会
2015/08/13 职场文书
2016大学生毕业实习心得体会
2016/01/23 职场文书
2019暑期安全倡议书!
2019/06/27 职场文书
Pytorch 统计模型参数量的操作 param.numel()
2021/05/13 Python