day17-pygame

1.復(fù)習(xí)(補(bǔ)充)

1.json數(shù)據(jù)
json數(shù)據(jù)的要求:
a.一個(gè)json對(duì)應(yīng)一個(gè)數(shù)據(jù)
b.json中的數(shù)據(jù)一定是json支持的數(shù)據(jù)類型

數(shù)字:整數(shù)和小數(shù)
字符串:雙引號(hào)引起來的內(nèi)容
數(shù)組:[120, "anc", true, [1, 2], {"a":123}]
字典: {"abc":120, "aa":"abc", "list":[1, 2]}
布爾: true/false
null: 空(None)

json模塊:
load(文件對(duì)象) --> 將文件中的內(nèi)容讀出來,轉(zhuǎn)換成python對(duì)應(yīng)的數(shù)據(jù)
dump(內(nèi)容, 文件對(duì)象) --> 將內(nèi)容以json格式,寫入到文件中

loads(字符串) --> 將json格式字符串轉(zhuǎn)換成python數(shù)據(jù)  '{"a": 12}'
dumps(python數(shù)據(jù)) --> 將python數(shù)據(jù)轉(zhuǎn)換成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 錯(cuò)誤類型
錯(cuò)誤類型:必須是Exception的子類(系統(tǒng)的錯(cuò)誤類型和自定義的類型) 
自定義錯(cuò)誤類型:寫一個(gè)類繼承Exception,重寫__str__方法定制錯(cuò)誤提示語

3.類和對(duì)象
a.類的聲明
class 類名(父類列表):
    類的內(nèi)容

b.創(chuàng)建對(duì)象
對(duì)象 = 類名()

c.類的字段和對(duì)象的屬性
類的字段:
對(duì)象的屬性:init方法,self.屬性=值

d.對(duì)象方法,類方法,靜態(tài)方法
對(duì)象方法:
類方法:@classmethod 
靜態(tài)方法:@staticmethod 

e.對(duì)象屬性的增刪改查
f.私有化:名字前加__
g.getter和setter
h.常用的內(nèi)置屬性: 對(duì)象.__dict__, 對(duì)象.__class__, 類.__name__
i.繼承:所有類都默認(rèn)繼承object,繼承哪些東西,重寫(super()), 添加對(duì)象屬性

代碼示例

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

補(bǔ)充1:拋出異常

代碼示例

class MyError(Exception):
    def __str__(self):
        return '需要一個(gè)偶數(shù),但是給了一個(gè)奇數(shù)'


number = int(input('請(qǐng)輸入一個(gè)偶數(shù):'))
if number & 1:
    raise MyError

運(yùn)行結(jié)果

請(qǐng)輸入一個(gè)偶數(shù):1
Traceback (most recent call last):
  File "E:/Python Study/第一階段/day17-pygame/01-recode.py", line 98, in <module>
    raise MyError
__main__.MyError: 需要一個(gè)偶數(shù),但是給了一個(gè)奇數(shù)

補(bǔ)充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

注意:多繼承的時(shí)候,只能繼承第一個(gè)父類的對(duì)象屬性(創(chuàng)建對(duì)象的時(shí)候調(diào)用的是第一個(gè)父類的對(duì)象方法)一般在需要繼承多個(gè)類的功能的時(shí)候用

代碼示例

b1 = Bird('abc')
# b1.age = 18
# b1.height = 200
print(b1.age)
# print(b1.height)
b1.can_fly()
b1.run()

運(yùn)行結(jié)果

10
可以飛
可以跑

擴(kuò)展(將對(duì)象保存到本地)

代碼示例

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] + '>'
# 將對(duì)象保存到本地
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)

擴(kuò)展(將字典列表轉(zhuǎn)換成對(duì)象列表)

代碼示例

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))

擴(kuò)展(將不同類型的對(duì)象添加到不同的json文件中)

代碼示例

def add_object_json2(obj: object):
    file_name = obj.__class__.__name__ + '.json'

    # 獲取原文中的內(nèi)容
    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('學(xué)生:', get_all_info(Student))
print('狗:', get_all_info(Dog))

運(yùn)行結(jié)果可自行檢測(cè)

2.抽象類

抽象類:只能被繼承不能實(shí)例化的類
抽象方法:聲明的時(shí)候不用實(shí)現(xiàn),在子類中必須去重寫的方法

怎么聲明抽象類:類繼承abc模塊中的ABCMeta,繼承的時(shí)候需要參數(shù)metaclass.并且通過
abstractmethod來聲明抽象方法

子類繼承一個(gè)抽象類,必須在子類中實(shí)現(xiàn)抽象類中所有的抽象方法

代碼示例

import abc


class Shape(metaclass=abc.ABCMeta):  # 不能實(shí)例化

    # 聲明抽象方法
    @abc.abstractmethod
    def draw(self):
        pass


class Circle(Shape):
    def draw(self):   # 必須實(shí)現(xiàn)抽象方法
        print('123')


c1 = Circle()

3.pygame圖片的顯示

display --> 屏幕相關(guān)
event --> 事件
draw --> 圖形
image --> 圖片
font --> 字體

代碼示例

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

# 2.創(chuàng)建窗口對(duì)象
"""
set_mode(size):設(shè)置窗口大小  --> size是元組:(長、寬),單位是像素
"""
screen = pygame.display.set_mode((600, 600))
"""
fill(顏色) --> 填充指定的顏色,元組(red,green,blue)
計(jì)算機(jī)使用的是計(jì)算機(jī)三原色(紅,綠,藍(lán)) ---> rgb顏色,對(duì)應(yīng)的值的范圍是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(圖片地址) --> 返回圖片對(duì)象
"""
image = pygame.image.load('image/d.jpg')

"""
a.獲取圖片的大小
圖片.get_size() --> 返回圖片的大小,結(jié)果是元組
"""
image_width, image_height = image.get_size()

"""
b.對(duì)圖片進(jìn)行縮放
transform.scale(圖片對(duì)象,大小) ---> 將指定的圖片縮放成指定大小,
返回一個(gè)新的圖片
注意:可能會(huì)使圖片發(fā)生形變
"""
new_image = pygame.transform.scale(image, (150, 200))

"""
c.對(duì)圖片進(jìn)行縮放旋轉(zhuǎn)
transform.rotozoom(圖片對(duì)象,角度,比例)
比例:原圖的多少倍,  放大:大于1 反之
角度:0-360(逆時(shí)針旋轉(zhuǎn))
"""
new_image1 = pygame.transform.rotozoom(image, 90, 1)

angle = 0
"""
2.渲染圖片
blit(渲染對(duì)象,渲染位置)
渲染位置 -> 元組,(x坐標(biāo),y坐標(biāo))
"""
screen.blit(new_image1, (0, 0))

"""
3.展示類容
只要想將內(nèi)容展示在屏幕 上,都要調(diào)用這個(gè)方法
"""
pygame.display.flip()

# 3.游戲循環(huán)(不斷檢測(cè)是否有事件發(fā)生 )
while True:
    # 不斷檢測(cè)事情的產(chǎn)生
    for event in pygame.event.get():
        # 不同類型的事情,event的type屬性不同
        if event.type == pygame.QUIT:
            exit()   # 結(jié)束
    # angle += 1
    # new_image1 = pygame.transform.rotozoom(image, angle, 0.5)
    # screen.blit(new_image1, (300, 300))
    # pygame.display.flip()

運(yùn)行結(jié)果可自行檢測(cè)

4.pygame文字顯示

代碼示例

import pygame

pygame.init()

screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))  # 填充背景顏色
pygame.display.flip()

"""
顯示文字:
1.創(chuàng)建字體對(duì)象
font.SysFont(字體名, 字體大小, 是否加粗=False, 是否傾斜=False)
---> 創(chuàng)建系統(tǒng)字體對(duì)象
font.Font(字體文件路徑,字體大小) ---> 自定義字體
字體文件:后綴就是.ttf文件
"""
# font = pygame.font.SysFont('NewTimes', 20)
font = pygame.font.Font('aa.ttf', 50)

"""
2.根據(jù)字體創(chuàng)建文字對(duì)象
字體對(duì)象.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()  # 結(jié)束

運(yùn)行結(jié)果可自行檢測(cè)

5.pygame圖片顯示

代碼示例

import pygame
import random


def rand_color():
    """隨機(jī)顏色"""
    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: 窗口,圖片,文字對(duì)象
color: 線的顏色
start_pos, end_pos: 起點(diǎn)和終點(diǎn)(坐標(biāo))
width: 寬度
"""
pygame.draw.line(screen, (0, 0, 0), (50, 50), (100, 100), 5)

"""
draw.lines(Surface, color, closed, pointlist, width=1)
closed: 是否閉合起點(diǎn)和終點(diǎn)
pointlist: 列表,列表中的元素是點(diǎn)對(duì)應(yīng)的元組
"""
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:默認(rèn)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):確定鉅形的坐標(biāo),高度,寬度
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()  # 結(jié)束

運(yùn)行結(jié)果可自行檢測(cè)

6.pygame事件

代碼示例

import pygame
import random


def rand_color():
    """隨機(jī)顏色"""
    return random.randint(0, 255),random.randint(0, 255),random.randint(0, 255)


"""
鼠標(biāo)事件
MOUSEBUTTONDOWN:鼠標(biāo)點(diǎn)擊事件
MOUSEBUTTONUP:鼠標(biāo)彈起事件
MOUSEMOTION:鼠標(biāo)移動(dòng)事件
event.pos:獲取鼠標(biāo)坐標(biāo)

鍵盤事件
KEYDOWN:鍵盤按下事件
KEYUP:鍵盤彈起事件
event.key:獲取按鍵的值(得到的是一個(gè)編碼值)
chr(event.key):將編碼值轉(zhuǎn)換成字符
"""
pygame.init()
screen = pygame.display.set_mode((600, 400))
screen.fill((255, 255, 255))
pygame.display.flip()

while True:
    # 只要有事件產(chǎn)生就會(huì)進(jìn)入for循環(huán)
    for event in pygame.event.get():
        # 不同類型的事情,event的type屬性不同
        # 根據(jù)type來判斷是什么事件產(chǎn)生的
        if event.type == pygame.QUIT:
            exit()  # 結(jié)束

        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 鼠標(biāo)按下后要做什么事情
            print('鼠標(biāo)點(diǎn)擊事件', event.pos)
            pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
            pygame.display.update()  # 更新屏幕

        elif event.type == pygame.MOUSEBUTTONUP:
            print('鼠標(biāo)彈起事件')

        elif event.type == pygame.MOUSEMOTION:
            print('鼠標(biāo)移動(dòng)事件')
            pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
            pygame.display.update()  # 更新屏幕

        # =========================鼠標(biāo)事件=========================
        elif event.type == pygame.KEYDOWN:
            print('鍵盤按下', event.key, chr(event.key))
        elif event.type == pygame.KEYUP:
            print('鍵盤彈起')

運(yùn)行結(jié)果可自行檢測(cè)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,211評(píng)論 3 119
  • 在 Mac 上配置 Caffe 大概花了半天多的時(shí)間,時(shí)間主要是花在解決各種奇怪的 error 上面了。在此記錄一...
    MoreThanCode閱讀 1,649評(píng)論 1 1
  • react-navigation實(shí)現(xiàn)頁面框架 初始化一個(gè)RN項(xiàng)目 page.json 引入react-naviga...
    evanywang閱讀 4,059評(píng)論 2 3
  • 點(diǎn)擊查看:全文目錄 上一章:(1)突變 三年后。 在本市最大的夜店里,各色人群縱情狂歡,群魔亂舞。夜店一角,一個(gè)平...
    跳刀風(fēng)杖閱讀 743評(píng)論 0 0
  • 每當(dāng)《獨(dú)家記憶》那輕緩悠揚(yáng)的旋律、優(yōu)美柔和的歌詞飄進(jìn)我的耳朵時(shí),你可愛的微笑的臉龐、微胖而靈活的身影便浮現(xiàn)...
    不將就_2377閱讀 340評(píng)論 0 3

友情鏈接更多精彩內(nèi)容