首页 > 编程语言 >python module

python module

时间:2023-01-08 15:56:16浏览次数:59  
标签:sheet python module sys pygame import path os

1.easygui

  • easygui是Python的一个图形化界面的库。

  • 下载模块

    pip install easygui

常用功能

  1. 消息弹窗

    msgbox()   #消息弹窗
    msgbox(msg=' ', title=' ', ok_button=' ', image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    ok_button:#按钮上显示的信息
    image:#显示图片(需要路径)
    #返回值:
     #按钮信息
     #右上角×号返回None
    #########################
    import easygui as t
    t.msgbox('Hello','easy','Yes','wjx.png')
  2. 双项选择

    ccbox()     #双项选择
    ccbox(msg=' ', title=' ', choices=('  ', '  '), image=None)
    msg:#需要显示的内容
    title:#窗口的标题
    choices:#元组形式,两个选项显示的内容
    image:#显示图片(需要路径)
    ​
    #返回值:
     #第一个按钮返回True
     #第二个按钮返回False
     #右上角×号返回None
    ​
    import easygui as t
    t.ccbox('下面水果,你喜欢哪一个?','选择',('苹果','橘子'))
    ​
  3. 多项选择

    buttonbox()   #多项选择
    buttonbox(msg=' ', title=' ', choices=('Button1', 'Button2', 'Button3'), image=None, root=None)
    ​
    msg:#需要显示的内容
    title:#窗口的标题
    choices:#元组形式或列表的形式,多个选项显示的内容
    image:#显示图片(需要路径)
    ​
    #返回值:
     #点击按钮返回按钮的信息
     #右上角×号返回None
    ​
    import easygui as t
    tuple = ('石头','剪刀','布')
    t.buttonbox('选择石头剪刀布','game',tuple)
  4. 可选的下拉列表

    choicebox()与multchoicebox()——#可选的下拉列表
    choicebox(msg=' ', title=' ', choices=())
    msg:#需要显示的内容
    title:#窗口的标题
    choices:#元组形式或列表的形式,多个选项显示的内容
    ​
    #返回值:
     #点击显示的选项,返回选项的信息
    # 点击Cancel按钮返回None
    # 右上角×号返回None
    ​
    import easygui as t
    list = ['石头','剪刀','布']
    t.choicebox('选择石头剪刀布','game',list)
    ​
    multchoicebox()#功能同样,只是他可以提供多选,拥有全选与全清按钮。
    ​
    #返回值:
    # 多选的返回值是多选的文本列表
    # 点击Cancel按钮返回None
    # 右上角×号返回None
  5. 文本输入框

    enterbox()    #文本输入框
    enterbox(msg='  ', title=' ', default=' ', strip=True, image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    default:#关键字定义的是文本框默认值
    strip:#的值为True时会自动忽略输入的首尾空格,False则相反
    image:#显示图片(需要路径)
    ​
    #返回值:
    ## 输入内容后返回值为输入的字符串
    #点击Cancel按钮返回None
     #右上角×号返回None
       
    import easygui as t
    s = t.enterbox('What do you want to say ?','想说什么','Who are you ?')
    print(s)
  6. 数字输入

    integerbox() #  数字输入
    integerbox(msg='', title=' ', default='', lowerbound=0, upperbound=99, image=None, root=None,)
    msg:#需要显示的内容
    title:#窗口的标题
    default:#关键字定义的是文本框默认值
    lowerbound:#输入的最小值
    upperbound:#输入的最大值
    image:#显示图片(需要路径)
    ​
    #返回值:
    # 输入内容后返回值为输入的数字
    # 点击Cancel按钮返回None
    # 右上角×号返回None
    #输入数值超出范围时会给出提示后从新输入。
    ​
    import easygui as t
    s = t.integerbox('你多大了','年龄','18',0,120)
    print(s)
  7. 多选项输入

    mulenterbox()  #多选项输入
    multenterbox(msg=' ', title=' ', fields=(), values=())
    msg:#需要显示的内容
    title:#窗口的标题
    fields:#填写条目名称
    values:#默认内容
    ​
    #返回值:
    ### 输入内容后返回值为输入的内容,以列表的形式
    # 点击Cancel按钮返回None
    ## 右上角×号返回None
    ​
    import easygui as t
    message = ['学号', '姓名','性别','年龄','院系','入学时间']
    s = student = t.multenterbox('输入学生的信息:', '信息录入', message)
    print(s)
  8. 密码输入框

    passwordbox()#密码输入框(不显示)
    passwordbox(msg=' ', title=' ', default=' ', image=None, root=None)
    msg:#需要显示的内容
    title:#窗口的标题
    default:#关键字定义的是文本框默认值
    image:#显示图片(需要路径)
    ​
    #返回值:
    # 输入内容后返回值为输入的字符串
    ## 点击Cancel按钮返回None
    # 右上角×号返回None
    ​
    import easygui as t
    s = t.passwordbox('输入密码', '密码')
    print(s)
  9. 多项显示

    multpasswordbox() #多项显示
    multpasswordbok(msg=' ', title=' ',fields=(),values=())
    msg:#需要显示的内容
    title:#窗口的标题
    fields:#填写条目名称,最后一栏显示为*号
    values:#默认内容
    ​
    #返回值:
    # 输入内容后返回值为输入的内容,以列表的形式
    # 点击Cancel按钮返回None
    # 右上角×号返回None
    ​
    import easygui as t
    s = t.multpasswordbox('请输入账号密码', '登录',['用户名','账号','密码'],['123','123','123'])
    print(s)

2.openpyxl

  • 安装模块

    pip install openpyxl

常用功能

1.sheet

from openpyxl import load_workbook
​
#打开excel文件
workbook = load_workbook("文件名")
​
#1.获取所有的sheet名称
name_list = workbook.sheetnames
print(name_list)
​
#2.根据名称获取sheet
sheet_object = workbook["sheetname"]
print(sheet_object)
​
#3.根据索引获取sheet
sheet = worksheets[0]
​
#4.循环获取所有的sheet
for sheet_object in wcrkbook:
    print(sheet_object)
#不加.sheetnames内部也是自动获取sheetnames的

2.sheet中单元格的数据

from openpyxl import load_workbook
​
workbook = load_workbook("文件路径")
sheet = workbook.worksheets[1]
​
#1.获取 第n行 &第n列 的单元格(起始位置是1)
cell = sheet.cell(1,1)
print(cell)
print("内容",cell.value)
print("样式",cell.style)
print("字体",cell.font)
print("排序",cell.alignment)
​
#2.根据Excel的位置获取数据
cell_al = sheet["A1"]
print(cell_al.value)
​
#3.获取第n行的单元格
cell_list = sheet[1]
​
for cell in sheet[1]:
    print(cell.value)
    
#4.循环获取所有行数据
for row in sheet.rows:
    print(row[0].value)
    
#5.循环获取所有列
for col in sheet.columns:
    print(col[0].value)
​

3.合并的单元格

from openpyxl import load_workbook
​
workbook = load_workbook("文件路径")
sheet = workbooks[2]
​
#1.获取单元格
c1 = sheet.cell(1,1)
print(c1) #<cell "Sheet1".A1>
print(c1.value) #用户信息
#第一个和第二个合并单元格,第一个显示值,第二个显示null
c1 = sheet.cell(1,2)
print(c1) #<MergedCell "Sheet1".B1>
print(c1.value) #None
​

4.Excel

4.1原Excel文件基础上写内容

from openpyxl import load_workbook
​
workbook = load_workbook("文件路径")
sheet = worksheets[0]
​
#1.找到单元格,并修改单元格的内容
cell = sheet.cell(1,1)
cell.value = "值"
​
#将excel文件保存到p2.xlsx文件中
workbook.save("文件路径")

4.2新创建Excel文件写内容

from openpyxl import workbook
​
#创建excel且默认会创建一个sheet(名称为sheet)
workbook = workbook.Workbook()
​
sheet = worksheets[0]
​
#找到单元格,并修改单元格的内容
cell = sheet.cell(1,1)
cell.value = "值"
​
#将excel文件保存到p2.xlsx文件中
workbook.save("文件路径")

4.3删除和修改

from openpyxl import workbook
​
workbook = workbook.workbook()
​
#1.修改sheet名称
sheet = worksheets[0]
sheet.title = "值"
workbook.save("p2.xlsx")
​
#2.创建sheet并设置sheet颜色
sheet = workbook.create_sheet("工作计划",0)#零代表位置
sheet.sheet_properties.tabColor = "1072BA"
workbook.save("P2.xlsx")
​
#3.默认打开的sheet
workbook.active = 0
workbook.save("p2.xlsx")
​
#4.拷贝sheet
sheet = workbook.create_sheet("工作计划")
sheet.sheet_properties.tabColor = "1072BA"
​
new_sheet = workbook.copy_worksheet(workbook["Sheet"])
new_sheet.title = "新的计划"
workbook.save("p2.xlsx")
​
#5.删除sheet
del workbook["用户列表"]
workbook.save("files/p2.xlsx")

5.操作单元格

from openpyxl import load_workbook
from openpyxl.styles import Alignment,Border,Side,Font,PatternFill,GradientFill
​
workbook = load_workbook("文件")
sheet = workbook.worksheet[1]
#1.获取某个单元格,修改值
cell = sheet.cell(1,1)
cell.value = "开始"
​
#2.获取某个单元格,修改值
sheet["V3"] = "Alex"
vb.save("p2.xlsx")
​
#3.获取某些单元格,修改值
cell_list = sheet[B2:C3]
#b2到c3拿到的值是(b2,b3,c2,c3)
for row in cell_list:
    for cell in row :
        cell.value = "新的值"
vb.save("p2.xlsx")
​
#4.对齐方式
cell = sheet.cell(1,1)
#herizontal,水平方向对齐方式:“general”,"left","center"句中,"right","fill","justify","centercontinuous","distributed"
#vertieal,垂直方向对齐方式:"top","center","bottom","justify","distributed"
#text_rotation,旋转角度
#wrap_text,是否自动换行
cell.alignment = Alignment(horizontal="center",vertical="distributed",text_rotation=45,wrap_text=True)
wb.save("p2.xlsx")
​
#5.边框
#side的style有如下:dashDot,dashDotDot,dashed,dotted,double,hair,mediun,mediumDashDot,mediumDashDotdot,mediumDashed,slantDashDot,thick,thin.
sell = sheet.cell(9.2)
cell.border = Border(
    top = Side(style="thin",color="FFB6C1"),   
    bottom=Side(style="dashed",color="9932cc"),
    left=Side(style="dashed",color="9932cc"),
    right=Side(style="dashed",color="9932cc"),
    diagonal=Side(style="thin",color="483D8B"),#对角线
    diagonalUp=True,#左下-右上
    #diagonalDown=True #左上-右下
)
wb.save("p2.xlsx")
​
#6.字体
cell = sheet.cell(5,1)
cell.font = Font(name="微软雅黑",size=45,color="ff0000",underline="single") #underline下划线
wb.save("p2.xlsx")
​
#7.背景色
cell = sheet.cell(5,3)
cell.fill = PatternFill("solid",fgColor="99ccff")
wb.save("p2.xlsx")
​
#8.渐变背景色
cell = sheet.cell(5,5)
cell.fill = GradientFill("linear",stop=("FFFFFF","99ccff","000000"))#从左到右的三个颜色
wb.save("p2.xlsx")
​
#9.宽高(索引从1开始)
sheet.row_idmensions[1].height = 50
sheet.column_dimensions["E"].width = 100
wb.save("p2.xlsx")
​
#10.合并单元格
sheet.merge_cells("B2:D8")
#这是两种
sheet.merge_cells(start_row=15,start_column=3,end_row=18,end_column=8)
wb.save("p2.xlsx")
#这是解除合并单元格的
sheet.unmerge_cells("B2:D8")
wb.save("p2.xlsx")
​
#11.写入公式
sheet = wb.worksheets[3]
sheet["D1"] = "合计"
sheet["D2"] = "=B2*C2"
wb.save("p2.xlsx")
​
sheet = wb.worksheets[3]
sheet["D3"] = "=sum(B3,C3)"
wb.save("p2.xlsx")
​
#12.删除
#idx,要删除的索引位置
#anount,从索引位置开始要删除的个数(默认为1)
sheet.delete_rows(idx=1,anount=2)
sheet.delete_cols(idx=1,anount=3)
wb.save("p2.xlsx")
​
#13.插入
sheet.insert_rows(idx=5,anount=10)
sheet.insert_cols(idx=3,anount=2)
wb.save("p2.xlsx")
​
#14.循环写内容
​
sheet = wb["Sheet"]
cell_range = sheet["A1:C2"]
for row in cell_range:
    for cell in row:
        cell.value = "xx"
#第5行第1列到第7行第10列
for row in sheet.iter_rows(min_row=5,min_col=1,max_col=7,max_row=10):
    for cell in row:
        cell.value = "oo"
wb.save("p2.xlsx")
​
#15.移动
#将H2:J10范围的数据,向右移动15个位置、向上移动1个位置
sheet.nove_range("H2:J10",rows=-1,cols=15)
wb.save("p2.xlsx")
​
#16.打印区域
sheet.print_area = "A1:D200"
wb.save("p2.xlsx")
​
#17.打印时,每个页面的固定表头
sheet.print_title_cols = "A:D"
sheet.print_title_rows = "1:3"
wb.save("p2.xlsx")

6.作业

  1. 补充代码:实现去网上获取指定地区的天气信息,并写入excel中。

    import requests
    ​
    while True:
        city = input("请输入城市(Q/q退出):")
        if city.upper()=="Q":
            break
        url = "http://ws.webxml.com.cn//webServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName={}".format(city)
        res = requests.get(url=url)
        print(res.text)
        
        #1.提取xml格式中的数据
        #2.为每个城市创建一个sheet,并将获取的xml格式中的数据写入到excel中。
        from openpyxl import load_workbook
    ​
            workbook = load_workbook("a1.xlsx")
            sheet = workbook.create_sheet("工作计划")
            sheet.title = city
            sheet = workbook[city]
            cell=sheet["A1:AH1"]
            text=str(res.text)[:-16].split("<string>")[1:]
            for i in range(len(text)):
                cell[0][i].value = text[i][:-13]
                print(text[i][:-13])
            workbook.save("a1.xlsx")
  2. 读取ini文件内容,按照规则写入到Excel中

    [mysqld]
    datadir=/var/lib/mysql
    socket=py-mysql-bin
    log-bin=py-mysql-bin
    character-set-server=utf8
    collation-server=utf8_general-ci
    log-error=/var/log/mysqld.log
    symbolic-links=0
    ​
    [mysqld_safe]
    log-error=/var/log/mariadb/mariadb/mariadb.log
    pid-file=/var/run/mariadb/mariadb.pid
    ​
    [client]
    default-character-set=utf8
    #1.读取ini格式的文件,并创建一个excel文件,并且每个节点创建一个sheet,然后将节点下的键值写入到excel中。
    #2.首行,字体白色&单元格背景色蓝色
    #3.内容均句中
    #4.边框

3.Matplotlib and Plotly

  • 安装 Matplotlib and Plotly

    pip install matplotlib
    pip install Plotly

1.Matplotlib

  1. 简单使用

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    ​
    x_values = range(1, 1001, 19)
    y_values = [x**2 for x in x_values]                     # 自动计算数据
    ​
    # 写上这两行后可以解决,字体无法显示的问题。
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    ​
    # print(plt.style.available)                                # 查看样式
    plt.style.use("Solarize_Light2")                        # 网格样式
    fig, ax = plt.subplots()
    ​
    # 隐藏xy轴,写这个可以隐藏坐标轴
    # ax.get_xaxis().set_visible(False)
    # ax.get_yaxis().set_visible(False)
    ​
    ax.scatter(x_values, y_values, c="red", s=1)            # 调用scatter()并使用参数s设置绘制图形时使用的点的尺寸,c是颜色。
    # ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=100)
    # c是颜色,写数据是透明色的透明度,cmap=plt.cm.Blues是告诉pyplot使用什么渐变颜色
    ​
    ax.set_title("平方数", fontsize=24)                      # 表标题,字号24
    ax.set_xlabel("值", fontsize=14)                     # x轴标题,字号14
    ax.set_ylabel("值的平方", fontsize=14)                  # y轴标题,字号14
    ​
    ax.tick_params(axis="both", which="major", labelsize=14)  # 设置刻度标记的大小。
    ax.axis([0, 1100, 0, 1100000])                              # 设置每个坐标轴的取值范围
    ​
    # plt.savefig("squares_plot.png", bbox_inches="tight")  # 这个方法是用来保存图片的,第一个参数是图片的名称,第二个是去掉多余的白边,
    plt.show()
  2. 将数据以逗号翻个的称为CSV文件,对人阅读比较麻烦,但是程序可以轻松提取并处理。

    import csv
    from datetime import datetime
    import matplotlib.pyplot as plt
    ​
    with open("aa.csv") as f:
        reader = csv.reader(f)              #将存储的对象最为实参
        header_row = next(reader)           #传入阅读器对象时,它将返回文件中的下一行
        # for index,column_header in enumerate(header_row): # enumerate用于获取索引及其值
        #     print(index,column_header)
        dates, highs, lows = [], [], []
        for row in reader:          #循环获取
            current_date = datetime.strptime(row[2], "%Y-%m-%d")        #索引获取时间并转为时间类型
            # 时间参数还有很多
            # %A    星期几,%B    英文月份名,%m    数字月份名,%d    数字天数,
            # %Y    四位年份,%y    两位年份,%H    24小时制小时数,%I    12小时制小时数,
            # %p    am或pm,%M    分钟数,%S    秒数
            try:
                high = int(row[5])      #获取索引5处的数据
                low = int(row[6])
            except ValueError:          #在天气的之中会出现没有值的情况,刚好ValueError可以检测到这个错误。
                print(f"Missing data for {current_date}")
            else:
                dates.append(current_date)
                highs.append(high)
                lows.append(low)
    ​
    plt.rcParams['font.sans-serif']=['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    ​
    plt.style.use("seaborn")
    fig,ax = plt.subplots()
    ax.plot(dates, highs, C="red", alpha=0.5)       # alpha透明度,0透明,1不透明。
    ax.plot(dates, lows, C="blue", alpha=0.5)
    ax.fill_between(dates,highs,lows,facecolor="blue",alpha=0.1) #x,y,y,facecolo颜色, alpha透明度,0透明,1不透明。
    ​
    ax.set_title("2018年7月每日最高气温", fontsize=24)
    ax.set_xlabel("", fontsize=14)
    fig.autofmt_xdate()                     # 绘制倾斜的标签
    ax.set_ylabel("温度", fontsize=14)
    ​
    plt.show()

2.Plotly

  1. 简单使用

    from random import randint
    ​
    class Die:
        def __init__(self, num_sides=6):
            self.num_sides = num_sides
        def roll(self):
            return randint(1, self.num_sides)       # randiint用于生成随机数
            
    die1 = Die()
    die2 = Die()
    ​
    results = [die1.roll()+die2.roll() for roll_num in range(100)]
    frequencies = [results.count(value) for value in range(1, (die1.num_sides+die2.num_sides)+1)]
    print(results)
    print(frequencies)
    # 绘制直方图
    from plotly.graph_objs import Bar,Layout
    from plotly import offline
    ​
    x_values = list(range(2, (die1.num_sides+die2.num_sides)+1))
    data = [Bar(x=x_values, y=frequencies)]             # 收集数据
    ​
    x_axis_config = {"title":"结果","dtick":1}           # x标题及属性设置,dtick是刻度间距
    y_axis_config = {"title":"结果的频率"}                # y标题及属性设置
    my_layout = Layout(title="2骰子1000次的结果", xaxis=x_axis_config, yaxis=y_axis_config)   # 标题整理
    offline.plot({"data":data,"layout":my_layout}, filename="d6.html")      # 渲染并保存
  2. json是使用非常广泛的数据格式。

    import json
    import plotly.express as px
    ​
    """
    print(px.colors.named_colorscales())        #这个方法可以查看,可以使用的渐变。
    """
    ​
    with open("bbb.json") as f:
        all_eq_data = json.load(f)          # load用于将json转为可以处理的格式
    """ 
    with open("ccc.json","w") as f:
        json.dump(all_eq_data,f,indent=4)   # dump接收一个json数据和一个文件数据,indent用于结构匹配的缩进。
    """   
    all_eq_dicts = all_eq_data["features"]
    mags, titles, lons, lats = list(), list(), list(), list()
    for eq_dict in all_eq_dicts:
        mag = eq_dict["properties"]["mag"]
        title = eq_dict["properties"]["title"]
        lon = eq_dict["geometry"]["coordinates"][0]
        lat = eq_dict["geometry"]["coordinates"][1]
        mags.append(mag)
        titles.append(title)
        lons.append(lon)
        lats.append(lat)
        
    fig = px.scatter(
        x=lons,
        y=lats,
        labels={"x":"经度","y":"纬度"},
        range_x=[-200,200]      #范围
        range_y=[-90,90]
        width=800,      #宽高800像素
        height=800,
        title="全球地震散点图",
        size = mags,    #默认点尺寸为20像素
        size_max=10,    #最大显示尺寸缩放到10
        color = mags,   #设置渐变
        hover_name = titles #震级大致位置
    )   
    fig.write_html("global_earthquakes.html")       # 保存
    fig.show()  #查看

     

4.sys

  • sys模块提供了一系列有关Python运行环境的变量和函数。

  • sys.argv,可以获取当前正在执行的命令行参数的参数列表(list)。 变量解释

    sys.argv[0]当前程序名

    sys.argv[1]第一个参数

    sys.argv[2]第二个参数

    len(sys.argv)-1 参数个数(减去文件名)

    import sys
    print(sys.argv)
    print(sys.argv[0])
    print(sys.argv[1])
    print("第二个参数:%s"%sys.argv[2])
    print("参数个数:%s"%(len(sys.argv)-1))
    -------------------结果:
    #python /root/mcw.py arg1 arg2
    ['/root/mcw.py', 'arg1', 'arg2']
    /root/mcw.py    #当前程序名
    arg1
    第二个参数:arg2
    参数个数:2
    2) 如果执行用的相对路径,返回的是相对路径
    print(sys.argv[0])
    ----------------结果:
    [root@xiaoma /root] test!
    #python ./mcw.py 
    ./mcw.py#sys.argv =['/root/mcw.py', 'arg1', 'arg2'] ,列表第一个元素为程序执行相对路径,第二个元素开始为程序传参
  • sys.path

    返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

    import sys
    print(sys.path)
    ---------------------结果:
    ['D:\\aPython_full目录\\小马过河的代码练习', 'C:\\mcw', 'C:\\mcw\\venv\\Scripts\\python36.zip', 'C:\\python3\\DLLs', 'C:\\python3\\lib', 'C:\\python3', 'C:\\mcw\\venv', 'C:\\mcw\\venv\\lib\\site-packages', 'C:\\mcw\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg', 'C:\\mcw\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg', 'C:\\软件安装\\PyCharm 2018.3.5\\helpers\\pycharm_matplotlib_backend']
    ​
    添加系统环境变量:
    import sys,os
    ​
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    print(BASE_DIR)
    #添加系统环境变量
    sys.path.append(BASE_DIR)
    print(sys.path)
    ​
    import sys
    sys.path.append("C:\python3\Scripts")
    print(sys.path)
    ------------------结果:
    ['D:\\.........., 'C:\\python3\\Scripts']
  • sys.platform

    获取当前执行环境的平台,如win32表示是Windows系统,linux2表示是linux平台

    print(sys.platform)
    -------------结果:
    win32  
    ​
    -------------结果:
    [root@xiaoma /root] test!
    #python mcw.py 
    linux2
  • sys.exit(n)

    调用sys.exit(n)可以中途退出程序,当参数非0时,会引发一个SystemExit异常,从而可以在主程序中捕获该异常。

    #vim mcw.py 
    import sys
    sys.exit(3)
    ----------结果:
    [root@xiaoma /root] test!
    #python mcw.py 
    [root@xiaoma /root] test!
    #echo $?
    3
  • sys.version

    获取Python解释程序的版本信息

    import sys
    print(sys.version)
    --------------结果:
    3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)]
    ​
    import sys
    print(sys.version)
    --------------结果:
    [root@xiaoma /root] test!
    #python mcw.py 
    2.7.5 (default, Nov  6 2016, 00:28:07) 
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
  • sys.getrefcount

    获取一个值的应用计数

    a = [11,22,33]
    b = a
    print(sys.getrefcount(a))
    --------------结果:
    3 #a,b,还有gerefcount方法三个都在使用这个列表
  • sys.getrecursionlimit python默认支持的递归数量

  • sys.stdout.write     可以做输出重定向

    for i in range(3):
        print("魔降风云变")
    import sys
    for i in range(3):
        sys.stdout.write('小马过河')
    -----------------结果:
    魔降风云变
    魔降风云变
    魔降风云变
    小马过河小马过河小马过河
    ​
    import sys
    for i in range(3):
        sys.stderr.write('小马过河')
    ------------------结果:
    小马过河小马过河小马过河

    stdout 是一个类文件对象;调用它的 write 函数可以打印出你给定的任何字符串。 实际上,这就是 print 函数真正做的事情;它在你打印的字符串后面加上一个硬回车,然后调用 sys.stdout.write 函数。 在最简单的例子中,stdout 和 stderr 把它们的输出发送到相同的地方 和 stdout 一样,stderr 并不为你添加硬回车;如果需要,要自己加上。 stdout 和 stderr 都是类文件对象,但是它们都是只写的。 它们都没有 read 方法,只有 write 方法。然而,它们仍然是类文件对象,因此你可以将其它任何 (类) 文件对象赋值给它们来重定向其输出。

  • sys.modules

    import sys,os
    print(sys.modules.keys())
    -----------------------结果;
    dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'nt', 'winreg', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', '_bootlocale', '_locale', 'encodings.gbk', '_codecs_cn', '_multibytecodec', 'sysconfig', 'encodings.cp437', 'sitecustomize'])

5.xlrd

1.背景

  • 安装模板:

    #到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境。
    #在cmd命令行输入:pip install xlrd
  • xlrd介绍:xlrd是python环境下对excel中的数据进行读取的一个模板,可以进行的操作有: 读取有效单元格的行数、列数

    读取指定行(列)的所有单元格的值

    读取指定单元格的值

    读取指定单元格的数据类型

2.常用函数

  • 打开文件(获取一个工作表):

    import xlrd
    data = xlrd.open_workbook("01.xls")#打开当前目录下名为01.xls的文档
    #此时data相当于指向该文件的指针
    table = data.sheet_by_index(0)#通过索引获取,例如打开第一个sheet表格
    table = data.sheet_by_name("sheet1")#通过名称获取,如读取sheet1表单
    table = data.sheets()[0]#通过索引顺序获取
    # 以上三个函数都会返回一个xlrd.sheet.Sheet()对象
    ​
    names = data.sheet_names()    #返回book中所有工作表的名字
    data.sheet_loaded(sheet_name or indx)   # 检查某个sheet是否导入完毕
  • 对行进行操作:

    nrows = table.nrows  #获取该sheet中的有效行数
    table.row(rowx)  #返回由该行中所有的单元格对象组成的列表
    table.row_slice(rowx)  #返回由该列中所有的单元格对象组成的列表
    table.row_types(rowx, start_colx=0, end_colx=None)    #返回由该行中所有单元格的数据类型组成的列表
    table.row_values(rowx, start_colx=0, end_colx=None)   #返回由该行中所有单元格的数据组成的列表
    table.row_len(rowx) #返回该列的有效单元格长度
  • 对列进行操作:

    ncols = table.ncols#获取列表的有效列数
    table.col(colx, start_rowx=0, end_rowx=None)#返回由该列中所有的单元格对象组成的列表
    table.col_slice(colx, start_rowx=0, end_rowx=None)#返回由该列中所有的单元格对象组成的列表
    table.col_types(colx, start_rowx=0, end_rowx=None)#返回由该列中所有单元格的数据类型组成的列表
    table.col_values(colx, start_rowx=0, end_rowx=None)#返回由该列中所有单元格的数据组成的列表
  • 对单元格进行操作:

    table.cell(rowx, colx)  # 返回单元格对象
    table.cell_type(rowx, colx)  # 返回单元格中的数据类型
    table.cell_value(rowx,colx)   #返回单元格中的数据

6.os

  1. os.path模块主要用于文件的属性获取,在编程中经常用到,以下是该模块的几种常用方法。更多的方法可以去查看官方文档:http://docs.python.org/library/os.path.html

    1. os.path.abspath(path)

      返回path规范化的绝对路径。

      os.path.abspath('test.csv') 
      'C:\\Python25\\test.csv' 
      os.path.abspath('c:\\test.csv') 
      'c:\\test.csv' 
      os.path.abspath('../csv\\test.csv') 
      'C:\\csv\\test.csv' 
    2. os.path.split(path)

      将path分割成目录和文件名二元组返回。

      os.path.split('c:\\csv\\test.csv') 
      ('c:\\csv', 'test.csv') 
      \>>> os.path.split('c:\\csv\\') 
      ('c:\\csv', '') 
    3. os.path.dirname(path)

      返回path的目录。其实就是os.path.split(path)的第一个元素。

       os.path.dirname('c:\\csv\test.csv') 
      'c:\\' 
       os.path.dirname('c:\\csv') 
      'c:\\' 
    4. os.path.basename(path)

      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素。

      os.path.basename('c:\\test.csv') 
      'test.csv' 
      os.path.basename('c:\\csv') 
      'csv' (这里csv被当作文件名处理了) 
      os.path.basename('c:\\csv\\') 
      '' 
    5. os.path.commonprefix(list)

      返回list中,所有path共有的最长的路径。

      os.path.commonprefix(['/home/td','/home/td/ff','/home/td/fff']) 
      '/home/td' 
    6. os.path.exists(path)

      如果path存在,返回True;如果path不存在,返回False。

       os.path.exists('c:\\') 
      True 
       os.path.exists('c:\\csv\\test.csv') 
      False 
    7. os.path.isabs(path)

      如果path是绝对路径,返回True。

    8. os.path.isfile(path)

      如果path是一个存在的文件,返回True。否则返回False。

       os.path.isfile('c:\\boot.ini') 
      True 
       os.path.isfile('c:\\csv\\test.csv') 
      False 
       os.path.isfile('c:\\csv\\') 
      False 
    9. os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False。

      \>>> os.path.isdir('c:\\') 
      True 
      \>>> os.path.isdir('c:\\csv\\') 
      False 
      \>>> os.path.isdir('c:\\windows\\test.csv') 
      False 
    10. os.path.join(path1[, path2[, ...]])

      将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。

      os.path.join('c:\\', 'csv', 'test.csv') 
      'c:\\csv\\test.csv' 
      os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv') 
      'c:\\csv\\test.csv' 
      os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c') 
      '/home/aa/bb/c' 
    11. os.path.normcase(path)

      在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。

      \>>> os.path.normcase('c:/windows\\system32\\') 
      'c:\\windows\\system32\\' 
    12. os.path.normpath(path)

      规范化路径。

      os.path.normpath('c://windows\\System32\\../Temp/') 
      'c:\\windows\\Temp' 
    13. os.path.splitdrive(path)

      返回(drivername,fpath)元组

      os.path.splitdrive('c:\\windows') 
      ('c:', '\\windows') 
    14. os.path.splitext(path)

      分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作

      os.path.splitext('c:\\csv\\test.csv') 
      ('c:\\csv\\test', '.csv') 
    15. os.path.getsize(path)

      返回path的文件的大小(字节)。

      os.path.getsize('c:\\boot.ini') 
      299L 
    16. os.path.getatime(path)

      返回path所指向的文件或者目录的最后存取时间。

    17. os.path.getmtime(path)

      返回path所指向的文件或者目录的最后修改时间

7.pygame

  1. 安装Pygame

    pip install pygame
  2. Pygame常用模块

    模块名 功能
    pygame.cdrom 访问光驱
    pygame.cursors 加载光标
    pygame.display 访问显示设备
    pygame.draw 绘制形状、线和点
    pygame.event 管理事件
    pygame.font 使用字体
    pygame.image 加载和存储图片
    pygame.joystick 使用游戏手柄或者类似的东西
    pygame.key 读取键盘按键
    pygame.mixer 声音
    pygame.mouse 鼠标
    pygame.movie 播放视频
    pygame.music 播放音频
    pygame.overlay 访问高级视频叠加
    pygame.rect 管理矩形区域
    pygame.scrap 本地剪贴板访问
    pygame.sndarray 操作声音数据
    pygame.sprite 操作移动图像
    pygame.surface 管理图像和屏幕
    pygame.surfarray 管理点阵图像数据
    pygame.time 管理时间和帧信息
    pygame.transform 缩放和移动图像
  • 简单示例:

    import pygame
    import sys
    ​
    pygame.init()  # 初始化pygame
    size = width, height = 320, 240  # 设置窗口大小
    screen = pygame.display.set_mode(size)  # 显示窗口
    ​
    while True:  # 死循环确保窗口一直显示
        for event in pygame.event.get():  # 遍历所有事件
            if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                sys.exit()
    pygame.quit()  # 退出pygame
  1. 制作一个跳跃的小球游戏

    • 创建一个游戏窗口,然后在窗口内创建一个小球。以一定的速度移动小球,当小球碰到游戏窗口的边缘时,小球弹回,继续运动按照如下步骤实现该功能:创建游戏窗口

    • 创建一个游戏窗口,宽和高设置为640*480。代码如下:

      import sys
      import pygame
      pygame.init()                       # 初始化pygame
      size = width, height = 640, 480     # 设置窗口大小
      screen = pygame.display.set_mode()  # 显示窗口
      import sys
      ​
      import pygame
      ​
      pygame.init()                       # 初始化pygame
      ​
      size = width, height = 640, 480     # 设置窗口大小
      ​
      screen = pygame.display.set_mode()  # 显示窗口
    • 上述代码中,首先导入pygame模块,然后调用init()方法初始化pygame模块,接下来,设置窗口的宽和高,最后使用display模块显示窗体。

  2. display模块的常用方法

    方法名 功能
    pygame.display.init() 初始化display模块
    pygame.display.quit() 结束display模块
    pygame.display.get_init() 如果display模块已经被初始化,则返回True
    pygame.display.set_mode() 初始化一个准备显示的界面
    pygame.display.get_surface() 获取当前的Surface对象
    pygame.display.flip() 更新整个待显示的Surface对象到屏幕上
    pygame.display.update() 更新部分内容显示到屏幕上,如果没有参数,则与flip功能相同(上一条)
  • 保持窗口显示

    • 运行第一步的代码后会出现一个一闪而过的黑色窗口,这是因为程序执行完成后,会自动关闭。如果想要让窗口一直显示,需要使用while True让程序一直执行,此外,还需要设置关闭按钮。具体代码如下:

      import pygame
      import sys
      ​
      pygame.init()  # 初始化pygame
      size = width, height = 320, 240  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      ​
      while True:  # 死循环确保窗口一直显示
          for event in pygame.event.get():  # 遍历所有事件
              if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                  sys.exit()
      ​
      pygame.quit()  # 退出pygame

      上述代码中添加了轮询事件检测。pygame.event.get()能够获取事件队列,使用for...in遍历事件,然后根据type属性判断事件类型。这里的事件处理方式与GUI类似,如event.type等于pygame.QUIT表示检测到关闭pygame窗口事件,pygame.KEYDOWN表示键盘按下事件,pygame.MOUSEBUTTONDOWN表示鼠标按下事件等。

  • 加载游戏图片

    • 在窗口添加小球。我们先准备好一张ball.png 图片,然后加载该图片,最后将图片显示在窗口中,具体代码如下:

      import pygame
      import sys
      ​
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      ​
      while True:  # 死循环确保窗口一直显示
          for event in pygame.event.get():  # 遍历所有事件
              if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                  sys.exit()
          screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
          screen.blit(ball, ballrect)  # 将图片画到窗口上
          pygame.display.flip()  # 更新全部显示
      ​
      pygame.quit()  # 退出pygame

      上述代码中使用iamge模块的load()方法加载图片,返回值ball是一个Surface对象。Surface是用来代表图片的pygame对象,可以对一个Surface对象进行涂画、变形、复制等各种操作。事实上,屏幕也只是一个Surfacepygame.display.set_mode()就返回了一个屏幕Surface对象。如果将ball这个Surface对象画到screen Surface 对象,需要使用blit()方法,最后使用display模块的flip()方法更新整个待显示的Surface对象到屏幕上。

  • Surface对象的常用方法

方法名 功能
pygame.Surface.blit() 将一个图像画到另一个图像上
pygame.Surface.convert() 转换图像的像素格式
pygame.Surface.convert_alpha() 转化图像的像素格式,包含alpha通道的转换
pygame.Surface.fill() 使用颜色填充Surface
pygame.Surface.get_rect() 获取Surface的矩形区域
  • 移动图片

    • 下面让小球动起来,ball.get_rect()方法返回值ballrect是一个Rect对象,该对象有一个move()方法可以用于移动矩形。move(x, y)函数有两个参数,第一个参数是 X 轴移动的距离,第二个参数是 Y 轴移动的距离。窗口的左上角是(0, 0),如果是move(100, 50)就是左移100下移50。

    • 为实现小球不停移动,将move()函数添加到while循环内,具体代码如下:

      import pygame
      import sys
      ​
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      ​
      speed = [5, 5]  # 设置移动的X轴、Y轴
      while True:  # 死循环确保窗口一直显示
          for event in pygame.event.get():  # 遍历所有事件
              if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                  sys.exit()
          ballrect = ballrect.move(speed)  # 移动小球
          screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
          screen.blit(ball, ballrect)  # 将图片画到窗口上
          pygame.display.flip()  # 更新全部显示
      ​
      pygame.quit()  # 退出pygame
  • 碰撞检测

    • 运行上述代码,发现小球在屏幕中一闪而过,此时,小球并没有真正消失,而是移动到窗体之外,此时需要添加碰撞检测的功能。当小球与窗体任一边缘发生碰撞,则更改小球的移动方向,具体代码如下:

      import pygame
      import sys
      ​
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      speed = [5, 5]  # 设置移动的X轴、Y轴
      ​
      while True:  # 死循环确保窗口一直显示
          for event in pygame.event.get():  # 遍历所有事件
              if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                  sys.exit()
                  
          ballrect = ballrect.move(speed)  # 移动小球
          # 碰到左右边缘
          if ballrect.left < 0 or ballrect.right > width:
              speed[0] = -speed[0]
          # 碰到上下边缘
          if ballrect.top < 0 or ballrect.bottom > height:
              speed[1] = -speed[1]
      ​
          screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
          screen.blit(ball, ballrect)  # 将图片画到窗口上
          pygame.display.flip()  # 更新全部显示
      ​
      pygame.quit()  # 退出pyga                          me

      上述代码中,添加了碰撞检测功能。如果碰到左右边缘,更改X轴数据为负数,如果碰到上下边缘,更改Y轴数据为负数。

  • 限制移动速度

    • 运行上述代码看似有很多球,这是因为运行上述代码的时间非常短,运行快的错觉,使用pygame的time模块,使用pygame时钟之前,必须先创建Clock对象的一个实例,然后在while循环中设置多长时间运行一次。

      import pygame
      import sys
      ​
      pygame.init()  # 初始化pygame
      size = width, height = 640, 480  # 设置窗口大小
      screen = pygame.display.set_mode(size)  # 显示窗口
      color = (0, 0, 0)  # 设置颜色
      ball = pygame.image.load('ball.png')  # 加载图片
      ballrect = ball.get_rect()  # 获取矩形区域
      speed = [5, 5]  # 设置移动的X轴、Y轴
      clock = pygame.time.Clock()  # 设置时钟
      ​
      while True:  # 死循环确保窗口一直显示
          clock.tick(60)  # 每秒执行60次
          for event in pygame.event.get():  # 遍历所有事件
              if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出
                  sys.exit()
      ​
          ballrect = ballrect.move(speed)  # 移动小球
          # 碰到左右边缘
          if ballrect.left < 0 or ballrect.right > width:
              speed[0] = -speed[0]
          # 碰到上下边缘
          if ballrect.top < 0 or ballrect.bottom > height:
              speed[1] = -speed[1]
      ​
          screen.fill(color)  # 填充颜色(设置为0,执不执行这行代码都一样)
          screen.blit(ball, ballrect)  # 将图片画到窗口上
          pygame.display.flip()  # 更新全部显示
      ​
      pygame.quit()  # 退出pygame
  • 开发Flappy Bird游戏

    • Flappy Bird是一款鸟类飞行游戏,一根手指操控按下小鸟上飞。

    • 分析 在Flappy Bird游戏中,主要有两个对象:小鸟、管道。可以创建Brid类和Pineline类来分别表示这两个对象。小鸟可以通过上下移动来躲避管道,所以在Brid类中创建一个bridUpdate()方法,实现小鸟的上下移动,为了体现小鸟向前飞行的特征,可以让管道一直向左侧移动,这样在窗口中就好像小鸟在向前飞行。所以在Pineline类中也创建一个updatePipeline()方法,实现管道的向左侧移动。此外还创建了3个函数:createMap()函数用于绘制地图;checkDead()函数用于判断小鸟的生命状态;getResult()函数用于获取最终分数。最后在主逻辑中实例化并调用相关方法,实现相应的功能。

  • 搭建主框架

    # -*- coding:utf-8 -*-
    import sys  # 导入sys模块
    import pygame  # 导入pygame模块
    import random
    ​
    ​
    class Bird(object):
        """定义一个鸟类"""
        def __init__(self):
            """定义初始化方法"""
            pass
    ​
        def birdUpdate(self):
            pass
    ​
    ​
    class Pipeline(object):
        """定义一个管道类"""
        def __init__(self):
            """定义初始化方法"""
    ​
        def updatePipeline(self):
            """水平移动"""
    ​
    ​
    def createMap():
        """定义创建地图的方法"""
        screen.fill((255, 255, 255))  # 填充颜色(screen还没定义不要着急)
        screen.blit(background, (0, 0))  # 填入到背景
        pygame.display.update()  # 更新显示
    ​
    ​
    if __name__ == '__main__':
        pygame.init()                           # 初始化pygame
        size = width, height = 400, 650         # 设置窗口大小
        screen = pygame.display.set_mode(size)  # 显示窗口
        clock = pygame.time.Clock()             # 设置时钟
        Pipeline = Pipeline()                   # 实例化管道类
        while True:
            clock.tick(60)                      # 每秒执行60次
            # 轮询事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:   # 如果检测到事件是关闭窗口
                    sys.exit()
    ​
            background = pygame.image.load("assets/background.png")  # 加载背景图片
            createMap()
        pygame.quit()  # 退出

    创建小鸟类、创建管道类、计算得分、碰撞检测

    import pygame
    import sys
    import random
    ​
    ​
    class Bird(object):
        """定义一个鸟类"""
    ​
        def __init__(self):
            """定义初始化方法"""
            self.birdRect = pygame.Rect(65, 50, 50, 50)  # 鸟的矩形
            # 定义鸟的3种状态列表
            self.birdStatus = [pygame.image.load("assets/1.png"),
                               pygame.image.load("assets/2.png"),
                               pygame.image.load("assets/dead.png")]
            self.status = 0      # 默认飞行状态
            self.birdX = 120     # 鸟所在X轴坐标,即是向右飞行的速度
            self.birdY = 350     # 鸟所在Y轴坐标,即上下飞行高度
            self.jump = False    # 默认情况小鸟自动降落
            self.jumpSpeed = 10  # 跳跃高度
            self.gravity = 5     # 重力
            self.dead = False    # 默认小鸟生命状态为活着
    ​
        def birdUpdate(self):
            if self.jump:
                # 小鸟跳跃
                self.jumpSpeed -= 1           # 速度递减,上升越来越慢
                self.birdY -= self.jumpSpeed  # 鸟Y轴坐标减小,小鸟上升
            else:
                # 小鸟坠落
                self.gravity += 0.2           # 重力递增,下降越来越快
                self.birdY += self.gravity    # 鸟Y轴坐标增加,小鸟下降
            self.birdRect[1] = self.birdY     # 更改Y轴位置
    ​
    ​
    class Pipeline(object):
        """定义一个管道类"""
    ​
        def __init__(self):
            """定义初始化方法"""
            self.wallx = 400  # 管道所在X轴坐标
            self.pineUp = pygame.image.load("assets/top.png")
            self.pineDown = pygame.image.load("assets/bottom.png")
    ​
        def updatePipeline(self):
            """"管道移动方法"""
            self.wallx -= 5  # 管道X轴坐标递减,即管道向左移动
            # 当管道运行到一定位置,即小鸟飞越管道,分数加1,并且重置管道
            if self.wallx < -80:
                global score
                score += 1
                self.wallx = 400
    ​
    ​
    def createMap():
        """定义创建地图的方法"""
        screen.fill((255, 255, 255))     # 填充颜色
        screen.blit(background, (0, 0))  # 填入到背景
    ​
        # 显示管道
        screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300))   # 上管道坐标位置
        screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500))  # 下管道坐标位置
        Pipeline.updatePipeline()  # 管道移动
    ​
        # 显示小鸟
        if Bird.dead:              # 撞管道状态
            Bird.status = 2
        elif Bird.jump:            # 起飞状态
            Bird.status = 1
        screen.blit(Bird.birdStatus[Bird.status], (Bird.birdX, Bird.birdY))              # 设置小鸟的坐标
        Bird.birdUpdate()          # 鸟移动
    ​
        # 显示分数
        screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50))  # 设置颜色及坐标位置
        pygame.display.update()    # 更新显示
    ​
    ​
    def checkDead():
        # 上方管子的矩形位置
        upRect = pygame.Rect(Pipeline.wallx, -300,
                             Pipeline.pineUp.get_width() - 10,
                             Pipeline.pineUp.get_height())
    ​
        # 下方管子的矩形位置
        downRect = pygame.Rect(Pipeline.wallx, 500,
                               Pipeline.pineDown.get_width() - 10,
                               Pipeline.pineDown.get_height())
        # 检测小鸟与上下方管子是否碰撞
        if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):
            Bird.dead = True
        # 检测小鸟是否飞出上下边界
        if not 0 < Bird.birdRect[1] < height:
            Bird.dead = True
            return True
        else:
            return False
    ​
    ​
    def getResutl():
        final_text1 = "Game Over"
        final_text2 = "Your final score is:  " + str(score)
        ft1_font = pygame.font.SysFont("Arial", 70)                                      # 设置第一行文字字体
        ft1_surf = font.render(final_text1, 1, (242, 3, 36))                             # 设置第一行文字颜色
        ft2_font = pygame.font.SysFont("Arial", 50)                                      # 设置第二行文字字体
        ft2_surf = font.render(final_text2, 1, (253, 177, 6))                            # 设置第二行文字颜色
        screen.blit(ft1_surf, [screen.get_width() / 2 - ft1_surf.get_width() / 2, 100])  # 设置第一行文字显示位置
        screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200])  # 设置第二行文字显示位置
        pygame.display.flip()                                                            # 更新整个待显示的Surface对象到屏幕上
    ​
    ​
    if __name__ == '__main__':
        """主程序"""
        pygame.init()                            # 初始化pygame
        pygame.font.init()                       # 初始化字体
        font = pygame.font.SysFont("Arial", 50)  # 设置字体和大小
        size = width, height = 400, 650          # 设置窗口
        screen = pygame.display.set_mode(size)   # 显示窗口
        clock = pygame.time.Clock()              # 设置时钟
        Pipeline = Pipeline()                    # 实例化管道类
        Bird = Bird()                            # 实例化鸟类
        score = 0
        while True:
            clock.tick(60)                       # 每秒执行60次
            # 轮询事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:
                    Bird.jump = True             # 跳跃
                    Bird.gravity = 5             # 重力
                    Bird.jumpSpeed = 10          # 跳跃速度
    ​
            background = pygame.image.load("assets/background.png")  # 加载背景图片
            if checkDead():                      # 检测小鸟生命状态
                getResutl()                      # 如果小鸟死亡,显示游戏总分数
            else:
                createMap()                      # 创建地图
        pygame.quit()
    import pygame import sys pygame.init()* # 初始化pygame* 
    size = width, height =320,240* # 设置窗口大小* 
    screen = pygame.display.set_mode(size)* # 显示窗口*
    whileTrue:* # 死循环确保窗口一直显示*
        for event in pygame.event.get():*# 遍历所有事件*
            if event.type== pygame.QUIT:*# 如果单击关闭窗口,则退出* 
                sys.exit() 
                pygame.quit()*  # 退出pygame*

标签:sheet,python,module,sys,pygame,import,path,os
From: https://www.cnblogs.com/InvincibleGrass/p/17034766.html

相关文章