I/O、数据和字体:Trivia游戏

本章包括如下内容:
Python数据类型
获取用户输入
处理异常
Mad Lib游戏
操作文本文件
操作二进制文件
Trivia游戏

其他的不说,我先去自己学习文件类型和字符串类型去了。这部分讲道理换行符还
是有点丑陋的,Python还需要想着各种地方加换行符,狗屎。

不去想书中示例丑陋的换行符,只要不影响其中几个重要的游戏效果就行。

实验空行会不会对于trivia游戏的结果产生影响

Python文件类型
f=open("filename","r")

读写模式r w a r+ w+ a+

r只读模式
w只写模式,已有文件内容会被清空,文件不存在则会创建新文件
a添加模式,不清空文件,在文件末尾加入内容
其他的说不了,很复杂。

怎么对文件指针位置进行调整

string.strip()函数删除末尾的换行符

madlib游戏简介:
    Mad Lib游戏相当简单。它要求某个人填入一些名称、事情、地点,然后使用这些单词和短语来组成一个
故事,往往会得到出人意料的、幽默的结果。这个小程序的有趣之处在于,故事是如何构建出来的(确实如此)。

这个程序是经过修改的,和书中story部分不同,没有许多令人心烦的换行符。而是直接用三个引号来完成多
行的输入。

论三个引号会怎么影响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
    weeks to get there travelling by SHIP.They
    enjoyed a luxurious candlelight dinner overlooking
    a DRINK ocean while eating FOOD.But,since
    they were both JOB,they had to cut their
    vacation short."""

story=story.replace("GUY",guy)
    story=story.replace("GIRL",girl)
    story=story.replace("FOOD",food)
    story=story.replace("SHIP",ship)
    story=story.replace("JOB",job)
    story=story.replace("PLANET",planet)
    story=story.replace("DRINK",drink)
    story=story.replace("NUMBER",number)
    print(story)

这个程序值得学习的部分:
    对于字符串类型,可以使用str.replace将给定字符替换成相应的变量。
    嗯,小故事也不错。

trivia游戏简介:
    Trivia游戏,从一个文件中读取出一些问题,并且要求用户从多个可选的答案中做出选择。
这个游戏涉及数据类型的设计,对于现在我面向对象的编程水平来说有点困难。需要一步一步将
整个程序分块分析,看看面向对象的编程设计思路。也可以帮助理解为什么面向对象是一种更高
级的编程方式。

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

#定义数据类型
    #Trivia包括__init__,show_question,handle_input,next_question等。一个初始化和三个自带函数。
    #__init__定义了Trivia所应包含的常量。data,current,total,correct,score,scored,failed,
    #wronganswer和colors。其中data是从文件中读取的字符串列表。
    #show_question负责显示当前问题,它会调用到全局的函数print_text
    #handle_input负责判断对错以及对score,scored,failed,wronganswer的进行相应的修改
    #next_question负责重置scored,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()

这段代码感觉就是面向对象语言的入门范例。首先设计好数据结构,主函数相对来说简单明了。这个跨度我感觉有一点大,
还需要一定程度的积累才行。

Python游戏编程入门2的更多相关文章

  1. Python游戏编程入门

    <Python游戏编程入门>这些文章负责整理在这本书中的知识点.注意事项和课后习题的尝试实现.并且对每一个章节给出的最终实例进行分析和注释. 初识pygame:pie游戏pygame游戏库 ...

  2. Python游戏编程入门 中文pdf扫描版|网盘下载内附地址提取码|

    Python是一种解释型.面向对象.动态数据类型的程序设计语言,在游戏开发领域,Python也得到越来越广泛的应用,并由此受到重视. 本书教授用Python开发精彩游戏所需的[]为重要的该你那.本书不 ...

  3. python编程学习--Pygame - Python游戏编程入门(0)---转载

    原文地址:https://www.cnblogs.com/wuzhanpeng/p/4261015.html 引言 博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因 ...

  4. Pygame - Python游戏编程入门(0) 转

    博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因为我感觉Python是一门很有意思的语言,很早以前就想学了(碍于懒),它的功能很强大,你可以用它来做科学运算,或者数 ...

  5. Pygame - Python游戏编程入门

    >>> import pygame>>> print(pygame.ver)1.9.2a0 如果没有报错,应该是安装好了~ 如果报错找不到模块,很可能是安装版本的问 ...

  6. Python游戏编程入门4

    Math和Graphics:Analog Clock示例程序本章介绍Python的math模块,该模块可以执行计算,如常见的三角正弦函数.余弦函数.正切函数等. 使用正弦和余弦函数绘制圆创建Anlog ...

  7. Python游戏编程入门3

    用户输入:Bomb Catcher游戏本章介绍使用键盘和鼠标获得用户输入.包括如下主题:学习pygame事件学习实时循环学习键盘和鼠标事件学习轮询键盘和鼠标的状态编写Bomb Catcher游戏 1本 ...

  8. PC游戏编程(入门篇)(前言写的很不错)

    PC游戏编程(入门篇) 第一章 基石 1. 1 BOSS登场--GAF简介 第二章 2D图形程式初体验 2.l 饮水思源--第一个"游戏"程式 2.2 知其所以然一一2D图形学基础 ...

  9. 分享《Python 游戏编程快速上手(第3版)》高清中文版PDF+高清英文版PDF+源代码

    通过编写一个个小巧.有趣的游戏来学习Python,通过实例来解释编程的原理的方式.14个游戏程序和示例,介绍了Python基础知识.数据类型.函数.流程控制.程序调试.流程图设计.字符串操作.列表和字 ...

随机推荐

  1. js考察this,作用域链和闭包

    在严格版中的默认的this不再是window,而是undefined. 先看两个例子 example one var num = 20; var obj = { num: 30, fn: (funct ...

  2. IIS宿主WCF服务*.svc Mime类型映射

    经常会遇到由于.net安装组件缺失,导致发布wcf服务后,访问wcf报.svc请求类型不支持 简单方法就是添加删除程序,修改.net组件安装选项,勾选http激活即可: 或者手工添加映射处理程序 1. ...

  3. div 拖拽

    html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...

  4. 学号 20175313《Java程序设计》 第七周学习总结

    目录 一.教材学习内容总结 二.教材学习中的问题和解决过程 三.代码托管 四.心得体会 五.学习进度条 六.参考资料 一.教材学习内容总结 第八章主要内容 了解String类 常量对象:常量池中的数据 ...

  5. CJSON在项目中的应用

    无需编译,只需将 cJSON.c.cJSON.h 添加到项目中即可使用

  6. idea (2018.09) 安装破解mybatis plugin

    本来打算安装的是mybatis plugin最新版本(4.0.4) 但是安装下来发现lib目录中少mybatis_plugin.jar包 只有手动安装了这里安装的是2.9.2版本使用了一下不受影响 破 ...

  7. GDI和内核对象区别

    1.GDI对象和核心对象之间最主要的区别在于GDI对象有单一拥有者,不是进程就是线程 2.核心对象可以有一个以上的拥有者,甚至可以跨进程,为了保持对每一位(拥有者)的追踪,核心对象保持了一个引用计数, ...

  8. spring boot 如何添加拦截

    添加拦截其它挺简单的,直接上代码吧,我以简单的登陆验证拦截为例 1,先实现一个拦截器 package com.xinyue.interview.gm.filter; import javax.serv ...

  9. Python3标准库

    文本 1. string:通用字符串操作 2. re:正则表达式操作 3. difflib:差异计算工具 4. textwrap:文本填充 5. unicodedata:Unicode字符数据库 6. ...

  10. Spring Configuration注解使用

    @Configuration是spring.xml的注解版. @ComponentScan是<context:component-scan base-package="com.cosh ...