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

运行结果如下:

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

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

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

为了完成这个任务,最重要的问题就是应该在哪个地方加上提示信息,一开始我的想法是在 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()

运行结果如下:

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

Original: https://blog.csdn.net/weixin_55267022/article/details/122236581
Author: 花无凋零之时
Title: Pygame学习笔记2:文件I/O以及一个简易的问答游戏——Trivia

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

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

(0)

大家都在看

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