Pygame学习笔记2:文件I/O以及一个简易的问答游戏——Trivia

使用pygame制作一个Trivia小游戏,即问答小游戏

源代码:

import sys
import pygame
from pygame.locals import *


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


class Trivia(object):
    def __init__(self, filename):
        self.data = []
        self.current = 0
        self.total = 0
        self.correct = 0
        self.score = 0
        self.scored = False
        self.failed = False
        self.wronganswer = 0
        self.colors = [white, white, white, white]

        f = open(filename, "r")
        trivia_data = f.readlines()
        f.close()

        for text_line in trivia_data:
            self.data.append(text_line.strip())
            self.total += 1

    def show_question(self):
        print_text(font1, 210, 5, "TRIVIA GAME")
        print_text(font2, 190, 500 - 20, "Press Keys(1-4) TO Answer", purple)
        print_text(font2, 530, 5, "SCORE", purple)
        print_text(font2, 550, 25, str(self.score), purple)

        # 从数据中取出正确答案
        self.correct = int(self.data[self.current + 5])
        question = int(self.current / 6)
        print_text(font1, 5, 80, "QUESTION" + str(question + 1))
        print_text(font2, 20, 120, self.data[self.current], yellow)

        # 回答正确,则字体为绿色
        if self.scored:
            self.colors = [white, white, white, white]
            self.colors[self.correct - 1] = green
            print_text(font1, 230, 380, "CORRECT!", green)
            print_text(font2, 170, 420, "Press Enter For Next Question", green)
        # 回答错误,则字体为红色
        elif self.failed:
            self.colors = [white, white, white, white]
            self.colors[self.wronganswer - 1] = red
            self.colors[self.correct - 1] = green
            print_text(font1, 220, 380, "INCORRECT!", red)
            print_text(font2, 170, 420, "Press Enter For Next Question", red)

        # 显示答案
        print_text(font1, 5, 170, "Answers")
        print_text(font2, 20, 210, "1 - " + self.data[self.current + 1], self.colors[0])
        print_text(font2, 20, 240, "2 - " + self.data[self.current + 2], self.colors[1])
        print_text(font2, 20, 270, "3 - " + self.data[self.current + 3], self.colors[2])
        print_text(font2, 20, 300, "4 - " + self.data[self.current + 4], self.colors[3])

    def next_question(self):
        if self.scored or self.failed:
            self.scored = False
            self.failed = False
            self.correct = 0
            self.colors = [white, white, white, white]
            # 问题格式是一个问题,四个答案,以及一个表示正确答案的编号,共六行
            self.current += 6
            if self.current >= self.total:
                self.current = 0

    def handle_input(self, number):
        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


if __name__ == "__main__":
    # 一些初始化操作
    pygame.init()
    screen = pygame.display.set_mode((600, 500))
    pygame.display.set_caption("The Trivia Game")
    font1 = pygame.font.Font(None, 40)
    font2 = pygame.font.Font(None, 24)
    white = 255, 255, 255
    cyan = 0, 255, 255
    yellow = 255, 255, 0
    purple = 255, 0, 255
    green = 0, 255, 0
    red = 255, 0, 0

    trivia = Trivia("trivia_data.txt")
    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((0, 0, 200))
        # 显示问题
        trivia.show_question()
        pygame.display.update()


文本内容的格式为一个问题,四个选项,以及一个表示正确答案的编号,共六行:

what is the name of the 4th planet from the sun?
Saturn
Mars
Earth
Venus
2
which planet has the most moons in the solar system?
Uranus
Saturn
Neptune
Jupiter
4
approximately how large is the sun's diameter(width)?
65 thousand miles
45 million miles
1 million miles
825 thousand miles
3
how far is the earth from the sun in its orbit(on average)?
13 million miles
93 million miles
250 thousand miles
800 thousand miles
2
what causes the earth's oceans to have tides?
the moon
the sun
earth's molten core
oxygen
1

运行结果如下:
在这里插入图片描述

任务一:当用户答完题目后,提示用户选择重新来还是退出

前面的代码在回答完所有问题后,会自动回到第一个问题,显得不是很友好,因此加上一个提示用户重新来还是退出的选择。

为了完成这个任务,最重要的问题就是应该在哪个地方加上提示信息,一开始我的想法是在next_question()函数中

if self.current >= self.total:
	self.current = 0
    self.score = 0
    self.wronganswer = 0

即在这个if语句中加上提示信息,但是很不幸,到最后一个问题的时候并没有显示出来,于是我仔细观察了一下源代码,发现用于显示的信息都是在show_question()函数中,每个函数完成的任务都是不一样的,于是我尝试着把提示信息加入到show_question()函数中:

# 到达最后一个问题
if self.current >= self.total - 6:
    print_text(font2, 280, 420, "QUIT(q)?", yellow)
else:
    print_text(font2, 170, 420, "Press Enter For Next Question", green)

然后我发现,它成功了,当初到达最后一个问题后,显示了提示信息。

我觉得可能是因为Trivia()类本来就是pygame中提供的,这里只是被我们重写了,但是有关这个类的使用,依然是要根据其对应的函数进行使用,即要想显示数据,就应该将代码写到show_question()函数中,否则就显示不出来。总之,收获颇多。

源代码如下:

import sys
import pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255), shadow=True):
    # 添加阴影效果
    if shadow:
        imgText = font.render(text, True, (0, 0, 0))
        screen.blit(imgText, (x - 2, y - 2))
    imgText = font.render(text, True, color)
    screen.blit(imgText, (x, y))


class Trivia(object):
    def __init__(self, filename):
        self.data = []
        self.current = 0
        self.total = 0
        self.correct = 0
        self.score = 0
        self.scored = False
        self.failed = False
        self.wronganswer = 0
        self.colors = [white, white, white, white]

        f = open(filename, "r")
        trivia_data = f.readlines()
        f.close()

        for text_line in trivia_data:
            self.data.append(text_line.strip())
            self.total += 1

    # 显示文字信息
    def show_question(self):
        print_text(font1, 210, 5, "TRIVIA GAME")
        print_text(font2, 190, 500 - 20, "Press Keys(1-4) TO Answer", purple)
        print_text(font2, 530, 5, "SCORE", purple)
        print_text(font2, 550, 25, str(self.score), purple)

        # 从数据中取出正确答案
        self.correct = int(self.data[self.current + 5])
        question = int(self.current / 6)
        print_text(font1, 5, 80, "QUESTION" + str(question + 1))
        print_text(font2, 20, 120, self.data[self.current], yellow)

        # 回答正确,则字体为绿色
        if self.scored:
            self.colors = [white, white, white, white]
            self.colors[self.correct - 1] = green
            print_text(font1, 230, 380, "CORRECT!", green)
            # 到达最后一个问题
            if self.current >= self.total - 6:
                print_text(font2, 280, 420, "QUIT(q)?", yellow)
            else:
                print_text(font2, 170, 420, "Press Enter For Next Question", green)
        # 回答错误,则字体为红色
        elif self.failed:
            self.colors = [white, white, white, white]
            self.colors[self.wronganswer - 1] = red
            self.colors[self.correct - 1] = green
            print_text(font1, 220, 380, "INCORRECT!", red)
            if self.current >= self.total - 6:
                print_text(font2, 280, 420, "QUIT(q)?", yellow)
            else:
                print_text(font2, 170, 420, "Press Enter For Next Question", red)

        # 显示答案
        print_text(font1, 5, 170, "Answers")
        print_text(font2, 20, 210, "1 - " + self.data[self.current + 1], self.colors[0])
        print_text(font2, 20, 240, "2 - " + self.data[self.current + 2], self.colors[1])
        print_text(font2, 20, 270, "3 - " + self.data[self.current + 3], self.colors[2])
        print_text(font2, 20, 300, "4 - " + self.data[self.current + 4], self.colors[3])

    def next_question(self):
        if self.scored or self.failed:
            self.scored = False
            self.failed = False
            self.correct = 0
            self.colors = [white, white, white, white]
            # 问题格式是一个问题,四个答案,以及一个表示正确答案的编号,共六行
            self.current += 6
            if self.current >= self.total:
                self.current = 0
                self.score = 0
                self.wronganswer = 0

    def handle_input(self, number):
        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


if __name__ == "__main__":
    # 一些初始化操作
    pygame.init()
    screen = pygame.display.set_mode((600, 500))
    pygame.display.set_caption("The Trivia Game")
    font1 = pygame.font.Font(None, 40)
    font2 = pygame.font.Font(None, 24)
    white = 255, 255, 255
    cyan = 0, 255, 255
    yellow = 255, 255, 0
    purple = 255, 0, 255
    green = 0, 255, 0
    red = 255, 0, 0

    trivia = Trivia("trivia_data.txt")
    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()
                elif event.key == pygame.K_q:
                    sys.exit()

        # 清除屏幕
        screen.fill((0, 0, 200))
        # 显示问题
        trivia.show_question()
        pygame.display.update()


运行结果如下:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值