《Pygame游戏编程入门》学习——第3章 I/O、数据和字体:Trivia游戏

《Pygame游戏编程入门》学习——第3章 I/O、数据和字体:Trivia游戏

第3章 挑战 1

问题1. 修改Trivia游戏,使用已有的代码来扩展你的背景,加入自己的用户输入和问题。

思路:增加背景颜色(RGB.py)和中文字体。系统中已有的中文字体名称:stfangsong, stcaiyun, stheiti, stxinwei, stsong, stzhongsong, sthupo, stliti, stkaiti, stxingkai, stxihei

问题2. 修改Trivia游戏中包含问题的trivia_data.txt数据文件,添加几个新的航天学问题。作为替代方案,可以创建你自己选择的其他学科领域的问题。

思路:由于使用excel表格能更有条理的准备数据,所以将网上的10道天文学选择题2录入excel中,然后使用xlrd模块3直接从excel中读取数据。

提前准备好excel表格:

《Pygame游戏编程入门》学习——第3章 I/O、数据和字体:Trivia游戏

需要注意的是,xlrd模块只能识别Microsoft Excel 97-2003文件(×.xls),所以需要把以上表格另存为.xls文件。

; 问题3. 修改Trivia游戏,使得用户回答完最后一个问题之后,提示用户是想要再玩一次还是退出,而不是从头再开始回答。

思路: Trivia类增加一个布尔变量 end,用于判断用户是否已答完所有问题。在 show_question()方法中,如果 endTrue,则打印提示:”再玩一次(1),或退出(enter)”。 handle_input()方法用于响应用户数字1-4的输入, next_question()方法用于响应用户回车的输入,故在两个方法中分别实现再玩一次和退出的逻辑即可。

3.6_Trivia.py代码如下:

import sys, pygame, RGB, xlrd
from pygame.locals import *

class Trivia():
    def __init__( self ):
        self.data = {}
        self.current = 1
        self.total = 0
        self.correct = 0
        self.score = 0
        self.scored = False
        self.failed = False
        self.wronganswer = 0
        self.colors = [ RGB.White, RGB.White, RGB.White, RGB.White ]
        self.end = False

    def load_data( self ):
        workbook = xlrd.open_workbook( r'data.xls' )
        data_sheet = workbook.sheet_by_name( 'data' )
        self.total = data_sheet.nrows - 1
        for row in range( 1, data_sheet.nrows ):
            name = data_sheet.cell_value( row, 0 )
            self.data[ name ] = {}
            for col in range( 1, data_sheet.ncols ):
                attr = data_sheet.cell_value( 0, col )
                value = data_sheet.cell_value( row, col )
                self.data[ name ][ attr ] = value

    def show_question( self ):
        if self.end:
            print_text( font1, 110, 5, '再玩一次(1),或退出(enter)' )
            return

        print_text( font1, 210, 5, 'TRIVIA游戏' )
        print_text( font2, 190, 500-40, "按1-4回答问题", RGB.Purple )
        print_text( font2, 530, 15, "得分", RGB.Purple )
        print_text( font2, 550, 45, str( self.score ), RGB.Purple )

        self.correct = int(self.data[ self.current ][ '正确答案' ] )
        question = self.current
        print_text( font1, 5, 80, "问题" + str( question ) )
        print_text( font2, 5, 130, self.data[ self.current ][ '问题' ], RGB.Yellow )

        if self.scored:
            self.colors = [ RGB.White, RGB.White, RGB.White, RGB.White ]
            self.colors[ self.correct - 1 ] = RGB.Green
            print_text( font1, 230, 380, "正确!", RGB.Green )
            print_text( font2, 170, 420, "输入回车前往下一题", RGB.Green )
        elif self.failed:
            self.colors = [ RGB.White, RGB.White, RGB.White, RGB.White ]
            self.colors[ self.wronganswer - 1 ] = RGB.Red
            self.colors[ self.correct - 1 ] = RGB.Green
            print_text( font1, 230, 380, "错误!", RGB.Red )
            print_text( font2, 170, 420, "输入回车前往下一题", RGB.Red )

        print_text( font1, 5, 160, "答案" )
        print_text( font2, 20, 210, '1 - ' + self.data[ self.current ][ 'A' ], self.colors[ 0 ] )
        print_text( font2, 20, 240, '2 - ' + self.data[ self.current ][ 'B' ], self.colors[ 1 ] )
        print_text( font2, 20, 270, '3 - ' + self.data[ self.current ][ 'C' ], self.colors[ 2 ] )
        print_text( font2, 20, 300, '4 - ' + self.data[ self.current ][ 'D' ], self.colors[ 3 ] )

    def handle_input( self, number ):
        if self.end:
            self.end = False
            self.current = 1
            return

        if not self.scored and not self.failed:
            if number == self.correct:
                self.scored = True
                self.score += 1
            else:
                self.failed = True
                self.wronganswer = number

    def next_question( self ):
        if self.end:
            sys.exit( 0 )

        if self.scored or self.failed:
            self.scored = False
            self.failed = False
            self.correct = 0
            self.colors = [ RGB.White, RGB.White, RGB.White, RGB.White ]
            self.current += 1

            if self.current >= self.total:
                self.end = True

def print_text( font, x, y, text, color=RGB.White, shadow=True ):
    if shadow:
        imgText = font.render( text, True, RGB.Black )
        screen.blit( imgText, ( x - 2, y - 2 ) )
    imgText = font.render( text, True, color )
    screen.blit( imgText, ( x, y ) )

pygame.init()
screen = pygame.display.set_mode( ( 600, 500 ) )
pygame.display.set_caption( 'Trivia游戏' )
font1 = pygame.font.SysFont( 'stheiti', 36 )
font2 = pygame.font.SysFont( 'stheiti', 24 )
trivia = Trivia()
trivia.load_data()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYUP:
            if event.key == pygame.K_ESCAPE:
                sys.exit()
            elif event.key == pygame.K_1:
                trivia.handle_input( 1 )
            elif event.key == pygame.K_2:
                trivia.handle_input( 2 )
            elif event.key == pygame.K_3:
                trivia.handle_input( 3 )
            elif event.key == pygame.K_4:
                trivia.handle_input( 4 )
            elif event.key == pygame.K_RETURN:
                trivia.next_question()

        screen.fill( RGB.Black )
        trivia.show_question()
        pygame.display.update()

游戏模块RGB.py的部分代码如下:

White = ( 255, 255, 255 )
Purple = ( 160, 32, 240 )
Yellow = ( 255, 255, 0 )
Green = ( 0, 255, 0 )
Red = ( 255, 0, 0 )
Black = ( 0, 0, 0 )

以上是本游戏用到的颜色,全部RGB的颜色代码可以查RGB颜色表

运行结果:

《Pygame游戏编程入门》学习——第3章 I/O、数据和字体:Trivia游戏

Original: https://blog.csdn.net/quanet_033/article/details/126909244
Author: 下唐人
Title: 《Pygame游戏编程入门》学习——第3章 I/O、数据和字体:Trivia游戏

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/781110/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 计算机网络-王道考研 002 物理层

    物理层 物理层 物理层基本概念 数据通信基础知识 典型的数据通信模型 数据通信相关术语 三种通信方式 两种数据传输方式 小章总结 -数据通信基础知识 码元、波特、速率、带宽 码元 …

    Python 2023年6月12日
    0104
  • Istio设置请求超时和重试

    当请求后端服务响应过慢的时候,为了不产生积压请求,不拖垮其他服务,主动注入故障,返回超时信息 主动注入故障可以减少等待时消耗的资源,避免请求积压,避免级联错误问题。超时也可以设置在…

    Python 2023年8月11日
    058
  • 【Python开发(基础/后端/安全开发)】专栏文章汇总

    抵扣说明: 1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。 Original: https://blo…

    Python 2023年8月3日
    064
  • 10.模型层与ORM

    模型层是与数据库交互信息的,我们先搞个mysql 附录一 windows上安装mysql_potato123232的博客-CSDN博客 安装之后,我们在环境中中安装 mysqlcl…

    Python 2023年8月6日
    064
  • Numpy || np.array()函数用法指南

    1、Numpy ndarray对象 numpy ndarray对象是一个n维数组对象,ndarray只能存储一系列相同元素。 [1,2,3,4] [[1,2,3,4]] [[1,2…

    Python 2023年8月22日
    0104
  • 学习pandas df[]

    啊哦~你想找的内容离你而去了哦 内容不存在,可能为如下原因导致: ① 内容还在审核中 ② 内容以前存在,但是由于不符合新 的规定而被删除 ③ 内容地址错误 ④ 作者删除了内容。 可…

    Python 2023年8月7日
    056
  • Pygame实战:Python趣味编程之我的兔子终于变了游戏啦

    导语 养过兔子的人应该有同感,看似温柔端庄的兔子实际上是充满活力的小恶魔。它们每天钻来钻去、爬高上低、跳来跳去、咬这个啃那个….每天都在想着新法子调皮捣蛋。 害!虽说小…

    Python 2023年9月22日
    041
  • Pjax 下动态加载插件方案

    在纯静态网站里,有时候会动态更新某个区域往会选择 Pjax(swup、barba.js)去处理,他们都是使用 ajax 和 pushState 通过真正的永久链接,页面标题和后退按…

    Python 2023年10月20日
    039
  • 【深度学习】DNN房价预测

    前言 我们使用深度学习网络实现波士顿房价预测,深度学习的目的就是寻找一个合适的函数输出我们想要的结果。深度学习实际上是机器学习领域中一个研究方向,深度学习的目标是让机器能够像人一样…

    Python 2023年11月1日
    082
  • MySQL安装与基本配置

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Python 2023年6月9日
    065
  • IDEA2022版本创建maven web项目(两种方式)

    回答1: 如果你使用 IntelliJ 项目时没有选择 “ app” 模板,可以手动添加 支持。 1.在 pom.xml 文件中添加以下依赖: </p…

    Python 2023年10月10日
    046
  • Scrapy 基础知识笔记(一)

    (参考书籍Python 网络爬虫框架Scrapy从入门到精通,张颖,北京大学出版社) 一、Scrapy Scrapy用途广泛,可以用于数据采集、数据挖掘、网络异常用户检测、存储数据…

    Python 2023年10月5日
    041
  • Python代码阅读(第40篇):通过两个列表生成字典

    本篇阅读的代码实现了使用两个列表中的元素分别作为key和value生成字典。 本篇阅读的代码片段来自于30-seconds-of-python。 Python 代码阅读合集介绍:为…

    Python 2023年6月15日
    0111
  • pandas处理异常数据(缺失值和重复值)

    1. 缺失值** a) 可以用None或者np.nan来表示缺失的值 import pandas as pd import numpy as np data=[[‘mark’,55…

    Python 2023年8月7日
    046
  • python怎么启动flask_flask如何启动

    Flask 程序实例在创建的时候,需要默认传入当前 Flask 程序所指定的包(模块),接下来就来详细查看一下 Flask 应用程序在创建的时候一些需要我们关注的参数: from …

    Python 2023年8月14日
    067
  • Python小游戏——小鸟管道游戏【附原码】

    前言 又是一篇摸鱼小文章~相信这个游戏应该大多数人都玩过吧 话不多说,现在就来开整,赶紧做完,赶紧摸鱼 不得不说这个小游戏挑战性还蛮大的 开发工具 Python版本:3.6.4 相…

    Python 2023年9月24日
    032
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球