学习Python,学习Pygame(三)

        在上一章中,大致了解Pygame,显然,游戏中缺少不了字幕的存在,在游戏中,字幕一般都是从文件中提取出来的,所以在Python中掌握对文件的操作显然也是一件非常重要的事情。

        Python是一种解释性的语言,而不像C++那样编译型的语言,所以以下的几行代码在Python中完全是可行的:

sth = 123
print(sth)
sth = '123'
print(sth)
        尽管输出一样,但是所代表的意义却是不一样的,一个int类型,另外一个则是string类型。

         那么,如何获取用户输入呢?用的是input()函数:(注释代表控制台输出)

name = input("What's your name?")
#What's your name?Python
print("My name is " + name)
#My name is Python
        在Python3.x中,所有的输入貌似都是作为字符串的形式,对于合法的数字而言,我们可以直接使用int()或者float()函数来使得字符串变成数字,当然这就意味着肯定有输入错误的时候,这个时候就需要用到异常处理:
a = input("Please enter a number: ")
try:
    num = float(a)
except:
    print("Error!\n")
       显然,异常处理的方式跟C++很像。

       好,接下来看看如何对文件进行输入输出,关于这些操作,还是跟C++非常的相似,感觉只是不需要声明一个指向文件的指针。

#打开文件并写入文件再关闭
file1 = open("data.txt","w")
file1.write("write the file\n")
file1.write("write the file again\n")
file1.close()

#打开文件并读取文件再关闭
text_line = []
file2 = open("data.txt", "r")
text_line = file2.readlines()
print(text_line)
file2.close()
         当然,读取的方式有很多种,最简单的file.read(x),x代表读取的字符数;file.readline()表示读取文件中的一行;file.readlines()表示读取文件中的所有,并且所返回的是一个列表,每一行代表一个元素。除了这种方式,还有操作二进制文件,个人觉得没有什么太大的区别。

         有了这些知识结合文字的显示,我们就可以写一个纯文字的游戏,虽然不怎么美观。在这个小游戏中,使用了类的知识

import sys
import 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]

        #read trivia from file
        f = open(filename, "r")
        trivia_data = f.readlines()
        #print(trivia_data)
        f.close()

        #count and clean up trivia 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)

        #get correct answer out of data (first)
        self.correct = int(self.data[self.current+5])

        #display question
        question = self.current // 6 + 1 # // is defferent from /
        print_text(font1, 5, 80, "QUESTION" + str(question))
        print_text(font2, 20, 120, self.data[self.current], yellow)

        #respond to correct answer
        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)

        #display answer
        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, 310, "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 += 1

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

#main program begins
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

#load the trivia data file
trivia = Trivia("question.txt")

#repeating loop
while True:
    for event in pygame.event.get():
        if event.type is QUIT:
            sys.exit()
        elif event.type is 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()

        #clean the screen
        screen.fill((0, 0, 200))

        #display trivia data
        trivia.show_question()

        #updata the display
        pygame.display.update()

question.txt

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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值