1.復習(補充)
1.json數據
json數據的要求:
a.一個json對應一個數據
b.json中的數據一定是json支持的數據類型
數字:整數和小數
字符串:雙引號引起來的內容
數組:[120, "anc", true, [1, 2], {"a":123}]
字典: {"abc":120, "aa":"abc", "list":[1, 2]}
布爾: true/false
null: 空(None)
json模塊:
load(文件對象) --> 將文件中的內容讀出來,轉換成python對應的數據
dump(內容, 文件對象) --> 將內容以json格式,寫入到文件中
loads(字符串) --> 將json格式字符串轉換成python數據 '{"a": 12}'
dumps(python數據) --> 將python數據轉換成json格式的字符串
2.異常處理
try-except-finally語法捕獲異常
raise語法拋出異常
a.
try:
代碼1
except:
代碼2
try:
代碼1
except (異常類型1,異常類型2...):
代碼2
try:
代碼1
except 異常類型1:
代碼2
except 異常類型2:
代碼3
...
b. raise 錯誤類型
錯誤類型:必須是Exception的子類(系統的錯誤類型和自定義的類型)
自定義錯誤類型:寫一個類繼承Exception,重寫__str__方法定制錯誤提示語
3.類和對象
a.類的聲明
class 類名(父類列表):
類的內容
b.創建對象
對象 = 類名()
c.類的字段和對象的屬性
類的字段:
對象的屬性:init方法,self.屬性=值
d.對象方法,類方法,靜態方法
對象方法:
類方法:@classmethod
靜態方法:@staticmethod
e.對象屬性的增刪改查
f.私有化:名字前加__
g.getter和setter
h.常用的內置屬性: 對象.__dict__, 對象.__class__, 類.__name__
i.繼承:所有類都默認繼承object,繼承哪些東西,重寫(super()), 添加對象屬性
代碼示例
class Perosn(object):
def __init__(self):
self._age = 0
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = value
補充1:拋出異常
代碼示例
class MyError(Exception):
def __str__(self):
return '需要一個偶數,但是給了一個奇數'
number = int(input('請輸入一個偶數:'))
if number & 1:
raise MyError
運行結果
請輸入一個偶數:1
Traceback (most recent call last):
File "E:/Python Study/第一階段/day17-pygame/01-recode.py", line 98, in <module>
raise MyError
__main__.MyError: 需要一個偶數,但是給了一個奇數
補充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('可以飛')
class Bird(Animal, Fly):
def __init__(self, color):
super().__init__(10)
self.color = color
注意:多繼承的時候,只能繼承第一個父類的對象屬性(創建對象的時候調用的是第一個父類的對象方法)一般在需要繼承多個類的功能的時候用
代碼示例
b1 = Bird('abc')
# b1.age = 18
# b1.height = 200
print(b1.age)
# print(b1.height)
b1.can_fly()
b1.run()
運行結果
10
可以飛
可以跑
擴展(將對象保存到本地)
代碼示例
import json
class Student:
def __init__(self, name='', age=0, tel=''):
self.name = name
self.age = age
self.tel = tel
self.sex = '男'
def show_info(self):
print(self.__dict__)
def __repr__(self):
return '<' + str(self.__dict__)[1:-1] + '>'
all_students = [Student('小明', 18, '1278763'),
Student('xiaohua', 12, '127723')
]
class Dog:
def __init__(self):
self.name = ''
self.age = 0
self.color = ''
self.type = ''
def __repr__(self):
return '<' + str(self.__dict__)[1:-1] + '>'
# 將對象保存到本地
def object_json(file, content):
with open('./' + file, 'w', encoding='utf-8') as f:
new = []
for stu in content:
new.append(stu.__dict__)
json.dump(new, f)
# object_json('test.json', all_students)
擴展(將字典列表轉換成對象列表)
代碼示例
def json_object(file, type):
with open('./' + file, 'r', encoding='utf-8') as f:
list1 = json.load(f)
all_value = []
for dict1 in list1:
object = type()
for key in dict1:
setattr(object, key, dict1[key])
all_value.append(object)
return all_value
# print(json_object('test.json', Student))
# print(json_object('test2.json', Dog))
擴展(將不同類型的對象添加到不同的json文件中)
代碼示例
def add_object_json2(obj: object):
file_name = obj.__class__.__name__ + '.json'
# 獲取原文中的內容
try:
with open('./' + file_name, encoding='utf-8') as f:
list1 = json.load(f)
except FileNotFoundError:
list1 = []
with open('./' + file_name, 'w', encoding='utf-8') as f:
list1.append(obj.__dict__)
json.dump(list1, f)
add_object_json2(stu)
add_object_json2(dog1)
def get_all_info(type):
file = type.__name__ + '.json'
with open('./' + file, 'r', encoding='utf-8') as f:
list1 = json.load(f)
all_value = []
for dict1 in list1:
object = type()
for key in dict1:
setattr(object, key, dict1[key])
all_value.append(object)
return all_value
print('學生:', get_all_info(Student))
print('狗:', get_all_info(Dog))
運行結果可自行檢測
2.抽象類
抽象類:只能被繼承不能實例化的類
抽象方法:聲明的時候不用實現,在子類中必須去重寫的方法
怎么聲明抽象類:類繼承abc模塊中的ABCMeta,繼承的時候需要參數metaclass.并且通過
abstractmethod來聲明抽象方法
子類繼承一個抽象類,必須在子類中實現抽象類中所有的抽象方法
代碼示例
import abc
class Shape(metaclass=abc.ABCMeta): # 不能實例化
# 聲明抽象方法
@abc.abstractmethod
def draw(self):
pass
class Circle(Shape):
def draw(self): # 必須實現抽象方法
print('123')
c1 = Circle()
3.pygame圖片的顯示
display --> 屏幕相關
event --> 事件
draw --> 圖形
image --> 圖片
font --> 字體
代碼示例
# 1.初始化游戲
pygame.init()
# 2.創建窗口對象
"""
set_mode(size):設置窗口大小 --> size是元組:(長、寬),單位是像素
"""
screen = pygame.display.set_mode((600, 600))
"""
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('image/d.jpg')
"""
a.獲取圖片的大小
圖片.get_size() --> 返回圖片的大小,結果是元組
"""
image_width, image_height = image.get_size()
"""
b.對圖片進行縮放
transform.scale(圖片對象,大小) ---> 將指定的圖片縮放成指定大小,
返回一個新的圖片
注意:可能會使圖片發生形變
"""
new_image = pygame.transform.scale(image, (150, 200))
"""
c.對圖片進行縮放旋轉
transform.rotozoom(圖片對象,角度,比例)
比例:原圖的多少倍, 放大:大于1 反之
角度:0-360(逆時針旋轉)
"""
new_image1 = pygame.transform.rotozoom(image, 90, 1)
angle = 0
"""
2.渲染圖片
blit(渲染對象,渲染位置)
渲染位置 -> 元組,(x坐標,y坐標)
"""
screen.blit(new_image1, (0, 0))
"""
3.展示類容
只要想將內容展示在屏幕 上,都要調用這個方法
"""
pygame.display.flip()
# 3.游戲循環(不斷檢測是否有事件發生 )
while True:
# 不斷檢測事情的產生
for event in pygame.event.get():
# 不同類型的事情,event的type屬性不同
if event.type == pygame.QUIT:
exit() # 結束
# angle += 1
# new_image1 = pygame.transform.rotozoom(image, angle, 0.5)
# screen.blit(new_image1, (300, 300))
# pygame.display.flip()
運行結果可自行檢測
4.pygame文字顯示
代碼示例
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255)) # 填充背景顏色
pygame.display.flip()
"""
顯示文字:
1.創建字體對象
font.SysFont(字體名, 字體大小, 是否加粗=False, 是否傾斜=False)
---> 創建系統字體對象
font.Font(字體文件路徑,字體大小) ---> 自定義字體
字體文件:后綴就是.ttf文件
"""
# font = pygame.font.SysFont('NewTimes', 20)
font = pygame.font.Font('aa.ttf', 50)
"""
2.根據字體創建文字對象
字體對象.render(文字, 是否抗鋸齒, 顏色)
"""
text = font.render('哈羅', True, (0, 255, 0))
"""
3.在窗口上渲染文字
"""
screen.blit(text, (100, 100))
# 展示在屏幕上
pygame.display.flip()
while True:
for event in pygame.event.get():
# 不同類型的事情,event的type屬性不同
if event.type == pygame.QUIT:
exit() # 結束
運行結果可自行檢測
5.pygame圖片顯示
代碼示例
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.畫線
draw.line(Surface, color, start_pos, end_pos, width=1)
Surface: 窗口,圖片,文字對象
color: 線的顏色
start_pos, end_pos: 起點和終點(坐標)
width: 寬度
"""
pygame.draw.line(screen, (0, 0, 0), (50, 50), (100, 100), 5)
"""
draw.lines(Surface, color, closed, pointlist, width=1)
closed: 是否閉合起點和終點
pointlist: 列表,列表中的元素是點對應的元組
"""
points = [(50, 100), (200, 100), (250, 200), (120, 250), (30, 160)]
pygame.draw.lines(screen, (255, 0, 0), True, points, 5)
"""
2.畫圖
draw.circle(Surface, color, pos, radius, width=0)
pos:圓心的位置
radius:半徑
width=0:默認0(填充)
"""
pygame.draw.circle(screen, rand_color(), (100, 200), 80)
"""
draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1)
Rect:(x, y, w, h):確定鉅形的坐標,高度,寬度
start_angle,stop_angle:起始弧度(0->0, 90->pi/2,.....)
"""
from math import pi
screen.fill((255, 255, 255)) # 將之前畫的全部覆蓋掉
pygame.draw.arc(screen, rand_color(), (100, 100, 200, 100), 0, pi*2, 5)
pygame.display.flip()
while True:
for event in pygame.event.get():
# 不同類型的事情,event的type屬性不同
if event.type == pygame.QUIT:
exit() # 結束
運行結果可自行檢測
6.pygame事件
代碼示例
import pygame
import random
def rand_color():
"""隨機顏色"""
return random.randint(0, 255),random.randint(0, 255),random.randint(0, 255)
"""
鼠標事件
MOUSEBUTTONDOWN:鼠標點擊事件
MOUSEBUTTONUP:鼠標彈起事件
MOUSEMOTION:鼠標移動事件
event.pos:獲取鼠標坐標
鍵盤事件
KEYDOWN:鍵盤按下事件
KEYUP:鍵盤彈起事件
event.key:獲取按鍵的值(得到的是一個編碼值)
chr(event.key):將編碼值轉換成字符
"""
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()
while True:
# 只要有事件產生就會進入for循環
for event in pygame.event.get():
# 不同類型的事情,event的type屬性不同
# 根據type來判斷是什么事件產生的
if event.type == pygame.QUIT:
exit() # 結束
elif event.type == pygame.MOUSEBUTTONDOWN:
# 鼠標按下后要做什么事情
print('鼠標點擊事件', event.pos)
pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
pygame.display.update() # 更新屏幕
elif event.type == pygame.MOUSEBUTTONUP:
print('鼠標彈起事件')
elif event.type == pygame.MOUSEMOTION:
print('鼠標移動事件')
pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
pygame.display.update() # 更新屏幕
# =========================鼠標事件=========================
elif event.type == pygame.KEYDOWN:
print('鍵盤按下', event.key, chr(event.key))
elif event.type == pygame.KEYUP:
print('鍵盤彈起')