欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-01-15 22:56:52
本文实例为大家分享了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 '{}\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()

以上就是整个项目的所有代码了,在这个小项目中,我使用了类继承的方法,在不断修改代码的同时,也让我更加熟悉了类继承的特点和用法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。