Python实现问题回答小游戏

 更新时间:2021年12月10日 11:12:00   作者:我的天才女友  
这篇文章主要介绍了利用Python制作一个简单的知识竞赛小游戏,可以实现回答问题功能,文中的示例代码介绍详细,感兴趣的同学快跟随小编一起学习吧

读取问题

如下所示,我们在文本中写了一个问题,然后将其读取出来。

“黄河远上白云间,一片孤城万仞山。”的作者是谁?

王之涣

李白

白居易

杜甫

file = open("1.txt", "r")
question_coll = file.readlines()
file.close()
print(file)

运行之后发现报错,查询之后发现编码格式不正确。

设置了读取的编码格式发现可以读取文本的内容

file = open("1.txt", encoding='utf-8')

绘制回答面板

为了方便读取,新建一个类来储存文件中的问题

# 问题类
class Question:

    # 回答列表
    answer_question = []

    # 正确答案
    answer_index = 1

    """问题类"""
    def __init__(self, question):
        self.question = question

导入问题,将文件中的问题保存在qustion中

from question import Question

因为文件的格式是固定的以6为一个问题的所有行数。

将问题

questionList = []
for i in range(int(len(question_coll) / 6)):
    que_all = question_coll[i * 6: i * 6 + 6]
    que = Question(que_all[0].rstrip())
    que.answer_question = [que_all[1].rstrip(), que_all[2].rstrip(), que_all[3].rstrip(), que_all[4].rstrip()]
    que.answer_index = int(que_all[5].rstrip())
    questionList.append(que)

封装屏幕上显示文字的打印

def draw_text(window_screen, font_size, content, starting_x, starting_y, text_color=WHITE, bg_color=BLACK):
    # 绘制文字
    # 设置字体
    font = pygame.font.SysFont("方正粗黑宋简体", font_size)
    text1 = font.render(content, True, text_color, bg_color)
    window_screen.blit(text1, (starting_x, starting_y))

显示问题

draw_text(screen, 48, "知识竞赛", 180, 20)
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    tips = "当前一共有" + str(len(questionList)) + "个问题,目前是第" + str(index) + "个。"
    draw_text(screen, 18, tips, 20, 140, bg_color=WHITE, text_color=BLACK)
    current_que = questionList[index - 1]
    question_main = "问题" + str(index) + ". " + current_que.question
    draw_text(screen, 16, question_main, 20, 200, bg_color=WHITE, text_color=BLACK)
    for i in range(len(current_que.answer_question)):
        option = str(i + 1) + ". " + current_que.answer_question[i]
        draw_text(screen, 16, option, 40, 260 + i * 40, bg_color=WHITE, text_color=BLACK)

    pygame.display.update()

这样就实现了问题的显示

回答问题

首先我们给出提示,为了方便确认问题是否回答,答案正确与否,我们在问题类中添加变量

    # 是否回答
    answeredFlg = False

    # 回答是否正确
    rightFlg = False

根据这些变量设置文字。

    if current_que.answeredFlg:
        if current_que.rightFlg:
            print("回答正确,是" + current_que.answer_question[current_que.answer_index])
        else:
            print("回答错误,正确答案是" + current_que.answer_question[current_que.answer_index])
    else:
        draw_text(screen, 16, "请按下1、2、3、4来回答答案", 40, 460, bg_color=WHITE, text_color=RED)

如果按下按键,根据答案的正确与否给与响应的提示。

 if current_que.answeredFlg:
        if current_que.rightFlg:
            str1 = "回答正确,是" + current_que.answer_question[current_que.answer_index - 1]
            draw_text(screen, 16, str1, 40, 460, bg_color=WHITE, text_color=GREEN)
        else:
            str1 = "回答错误,正确答案是" + current_que.answer_question[current_que.answer_index - 1]
            draw_text(screen, 16, str1, 40, 460, bg_color=WHITE, text_color=RED)
    else:
        draw_text(screen, 16, "请按下1、2、3、4来回答答案", 40, 460, bg_color=WHITE, text_color=RED)

问题切换

为了方便用户切换问题,在窗口上添加对应的按钮。

import pygame.font


class Button:

    def __init__(self, screen, msg, start_x, start_y):
        # 设置按钮的尺寸和其他属性
        self.screen = screen
        self.width, self.height = 200, 50
        self.button_color = (0, 255, 0)
        self.text_color = (255, 255, 255)
        self.font = pygame.font.SysFont("方正粗黑宋简体", 20)

        # 创建按钮的rect对象,并使其居中
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.rect.left = start_x
        self.rect.right = start_y
        # 按钮的标签只需创建一次
        self._prep_msg(msg)

    def _prep_msg(self, msg):
        """将msg渲染为图像,并让按钮居上"""
        self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)
        self.msg_image_rect = self.msg_image.get_rect()
        self.msg_image_rect.center = self.rect.center

    def draw_button(self):
        # 绘制一个用颜色填充的按钮,在绘制文本
        self.screen.fill(self.button_color, self.rect)
        self.screen.blit(self.msg_image, self.msg_image_rect)

answer_question.py

	btn1 = Button(screen, "next", 300, 500)
    btn1.draw_button()

修改对应的按钮颜色,并添加上一个按钮。

通过是否回答和是否有下一个或者上一个控制按钮的显示

    if current_que.answeredFlg and index < len(questionList):
        btn1 = Button(screen, "下一个", 300, 500)
        btn1.draw_button()
    if index > 1:
        btn2 = Button(screen, "上一个", 50, 500)
        btn2.draw_button()

给按钮添加事件

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if btn1.rect.collidepoint(mouse_pos):
                if current_que.answeredFlg and index < len(questionList):
                    index += 1
            if btn2.rect.collidepoint(mouse_pos) and index > 1:
                index -= 1

完整代码

answer_question.py 主程序

import pygame, sys
from pygame.locals import *
from question import Question
from button import Button

# 读取问题
file = open("1.txt", encoding='utf-8')
question_coll = file.readlines()
file.close()
questionList = []
for i in range(int(len(question_coll) / 6)):
    que_all = question_coll[i * 6: i * 6 + 6]
    que = Question(que_all[0].rstrip())
    que.answer_question = [que_all[1].rstrip(), que_all[2].rstrip(), que_all[3].rstrip(), que_all[4].rstrip()]
    que.answer_index = int(que_all[5].rstrip())
    questionList.append(que)


# 颜色变量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 初始化面板
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("知识竞赛")

# 当前问题
index = 1


def draw_text(window_screen, font_size, content, starting_x, starting_y, text_color=WHITE, bg_color=BLACK):
    # 绘制文字
    # 设置字体
    font = pygame.font.SysFont("方正粗黑宋简体", font_size)
    text1 = font.render(content, True, text_color, bg_color)
    window_screen.blit(text1, (starting_x, starting_y))


# 按钮
btn1 = Button(screen, "下一个", 300, 500)
btn2 = Button(screen, "上一个", 50, 500)
while True:
    answer_index = 0
    # 填充白色
    screen.fill(WHITE)
    draw_text(screen, 48, "知识竞赛", 180, 20)
    tips = "当前一共有" + str(len(questionList)) + "个问题,目前是第" + str(index) + "个。"
    draw_text(screen, 18, tips, 20, 140, bg_color=WHITE, text_color=BLACK)
    current_que = questionList[index - 1]
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_1:
                answer_index = 1
            if event.key == K_2:
                answer_index = 2
            if event.key == K_3:
                answer_index = 3
            if event.key == K_4:
                answer_index = 4
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if btn1.rect.collidepoint(mouse_pos):
                if current_que.answeredFlg and index < len(questionList):
                    index += 1
            if btn2.rect.collidepoint(mouse_pos) and index > 1:
                index -= 1

    question_main = "问题" + str(index) + ". " + current_que.question
    draw_text(screen, 16, question_main, 20, 200, bg_color=WHITE, text_color=BLACK)
    for i in range(len(current_que.answer_question)):
        option = str(i + 1) + ". " + current_que.answer_question[i]
        draw_text(screen, 16, option, 40, 260 + i * 40, bg_color=WHITE, text_color=BLACK)
    if answer_index != 0:
        current_que.answeredFlg = True
        current_que.rightFlg = answer_index == current_que.answer_index
    if current_que.answeredFlg:
        if current_que.rightFlg:
            str1 = "回答正确,是" + current_que.answer_question[current_que.answer_index - 1]
            draw_text(screen, 16, str1, 40, 460, bg_color=WHITE, text_color=GREEN)
        else:
            str1 = "回答错误,正确答案是" + current_que.answer_question[current_que.answer_index - 1]
            draw_text(screen, 16, str1, 40, 460, bg_color=WHITE, text_color=RED)
    else:
        draw_text(screen, 16, "请按下1、2、3、4来回答答案", 40, 460, bg_color=WHITE, text_color=RED)
    if current_que.answeredFlg and index < len(questionList):
        btn1.draw_button()
    if index > 1:
        btn2.draw_button()
    pygame.display.update()

问题类 qustion.py

# 问题类
class Question:
    """问题类"""

    # 回答列表
    answer_question = []

    # 正确答案
    answer_index = 1

    # 是否回答
    answeredFlg = False

    # 回答是否正确
    rightFlg = False

    def __init__(self, question):
        self.question = question


按钮类 button.py

import pygame.font


class Button:

    def __init__(self, screen, msg, start_x, start_y):
        # 设置按钮的尺寸和其他属性
        self.screen = screen
        self.width, self.height = 200, 50
        self.button_color = (255, 192, 128)
        self.text_color = (255, 255, 255)
        self.font = pygame.font.SysFont("方正粗黑宋简体", 20)

        # 创建按钮的rect对象,并使其居中
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.rect.left = start_x
        self.rect.top = start_y
        # 按钮的标签只需创建一次
        self._prep_msg(msg)

    def _prep_msg(self, msg):
        """将msg渲染为图像,并让按钮居上"""
        self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)
        self.msg_image_rect = self.msg_image.get_rect()
        self.msg_image_rect.center = self.rect.center

    def draw_button(self):
        # 绘制一个用颜色填充的按钮,在绘制文本
        self.screen.fill(self.button_color, self.rect)
        self.screen.blit(self.msg_image, self.msg_image_rect)

问题文本文件 1.txt

“黄河远上白云间,一片孤城万仞山。”的作者是谁?

王之涣

李白

白居易

杜甫

1

“落霞与孤鹜齐飞”的下一句是?

携酒对情人

秋水共长天一色

抱琴开野室

林塘花月下

2 

以上就是Python实现问题回答小游戏的详细内容,更多关于Python问题回答游戏的资料请关注脚本之家其它相关文章!

相关文章

  • 分享8点超级有用的Python编程建议(推荐)

    分享8点超级有用的Python编程建议(推荐)

    这篇文章主要介绍了分享8点超级有用的Python编程建议(推荐),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-10-10
  • 人工智能Text Generation文本生成原理示例详解

    人工智能Text Generation文本生成原理示例详解

    这篇文章主要为大家介绍了Text Generation文本生成原理示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-01-01
  • Python 的counter()函数解析与示例详解

    Python 的counter()函数解析与示例详解

    在 Python 中, collections 模块提供了 Counter 类,用于计算可迭代对象中元素的数量, Counter 是一个字典的子类,它以元素作为键,以元素出现的次数作为值进行计数,本文给大家介绍Python 的counter()函数,感兴趣的朋友一起看看吧
    2023-08-08
  • ​Python使用Mediapipe对图像进行手部地标检测

    ​Python使用Mediapipe对图像进行手部地标检测

    本文将以深度库即Mediapipe为基础库,以及其他计算机视觉预处理的CV2库来制作手部地标检测模型,文中的示例代码讲解详细,感兴趣的可以了解一下
    2022-03-03
  • Python中tqdm的使用和例子

    Python中tqdm的使用和例子

    Tqdm是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器tqdm(iterator),下面这篇文章主要给大家介绍了关于Python中tqdm的使用和例子的相关资料,需要的朋友可以参考下
    2022-09-09
  • python中用ctypes模拟点击的实例讲解

    python中用ctypes模拟点击的实例讲解

    在本篇文章里小编给各位整理了一篇关于python中用ctypes模拟点击的实例讲解内容,需要的朋友可以参考学习下。
    2020-11-11
  • Python下载网络文本数据到本地内存的四种实现方法示例

    Python下载网络文本数据到本地内存的四种实现方法示例

    这篇文章主要介绍了Python下载网络文本数据到本地内存的四种实现方法,涉及Python网络传输、文本读写、内存I/O、矩阵运算等相关操作技巧,代码中包含了较为详尽的注释说明便于理解,需要的朋友可以参考下
    2018-02-02
  • 利用python打开摄像头及颜色检测方法

    利用python打开摄像头及颜色检测方法

    今天小编就为大家分享一篇利用python打开摄像头及颜色检测方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • 基于Python制作GIF表情包生成工具

    基于Python制作GIF表情包生成工具

    在当前无表情包不会聊天的时代,怎么也不能输在表情包数量不足上啊,今天咱们就来基于Python制作一个 gif 生成工具,用来制作表情包也太好用啦
    2023-07-07
  • Python里disconnect UDP套接字的方法

    Python里disconnect UDP套接字的方法

    这篇文章主要介绍了Python里disconnect UDP套接字的方法,本文使用的是ctypes绕过的方法,需要的朋友可以参考下
    2015-04-04

最新评论