17總 pygame

復(fù)習(xí):

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

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


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]+'>'

import json

將對(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)

將字典列表轉(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))


stu = Student('xiaoming', 12, '231273')  # Student.json

dog1 = Dog()   # Dog.json
dog1.name = 'XiaoHua'
dog1.age = 3
dog1.color = '黃色'
dog1.type = '斗狗'

將不同類型的對(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))

問題:怎么將對(duì)象寫入json文件中?怎么將json中的字典讀出后轉(zhuǎn)換成相應(yīng)的對(duì)象?

1.抽象類和抽象方法:

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

怎么聲明抽象類:類繼承abc模塊中的ABCMeta,繼承的時(shí)候需要加參數(shù)metaclass。
并且要通過abstractmethod來聲明抽象方法
子類繼承一個(gè)抽象類,必須在子類中實(shí)現(xiàn)抽象類中所有的抽象方法
metaclass -> 元類
···
import abc

class Shape(metaclass=abc.ABCMeta):
# 聲明抽象方法
@abc.abstractmethod
def draw(self):
pass

@abc.abstractmethod
def area(self):
    pass

class Circle(Shape):
def draw(self):
print('畫圖形')

def area(self):
    print('面積')

···

抽象類不能實(shí)例化

s1 = Shape()

c1 = Circle()

2pygame圖片顯示:

import pygame

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

1.初始化游戲

pygame.init()

2.創(chuàng)建窗口對(duì)象

"""
set_mode(size) --> size是元祖:(長,寬), 單位是像素
"""
screen = pygame.display.set_mode((600, 400))

···
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('./files/luffy4.jpg')

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

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

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

"""
2.渲染圖片
blit(渲染對(duì)象,渲染位置)
渲染位置 -> 元祖,(x坐標(biāo), y坐標(biāo))
"""
screen.blit(new_image2, (100, 100))

angle = 0

"""
3.展示內(nèi)容,只要想將內(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é)束

"""author = 余婷"""

import pygame

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

顯示文字

"""
1.創(chuàng)建字體對(duì)象
SysFont(字體名, 字體大小, 是否加粗=False, 是否傾斜=False) --> 創(chuàng)建系統(tǒng)字體對(duì)象

Font(字體文件路徑, 字體大小) --> 自定義字體
字體文件:后綴是.ttf文件
"""

font = pygame.font.SysFont('宋體', 50, italic=True)

font = pygame.font.Font('./files/aa.ttf', 50)

"""
2.根據(jù)字體創(chuàng)建文字對(duì)象
字體對(duì)象.render(文字,是否抗鋸齒,顏色)
"""
text = font.render('你好,python', True, (0, 255, 0))

"""
3.在窗口上渲染文字
"""
screen.blit(text, (100, 100))

"""
4.展示在屏幕上
"""
pygame.display.flip()

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
"""author = 余婷"""
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))

畫圖(pygame.draw)

"""
1.畫線
def 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)

"""
def 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, 6)

"""
2.畫圓
def circle(Surface, color, pos, radius, width=0)
pos: 圓心位置
radius: 半徑
width: 默認(rèn)0(填充)
"""
pygame.draw.circle(screen, (255, 255, 0), (100, 200), 80, 0)

"""
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, 100, 100), pi/4, pi/4*3, 4)

pygame.display.flip()

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

"""author = 余婷"""
import pygame

"""
1.鼠標(biāo)事件:
事件類型:event.type
MOUSEBUTTONDOWN --> 鼠標(biāo)按下
MOUSEBUTTONUP --> 鼠標(biāo)彈起
MOUSEMOTION --> 鼠標(biāo)移動(dòng)
關(guān)心鼠標(biāo)的位置:event.pos

鍵盤事件
"""
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))
pygame.display.flip()

while True:
# 只要有事件產(chǎn)生就會(huì)進(jìn)入for循環(huán)
for event in pygame.event.get():
# 根據(jù)判斷type的值來判斷是什么事件產(chǎn)生了
if event.type == pygame.QUIT:
exit()

    # =================鼠標(biāo)事件=================
    elif event.type == pygame.MOUSEBUTTONDOWN:
        # 鼠標(biāo)按下后要做什么事情就寫在這兒...
        print('鼠標(biāo)按下:', event.pos)
        pygame.draw.circle(screen, rand_color(), event.pos, random.randint(10, 40))
        pygame.display.flip()

    elif event.type == pygame.MOUSEBUTTONUP:
        # 鼠標(biāo)按下后彈起
        print('鼠標(biāo)彈起', event.pos)
    elif event.type == pygame.MOUSEMOTION:
        # 鼠標(biāo)移動(dòng)
        print('鼠標(biāo)移動(dòng)', 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))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 1recode 1.json數(shù)據(jù)json數(shù)據(jù)的要求:a.一個(gè)json對(duì)應(yīng)一個(gè)數(shù)據(jù)b.json中的數(shù)據(jù)一定是json...
    大漠判官1閱讀 387評(píng)論 0 0
  • 1.recode 1.json數(shù)據(jù)json數(shù)據(jù)的要求:a.一個(gè)json對(duì)應(yīng)一個(gè)數(shù)據(jù)b.json中的數(shù)據(jù)一定是jso...
    芽菜包66閱讀 233評(píng)論 0 0
  • recode """ 1.json數(shù)據(jù) json數(shù)據(jù)的要求:a.一個(gè)json對(duì)應(yīng)一個(gè)數(shù)據(jù)b.json中的數(shù)據(jù)一定是...
    我才是鱷魚寶寶閱讀 264評(píng)論 0 0
  • 曉道閱讀 231評(píng)論 0 0
  • 一、while 循環(huán),讓指定的代碼重復(fù)執(zhí)行 二、while語句寫法: 初始條件設(shè)置 —— 通常是重復(fù)執(zhí)行的 計(jì)數(shù)器...
    姓高名旭升閱讀 208評(píng)論 0 0