欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現(xiàn)詩歌游戲(類繼承)

 更新時間:2019年02月26日 11:04:26   作者:我是李玉峰  
這篇文章主要為大家詳細介紹了python實現(xiàn)詩歌游戲,根據(jù)上句猜下句、猜作者、猜朝代、猜詩名,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了python實現(xiàn)詩歌游戲的具體代碼,供大家參考,具體內(nèi)容如下

具體游戲有:根據(jù)上句猜下句、猜作者、猜朝代、猜詩名等

如果有更好玩兒的游戲,不妨自己寫一下

1.首先,先把搜集到的詩歌全部放到一個txt文件下,命名為poems.txt

2.其次,再定義一個poem類,執(zhí)行的時候輸出詩歌的名字,作者,朝代等,代碼如下:

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 = '根據(jù)詩歌猜作者所處的朝代,猜對加10分,猜錯不扣分。'
 
  def design_question(self):
    """設計問題及答案"""
    self.answer = self.poem.dynasty
 
    # 打印題目
    print(self.poem.title)
    print(self.poem.author)
    print()
    # enumerate() 會將列表中的索引和數(shù)據(jù)一一對應取出
    # i 數(shù)據(jù)的索引  s數(shù)據(jù)
    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.判斷是否輸入了內(nèi)容
      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)根據(jù)上句猜出下一句的具體代碼如下:

# -*- 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 = '根據(jù)上一句,對出下一句,答對得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文件,自己在里邊聲明類,最后只需要調(diào)用一下就行),整合后的代碼如下所示:

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):
    """根據(jù)用戶選擇的玩法執(zhí)行游戲"""
    while True:
      self.list()
      idx = input('請輸入游戲編號,輸入q退出:')
      if idx == 'q':
        print('Bye Bye~')
        break
      Game.print_line()
 
      # 根據(jù)索引取出圖形對象
      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()

以上就是整個項目的所有代碼了,在這個小項目中,我使用了類繼承的方法,在不斷修改代碼的同時,也讓我更加熟悉了類繼承的特點和用法。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python?isdigit()函數(shù)使用詳解

    Python?isdigit()函數(shù)使用詳解

    這篇文章主要介紹了Python?isdigit()函數(shù)使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-07-07
  • pytorch動態(tài)神經(jīng)網(wǎng)絡(擬合)實現(xiàn)

    pytorch動態(tài)神經(jīng)網(wǎng)絡(擬合)實現(xiàn)

    這篇文章主要介紹了pytorch動態(tài)神經(jīng)網(wǎng)絡(擬合)實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • Python?列表中的刪除操作之del、remove?和?pop?的區(qū)別

    Python?列表中的刪除操作之del、remove?和?pop?的區(qū)別

    在Python中,列表(list)是一種非常靈活的數(shù)據(jù)結(jié)構(gòu),它允許我們存儲一系列的元素,在刪除元素時,我們可以使用三種不同的方法:del、remove?和?pop,每種方法都有其特定的用途和行為,了解它們的區(qū)別可以幫助我們更有效地使用列表,感興趣的朋友跟隨小編一起看看吧
    2024-05-05
  • Python代碼覆蓋率統(tǒng)計工具coverage.py用法詳解

    Python代碼覆蓋率統(tǒng)計工具coverage.py用法詳解

    這篇文章主要介紹了Python代碼覆蓋率統(tǒng)計工具coverage.py用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-11-11
  • Python字符串的創(chuàng)建和駐留機制詳解

    Python字符串的創(chuàng)建和駐留機制詳解

    字符串駐留是一種在內(nèi)存中僅保存一份相同且不可變字符串的方法,本文重點給大家介紹Python字符串的創(chuàng)建和駐留機制,感興趣的朋友跟隨小編一起看看吧
    2022-02-02
  • Python?LeNet網(wǎng)絡詳解及pytorch實現(xiàn)

    Python?LeNet網(wǎng)絡詳解及pytorch實現(xiàn)

    LeNet主要用來進行手寫字符的識別與分類,并在美國的銀行中投入了使用。本文主要為大家詳細介紹了LetNet以及通過pytorch實現(xiàn)LetNet,感興趣的小伙伴可以學習一下
    2021-11-11
  • 淺談django框架集成swagger以及自定義參數(shù)問題

    淺談django框架集成swagger以及自定義參數(shù)問題

    這篇文章主要介紹了淺談django框架集成swagger以及自定義參數(shù)問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • Python?網(wǎng)頁請求之requests庫的使用詳解

    Python?網(wǎng)頁請求之requests庫的使用詳解

    requests?是?Python?中比較常用的網(wǎng)頁請求庫,主要用來發(fā)送?HTTP?請求,在使用爬蟲或測試服務器響應數(shù)據(jù)時經(jīng)常會用到,使用起來十分簡潔,這篇文章主要介紹了Python?網(wǎng)頁請求之requests庫的使用詳解,需要的朋友可以參考下
    2022-09-09
  • python飛機大戰(zhàn)pygame游戲背景設計詳解

    python飛機大戰(zhàn)pygame游戲背景設計詳解

    這篇文章主要介紹了python飛機大戰(zhàn)pygame游戲背景設計,結(jié)合實例形式詳細分析了Python使用pygame模塊設計游戲背景相關(guān)原理、流程與實現(xiàn)技巧,需要的朋友可以參考下
    2019-12-12
  • 利用Python制作簡易的核酸檢測日歷

    利用Python制作簡易的核酸檢測日歷

    這篇文章主要為大家詳細介紹了如何利用Python語言制作簡易的核酸檢測日歷,文中的示例代碼講解詳細,感興趣的小伙伴可以動手嘗試一下
    2022-09-09

最新評論