Introduction to Python Game Programming 2

I/O, Data, and Fonts: Trivia Games This

chapter includes the following:
Python data types Getting
user input
Handling exceptions
Mad Lib games
Manipulating text files
Manipulating binary files went. This part makes sense. Newlines are still a bit ugly. Python still needs to think about adding newlines in various places, shit. Don't think about the ugly line breaks in the examples in the book, as long as it doesn't affect a few important gameplay effects. Will empty lines affect the results of trivia games? Python file type f=open("filename","r") read-write mode rwa r+ w+ a+ r read-only mode w write-only mode, the existing file content will be deleted Empty, if the file does not exist, a new file will be created a add mode, the file will not be emptied, and the content will be added at the end of the file . How to adjust the file pointer position string.strip() function removes the newline at the end madlib game introduction:     Mad Lib game is quite simple. It asks someone to fill in some names, things, places, and then uses those words and phrases to compose a story, often with unexpected, humorous results. What's interesting about this little program is how the story is built (and it is). This program is modified and, unlike the story section of the book, doesn't have many annoying line breaks. Instead, use three quotation marks directly to complete multiple
































行的输入。

论三个引号会怎么影响sublime的Python输出格式(所有的代码一篇黄)。


    #!/usr/bin/python
    print("MAD LIB GAME")
    print("Enter answers to the following prompts")
    print
    guy=raw_input("Name of a famous man:")
    girl=raw_input("Name of a famous woman:")
    food=raw_input("Your favorite food:")
    ship=raw_input("Name of a space ship:")
    job=raw_input("Name of a profession:")
    planet=raw_input("Name of a planet:")
    drink=raw_input("Your favorite drink:")
    number=raw_input("A number from 1 to 10:")

    story="""    
    A famous married couple,GUY and GIRL,went on
    vacation to the planet PLANET.It took NUMBER























    Trivia game, reads some questions from a file and asks the user to choose from multiple possible answers.
This game involves the design of data types, which is a bit difficult for my level of object-oriented programming now. It is necessary to analyze the entire program step by step
and look at the object-oriented programming design ideas. It can also help to understand why object orientation is a more
advanced way of programming.



    #!/usr/bin/python
    import sys, pygame
    from pygame.locals import *
    pygame.init() #Define

    data types
    #Trivia includes __init__, show_question, handle_input, next_question, etc. One initialization and three built-in functions.
    #__init__ defines the constants that Trivia should contain. data, current, total, correct, score, scored, failed,
    #wronganswer and colors. where data is a list of strings read from the file.
    #show_question is responsible for displaying the current problem, it will call the global function print_text
    #handle_input is responsible for judging right and wrong and making corresponding modifications to score, scored, failed, wronganswer
    #next_question is responsible for resetting score, failed, current, correct
    class Trivia( ):
        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 data from file
            f=open("trivia_data.txt","r")
            trivia_data=f.readlines()
            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)
            if (self.current+5)<self.total:
                self.correct=int(self.data[self.current+5])
            else:
                sys.exit()
            #display question
            question=self.current
            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 Quetion",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,230,380,"INCORRECT!",red)
                print_text(font2,170,420,"Press Enter For Next Quetion",red)

            #display answers
            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))

    #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("trivia_data.txt")

    #repeating loop
    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()

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

        #display trivia data
        trivia.show_question()
        
        #update the display
        pygame.display.update()

    This code feels like an introductory example of an object-oriented language. First design the data structure, the main function is relatively simple and clear. I feel that this span is a bit large and
requires a certain degree of accumulation.







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324575190&siteId=291194637