python游戏|pygame-简单答题

本文源代码参考《python游戏编程入门》。
这是一个简单的答题游戏,主要实现功能:答题界面,选择答案,答对时答案标绿,答错时答案标红,同时给正确答案标绿,按下回车键进入下一题。完整代码:

import sys,pygame
from pygame.locals import *

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',encoding='utf-8')
        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 = self.current // 6 + 1
        print_text(font1,5,80,"QUESTION " + str(question))
        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 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

    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 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))

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:
            pygame.quit()
            sys.exit()
        elif event.type == KEYUP:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                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 milloin 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

先导入模块

import sys,pygame
from pygame.locals import *

在主代码中单独定义一个函数,用于绘制文字对象到界面上。参数:font表示font对象,x,y坐标位置,color颜色初始值为白色

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))

把游戏的主要属性都写到一个类Trivia中,有一个参数filename,表示读取的文件,构造函数里给属性初始化:

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]
        #打开文件,设置编码方式为utf-8
        f = open(filename,'r',encoding='utf-8')
        trivia_data = f.readlines()
        f.close()
        #readlines方法是按行读取文件,生成列表
        #由于生成的每一个元素最后会有换行符,所以使用strip函数删除空白
        #添加到新的列表self.data中
        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)
        #获取正确答案,文件中第5行是答案数字字符型,将其转化为数值型
        self.correct = int(self.data[self.current+5])
        #每6行是一个题,对6整除,加1是因为列表从0计数,得到题目
        #将题目绘制上去
        question = self.current // 6 + 1
        print_text(font1,5,80,"QUESTION " + str(question))
        print_text(font2,20,120,self.data[self.current],yellow)
        #判断如果输入答案正确,将答案标绿,改变颜色列表self.color相应位置的值
        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])

判断输入是否正确,一个参数number,输入的答案数字:

    def handle_input(self,number):
        #self.scored和self.failed的初始值都为false,说明这道题没有被答过。
        #接着判断答案为真则self.scored为真,答案为假则self.failed为真
        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.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

窗口主程序:

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:
            pygame.quit()
            sys.exit()
        elif event.type == KEYUP:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                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()

最后实现的效果:


答题正确
答题错误
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容