pygame中有这些类和函数:
#1
screen = pygame.display.set_mode()
#上面这个函数会返回一个Surface 对象,他是位图的一种.
#2
space = pygame.image.load("xx.png")
#3, Surface对象有一个名为blit()的方法,它可以绘制位图
screen.blit(space, (0,0))
""" 第一个参数是加载完成的位图,第二个参数是绘制的起始坐标"""
其实,没有代码的话直说函数有点空洞,现在我就将最重要的(至少我认为是)的重点列出来,以方便自己复习。
keys = pygame.key.get_pressed()
这个函数就是在打开的界面中监听你的动作,顺便说一句,在python中,函数的返回值最好设为列表,这样就和绝大多数的库函数保持一致了。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pygame
from pygame.locals import *
from sys import exit
import sys, random, time
""" 这个函数是简单的打印文字的,需要总结一下"""
def print_text(font, x, y, text, color = (255,255,255)):
imgText = font.render(text, True, color)
screen.blit(imgText, (x,y))
# 主程序
# 这样的程序最好分开写比较好
pygame.init()
screen = pygame.display.set_mode((600,500))
pygame.display.set_caption("Leyboard Demo")
font1 = pygame.font.Font(None, 24)
font2 = pygame.font.Font(None, 200)
white = 255,255,255
yellow = 255,255,0
color = 125,100,210
key_flag = False
correct_answer = 97
seconds = 10
score = 0
clock_start = 0
game_over = True
# 这是重点
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
elif event.type == KEYDOWN:
key_flag = True
elif event.type == KEYUP:
key_flag == False
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
exit()
if keys[K_RETURN]:
if game_over:
game_over = False
score = 0
seconds = 11
clock_start = time.clock()
current = time.clock() - clock_start
speed = score * 6
if seconds - current < 0:
game_over = True
elif current:
if keys[correct_answer]:
correct_answer = random.randint(97, 122)
score += 1
#清屏
screen.fill(color)
print_text(font1, 0, 20, "Try to keep up for 10 seconds...")
if key_flag:
print_text(font1, 450, 0, "You are keying...")
if not game_over:
print_text(font1, 0, 80, "Time:" + str(int(seconds - current)))
print_text(font1, 0, 100, "speed: " + str(speed) + "letters/min")
if game_over:
print_text(font1, 0, 160, "Press Enter to start ...")
print_text(font2, 0, 240, chr(correct_answer - 32), yellow)
#update
pygame.display.update()
System call is a call to a subroutine built in to the system, while Interrupt is an event, which causes the processor to temporarily hold the current execution. However one major difference is that system calls are synchronous, whereas interrupts are not. That means system calls occur at a fixed time (usually determined by the programmer), but interrupts can occur at any time due an unexpected event such as a key press on the keyboard by the user. Therefore, when ever a system call occurs the processor only has to remember where to return to, but in the event of an interrupt, the processor has to remember both the place to return to and the state of the system. Unlike a system call, an interrupt usually does not have anything to do with the current program.
使用with
的打开方式更加符合python的变成习惯,希望你能喜欢这种编程风格。
下面使用一个文件pi.txt 来测试一下这个问题。
pi.txt:
3.1415926535 8979323846 2643383279
#!/usr/bin/python
# -*- coding: UTF-8 -*-
""" 这是python打开文件的方法"""
""" 这里的文件名可以使用相对路径或者相对路径, windows使用(\)"""
""" 当然,file_path 可以事先定义"""
with open('inherit.py') as file_object:
for line in file_object:
print(line)
with open('inherit.py') as file_object:
contents = file_object.read()
print(contents)
"""除去空格"""
print(contents.rstrip())
""" 创建一个文件包含各行内容的列表"""
#注意,使用with的方式,open()方法返回的对象只能在with代码块内使用,
#如果想在其他地方使用代码,可以使用readlines()方法。
file_name = 'pi.txt'
with open(file_name) as object:
lines = object.readlines()
for line in lines:
print(line.rstrip())
为了更加美好的展现这个函数的特征,我们新建立一个代码段:
file_name = 'pi.txt'
with open(file_name) as object:
lines = object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
他的输出是这样的:
3.1415926535 8979323846 2643383279
36
我们看到这样的输出,也许并不完美,也许并不满足你的要求,现在,我们这样:
file_name = 'pi.txt'
with open(file_name) as object:
lines = object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
这样就会将好几行数字浓缩在一行之中。注意,python会将所有读取的内容视为文本内容,如果你的内容是数字,而且你还打算使用这个数字,就应该使用int()或者float()函数转化过来。
从文件读取,我们知道使用open(), 那么写入呢?对了,是write,但是,这个write只是一个文件的方法。
filename = 'name.txt'
with open(filename, 'w') as object:
object.write("hello, world")
这个东西与c语言的open(),read(),close()…多么的相近。这里的open()后面的参数 可以有’w’, ‘r’,’a’,’r+’,最后一种是即可读取也可写入。如果不是人为的指定参数, 那么就是只读模式打开文件.
同时,注意,python只能写入文本,所以像数字的内容写入文件的时候,必须使用str() 函数转化,这样才可以
当然在写入的同时可以使用制表符”\n”,”\t”等等。
root@yubo-2:~/test/python# cat test.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
fo = open("yubo.txt", "wb")
print "文件名", fo.name
print "是否已经关闭:", fo.closed
print "访问模式:", fo.mode
print "末尾是否强制加空格:", fo.softspace
file.closed 返回true如果文件已被关闭,否则返回false。
file.mode 返回被打开文件的访问模式。
file.name 返回文件的名称。
file.softspace 如果用print输出后,必须跟一个空格符,则返回false。否则返回true。
记得在打开一个文件后需要 file-objection.close();
write()方法不会在字符串的后面添加’\n’.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
fo = open("yubo.txt", "wb")
print "文件名", fo.name
print "是否已经关闭:", fo.closed
print "访问模式:", fo.mode
print "末尾是否强制加空格:", fo.softspace
fo.write("www.aftermath.cn\nVery good\n");
fo.close();
read()方法读取一个参数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
fo = open("yubo.txt", "r+")
str = fo.read(10);
print "读取的字符串是:", str
fo.close();
这里的read参数是读取的字节数。
seek()文件定位
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
fo = open("yubo.txt", "r+")
str = fo.read(10);
print "读取的字符串是:", str
# 查看当前位置
position = fo.tell();
print "当前文件位置:", position
# 把指针再次重新定位到文件开头
position = fo.seek(0,0);
str = fo.read(10);
print "重新读取字符串:", str
# 关闭打开的文件
fo.close();
需要导入os模块。
os.rename(“file-name1”,”file-name2”);
将文件1重命名为文件2。
os.remove(“file-name”);
这块文件类似于shell命令
chdir(): 改变目录。
getcwd(): 当前目录
rmdir(): 删除目录
这几个函数都有参数,必须注意。
import glob
import os
parent_dir = '/home/vimer/src/aosp_art/ziliao'
for pdf_file in glob.glob(os.path.join(parent_dir, "*.pdf")):
print (pdf_file)
glob
模块可以用来与os模块相结合,从而打印相关目录下的所有文件。
这是一个CMS系统,建立在Zope基础之上, 内容存储在Zope Object Database(ZODB)数据库上.不推荐。
强烈推荐 注意使用Mercurial
请先看下面的例子代码:
class Dog():
def __init__(self, name, age):
""" 初始化属性 name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting")
def roll_over(self):
print(self.name.title() + " is now rolling")
my_dog = Dog('yubo', 6)
print(" My dog,s name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + ".")
my_dog.sit()
my_dog.roll_over()
小提示,在python2.x中,定义类时需要在括号里面填上object
, 就像这样
def Dog(object)
根据约定,在python中,首字母大写就是指的类,上面的这个类的括号里面是空的,这说明我们要从空白处新建立类。
类中的函数称为方法,到目前为止,关于函数的使用方法都适用于类中,唯一的区别在于方法的调用。__init__
是python中较为特殊的方法,每当你根据类创建实例时,python都会自动运行它,之所以有下划线就是为了让用户避免与其他的方法相混淆。
方法__init__
中有三个实参,self name和age,self必须位于第一位且不可缺少,python在调用__init__
创建实例时,将自动传入实参self。每个与类相关联的方法都会传递实参self,它是一个指向实例本身的引用,这类似于c++的this指针。这里,你只需要把参数传递给你自己定义的参数。
def sit(self):
这个语句就是对应着上面的解释,看,这里你只需要传递一个self,其他的参数就可以调用了。另外,以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量。像这样可以通过实例访问的变量称为属性。
class Car():
def __init__(self, make, model, year):
""" 初始化汽车属性"""
self.make = make
self.model = model
self.year = year
''' 设置默认值, 可以不在形参中体现, 里程表的读数'''
self.odometer_read = 0
def get_describe_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_meter(self):
print("This car has " + str(self.odometer_read) + "meters read ")
my_new_car = Car('Audio', 'A4', '2016')
print(my_new_car.get_describe_name())
my_new_car.read_meter()
这里有三种方法: 直接通过实例进行修改、通过方法设置和通过方法进行递增。
class Car():
--snip--
my_new_car = Car('Audio', 'A4', '2016')
print(my_new_car.get_describe_name())
my_new_car.odometer_read = 112
my_new_car.read_meter()
2.通过方法修改属性的值
class Car():
--snip--
def update_odometer(self, mileage):
self.odometer_read = mileage
my_new_car = Car('Audio', 'A4', '2016')
print(my_new_car.get_describe_name())
my_new_car.update_odometer(113)
my_new_car.read_meter()
这种方案还是比较符合现代主流软件设计思潮的
集成就是利用父类已经让子类可以继续使用定义好的属性
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 自动继承父类的所有属性
# python 2 中需要填写object,而且继承的子类必须声明自己的实例加上self
# pyhton 3 中不需要这些
class Battery():
"""将多个类分开,让子类多继承"""
def __init__(self, battery_size = 70):
""" 初始化电平属性"""
self.battery_size = battery_size
def describe_battery(self):
""" 打印一条电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kwh battery.")
def get_range(self):
""" 打印一条消息,指出电瓶的续航里程"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = " This car can go approximately " + str(range)
message += " miles on a full charge "
print(message)
class Car(object):
""" 一次模拟汽车的简单尝试 """
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
""" 默认值 里程表"""
self.odometer_reading = 0
def get_describe(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
def read_odometer(self):
print(" This car has " + str(self.odometer_reading) + " miles on it")
""" 禁止任何人将里程表往回拨"""
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
""" 电动汽车的特点"""
def __init__(self, make, model, year):
""" 初始化父类的属性"""
super(ElectricCar, self).__init__(make, model, year)
""" 以这样的方法继承Battery()"""
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_describe())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
相信函数大家都比较熟悉了,这里就是简单的记录一点。
def greet_user(username):
""" 显示简单语句"""
print("hello, " + username.title() + ".")
greet_user('yubo')
上面就是简单的一个函数原型和调用的方法。首先,python定义函数需要关键词def
表明这是一个函数定义。后面紧接着是函数名称,括号里面是形参,你可以简单的理解为参数。参数就是你需要处理的数据,它可有可无,这个不是必须的。按照python的语法结构,这个语法块就是一个整体,不可分割。一般的函数还有返回值,这个函数显性没有返回值,但是它会向调用者打印一串字符串
# 默认值, 比如,上面的用法就是可以这样的:
def greet_user(username = 'yubo'):
...
# 实参变成可选的,下面这个函数有三个参数,这样的话,你的形参不可缺少
def get_formatted(first_name, middle_name, last_name):
""" 返回全名"""
full_name = first_name + ' ' + middle_name + ' ' + last_name;
return full_name.title()
name = get_formatted('bo', 'zi', 'bo')
print(name)
### 将参数用空值符表示出来,同时判断条件
def get_formatted(first_name, last_name, middle_name = ''):
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
name_1 = get_formatted('Bo', 'yu')
name_2 = get_formatted('bo', 'yu', 'zi')
print(name_1)
print(name_2)
# 看下面的这个函数,有意思
def get_formatted(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\n Please input your name\n")
print("enter 'q' to quit the exam:\n")
f_name = raw_input("First name:")
if f_name == 'q':
break
l_name = raw_input("Last name:")
if l_name == 'q':
break
formatted = get_formatted(f_name, l_name)
print(formatted)
# 传递列表
def greet_user(names):
for name in names:
print("Hello, " + name.title() + "!")
name_list = ['yubo', 'hechun','xiaoxiao']
greet_user(name_list)
# 在函数中修改列表
def print_list(unprinted_designs, complete_models):
""" 模拟打印每个设计,直到没有未打印的设计为止"""
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印
print("Printing model: " + current_design)
complete_models.append(current_design)
def show_list(complete_models):
""" 显示打印好的模型"""
print("\n The following models have been printed")
for complete_model in complete_models:
print(complete_model)
unprinted_designs = ['iphone', 'robot', 'winphone']
complete_models = []
print_list(unprinted_designs, complete_models)
show_list(complete_models)
# 禁止函数修改列表,则要将列表的副本传递给函数,比如,上面的例子:
print_list(unprinted_designs[:], complete_models)
# 不过,你除非有充足的理由这样做,否则这样会花时间和内存创建副本,
#这样会影响效率
# 向函数传递任意多的参数, 需要在形参名字前面加上星号(*)
def make_pizza(*topping):
print(topping)
""" 当然,实参位置还是需要注意的"""
make_pizza('yubo')
make_pizza('hechun', 'xiaoxiao')
# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建一个字典, 其中包含我们知道的一切"""
profile = {}
profile['first_mane'] = first;
profile['last_name'] = last;
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('bo', 'yu',
location = 'Qingdao', phone = '123')
print(user_profile)