美文网首页
day17pygame

day17pygame

作者: PythonLi | 来源:发表于2018-10-22 21:08 被阅读0次

1.recode

1.json数据
json数据的要求
a.一个json文件对应一个数据
b.json中的数据一定是一个json支持的数据类型

数字:整数和小数
字符串:双引号括起来的内容
数组:[120,"anc",true,[1,2],{"a":123}]
字典:{"abc":120}
布尔:
null:

json模块:
load(文件对象)---> 将文件中的内容读出来,然后转换成python对应的数据类型
dump(内容,文件对象)--->将内容以json格式写入到文件红

loads(字符串)---> 将json格式字符串转换成python数据 '{"a":12}'
dumps(python数据)---> 将python数据转换成json对应的字符串

2.异常处理
try-except-finally语法捕获 异常
raise语法抛出异常

try:
代码
except:
代码2

try:
代码1
except(异常类型1,异常类型2...)
代码2

try:
代码1
except 异常类型1:
代码2
except 异常类型2:
代码3
....

b. raise错误类型
错误类型: 必须是Exception(系统的错误类型和自定义类型)
自定义: 学一个Kauai回城except,重写)str(self):方法定制错误语法提示

3.类和对象
a.类的声明
class 类名(父类):
类的内容

b.创建对象
对象 = 类名()

c . 对象的属性
类的字段:
对象属性:init方法,self.属性 = 值

d. 对象方法,类方法,静态方法
对象方法: 要用到对象属性
类方法:@classmethod 自带参数,需要用到类的字段
静态方法:@staticmethod 对象属性和类的字段都不需要

e. 对象属性的增删改查
对象.属性

f. 私有化 : 名字前面加__

g. getattr setattr

h.常用的内置属性:对象.class 类.name 对象.dict_

i. 继承: 所有的类都默认继承object,继承所有的方法和类字段,重写 super()

# 补充2:多继承
class Animal:
    num = 10
    def __init__(self, age):
        self.age = age

    def run(self):
        print('可以跑')

print(Animal.__dict__)

class Fly:
    def __init__(self, height):
        self.height = height

    def can_fly(self):
        print('可以飞')
f1 = Fly(200)

class Bird(Animal, Fly):
    def __init__(self, color,height):
        super().__init__(10)
        self.color = color
        self.height = height


# 注意:多继承的时候,只能继承第一个父类的对象属性(创建对象的时候调用的是第一个父类的对象方法)
# 一般在需要继承多个类的功能的时候用
b1 = Bird('abc',220)
b1.age = 18
#b1.height = 200
print(b1.age)
print(b1.height)
b1.can_fly()
b1.run()
import json
class Person:
    def __init__(self,name='',age=0,tel=''):
        self.name = name
        self.age = age
        self.tel = tel
    def __repr__(self):
        return str(self.__dict__)
stu1 = Person('小明',18,'123451')
class Dog:
    def __init__(self):
        self.name = ''
        self.age = 0
        self.color = ''
        self.type = ''
    def __repr__(self):
        return str(self.__dict__)
dog1 = Dog()
dog1.name = '小黑'
dog1.age = 3
dog1.color='黑色'
dog1.type = '土狗'

def object_json(file,content):
    with open('./'+file,'w',encoding='utf-8') as  f:
        new = []
        #for stu in content:
        new.append(content.__dict__)
        json.dump(new,f)
object_json('Person.json',stu1)
object_json('Dog.json',dog1)


def get_all_info(type):
    with open('./'+type.__name__+'.json','r',encoding='utf-8') as f:
        all_info = json.load(f)
        list1 = []
        for info1 in all_info:#allinfo列表中遍历出每个字典
            object = type()
            for key in info1:
                setattr(object,key,info1[key])
            list1.append(object)
        return list1

print(get_all_info(Person))
print(get_all_info(Dog))

2.抽象类和抽象方法

抽象类:只能被继承不能实例化(不能创建对象)
抽象方法:声明的时候不用实现,在子类中必须去重写的方法

怎么声明抽象类: 类继承abc模块中的ABCMeta,继承的时候需要加参数metaclass
并且要通过@abstractclassmethod 来声明抽象方法
子类继承一个抽象类后,必须在子类中实现抽象类中所有的抽象方法

import abc
# 声明抽象类
class Shape(metaclass=abc.ABCMeta):
    # 声明抽象方法
    @abc.abstractclassmethod
    def draw(self):
        pass
#s1 = Shape()

class Circle(Shape):
    def draw(self):
        print('必须实现抽象方法')

    #area = lambda a=4,b=5 : a*b
c1 = Circle()
c1.draw()
#c1.area()

3.pygame图片显示

display --> 屏幕相关
event --> 事件
draw --> 图形
image-->图片
font-->字体

# 1.初始化游戏
pygame.init()

# 2.创建窗口对象

#set_mode(size) --->size是元组:(长,宽)单位是像素  

screen = pygame.display.set_mode((533,300))

#fill(颜色)-->填充指定的颜色,元组(red,green,blue)
#计算机使用的是计算机三原色(红、绿、蓝)---> rgb##颜色,对应的值的范围(0-255)
#红色:(255,0,0)
#绿色(0,255,0)
#白色(255,255,255)
#黑色(0,0,0)
#黄色(255,255,0)

screen.fill((255,255,255))
# 4.显示图片

#1.加载图片
#load(图片地址) -->返回图片对象

image = pygame.image.load('./files/风景.jpg')
"""
a.获取图片大小
图片.get_size()---> 返回图片的大小,结果是元组
"""
size = image.get_size()
print(size)
image_width, image_height = image.get_size()
"""
b.将图片进行缩放
transform.scale(图片对象,大小)--->将指定的图片进行缩放
注意: 这种缩放可能会然图片发送形变
"""
new_image1 = pygame.transform.scale(image,(100,100))

"""
c.对图片进行缩放和旋转
pygame.transform.rotozoom(图片对象,角度,缩放比例)
比例: 原图的多少倍,放大: 大于1  缩小:大于1

"""
new_image2 = pygame.transform.rotozoom(image,0,0.5)
"""
2.渲染图片
blit(渲染对象,渲染位置)
渲染位置 --> 元组,(x坐标,y坐标)
"""
screen.blit(new_image2,(133,75))

"""
3.展示内容
只要想将内容展示在屏幕上,都必须调用这个方法
"""
pygame.display.flip()

# 3. 游戏循环(不断检测是否有事件发生)
while True:
    #events = pygame.event.get()
    # 不断检测事件的产生
        for event in pygame.event.get():
            #不同的类型的事件,事件event的type属性不同
            if event.type == pygame.QUIT:
                exit()#程序结束

3.pygame显示文字

import pygame

pygame.init()
screen = pygame.display.set_mode((600,400))
screen.fill((255,255,255))
pygame.display.flip()

1.创建字体对象
SysFont(字体名,字体大小,是否加粗=Flase,是否倾斜=Flase)--->创建系统字体
Font(字体文件路径,字体大小)--->自定义字体
字典文件:后缀是.ttf文件

#font = pygame.font.SysFont('NewTimes',100)
font = pygame.font.Font('./files/aa.ttf',60)

2.根据字体创建文字对象
字体对象.render(文字内容,是否抗锯齿,文字颜色)

text = font.render('红红火火恍恍惚惚',True,(255,0,0))

3.在屏幕上渲染文字

screen.blit(text,(65,150))

4.展示在屏幕上

pygame.display.flip()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

5.图形显示

import pygame
import random
def rand_color():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)

pygame.init()
screen = pygame.display.set_mode((600,400))
screen.fill((255,255,255))

1.画线
def line(Surface,color,star_pos,end_pos,width=1)
Surface: 串口, 图片, 文字
color:颜色
star_pos,end_pos :起点和终点(坐标)元组
width:宽度

pygame.draw.line(screen,(255,0,0,),(50,50),(100,100),50)

画多条线
def lines(Surface, color, closed, pointlist, width=1)
closed:
pointlist:列表,列表中的元素是对应的坐标

points = [(50,100),(200,100),(250,180),(150,200),(30,230)]
pygame.draw.lines(screen,(255,0,0),True,points)

2.画圆
def circle(Surface, color, pos, radius, width=0)
pos:圆心位置
radius:半径
width:默认0 (填充)

pygame.draw.circle(screen,(255,255,0),(400,200),150)

3.画弧
def arc(Surface, color, Rect, start_angle, stop_angle, width=1)
Rect:(x,y,w,h)(坐标,宽,高)
start_angle, stop_angle:弧度(0->0,90->pi/2,45->pi/4)

from math import pi
screen.fill((255,255,255)) #将之前画的全部覆盖。
pygame.draw.arc(screen,rand_color(),(100,100,150,150),pi/4,pi/4*3,5)
pygame.draw.arc(screen,rand_color(),(250,100,150,150),pi/4,pi/4*3,5)

4.椭圆
def ellipse(Surface, color, Rect, width=0)

pygame.draw.ellipse(screen,rand_color(),(190,180,100,70),2)

5.矩形a
def rect(Surface, color, Rect, width=0)

pygame.draw.rect(screen,rand_color(),(350,200,150,100),3)

pygame.display.flip()

while True:
    for event in  pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

6.pygame事件

事件类型:event.type
MOUSEBUTTONDOWN 按下
MOUSEBUTTONUP 弹起
MOUSEMOTION 移动
关心鼠标的位置:event.pos

import random
import pygame


pygame.init()
screen = pygame.display.set_mode((600,400))
screen.fill((255,255,255))
pygame.display.flip()
#screen.fill((255,255,255))
def rand_color():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)
while True:
    #只要有事件产生就会进入for循环
    for event in  pygame.event.get():
        #根据判断type的值来判断是什么事件产生了
        if event.type == pygame.QUIT:
            exit()
 #=========================鼠标=====================================
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 鼠标按下后要做什么事情就写在这儿...
            print('鼠标按下:',event.pos)
            pygame.draw.circle(screen, rand_color(), event.pos, 30)
            pygame.display.flip()
            screen.fill((255,255,255))

        elif event.type == pygame.MOUSEBUTTONUP:
            # 鼠标弹起后
            print('鼠标弹起',event.pos)
        elif event.type == pygame.MOUSEMOTION:
            # 鼠标移动
            print('鼠标移动',event.pos)
            #pygame.draw.circle(screen,rand_color(),event.pos, 30)
            #pygame.display.flip()
# ===========================键盘============================
        elif event.type ==pygame.KEYDOWN:
            print('按键按下:',event.key,chr(event.key))

        elif event.type == pygame.KEYUP:
            print('按键弹起:',event.key,chr(event.key))

相关文章

  • day17pygame

    1.recode 1.json数据json数据的要求a.一个json文件对应一个数据b.json中的数据一定是一个...

网友评论

      本文标题:day17pygame

      本文链接:https://www.haomeiwen.com/subject/mslnzftx.html