Day11-pygame應(yīng)用

上周內(nèi)容回顧:


1.列表找前、字典、集合判族、元祖
{key:value}, key唯一的躺盛,key值是不可變的

元祖:不可變的,有序的
(元素,)

集合:可變五嫂、無序
{元素}
數(shù)學(xué)相關(guān)的集合運算

dict1 = {'a':12,'b':[
{'aa':1, 'bb':2},
{'aa':100, 'bb':200}
]}
dict1['b'].append
dict1['b'].remove
dict1['b'][]

dict1['b'][1]['bb']

怎么選是用字典還是列表?:
(1.同時存儲多個信息 --> 考慮使用容器類型(列表颗品、字典肯尺、集合沃缘、元祖)
(2.是否可以對數(shù)據(jù)進行增刪改查---> 是:列表、字典 否:元祖则吟、集合
(3.看存儲的數(shù)據(jù)是否是同一類數(shù)據(jù)---> 是:列表 否:字典


2.函數(shù)
(1.怎么聲明函數(shù)
def 函數(shù)名(參數(shù)列表):
函數(shù)體

(2.參數(shù)
參數(shù)的功能是從函數(shù)外面給函數(shù)傳值

傳參:位置參數(shù)槐臀、關(guān)鍵參數(shù)(保證每個參數(shù)都要有值)

參數(shù)可以有默認值:1.有默認值的參數(shù)要放到?jīng)]有默認值的參數(shù)的后面 2.可以不用傳參

參數(shù)個數(shù)可以不定:參數(shù)名前加'',參數(shù)就變成元祖
補充:容器類型前面加'
',就是將容器中的所有的元素全部取出(元祖用得比較多)

(3.返回值
return后面的表達式的值(沒有遇到return脱吱,默認是None)
函數(shù)調(diào)用表達式的值

凡是函數(shù)功能會產(chǎn)生數(shù)據(jù)迂求,或者想要給調(diào)用者返回信息的時候由蘑,都需要返回值

(4.函數(shù)的調(diào)用過程
a.回到函數(shù)聲明的位置
b.用實參給形參賦值
c.執(zhí)行函數(shù)體
d.遇到return 或者函數(shù)體執(zhí)行完诫肠,將返回值返回給調(diào)用者
e.回到函數(shù)調(diào)用的位置(調(diào)用表達式的值是返回值),接著往下執(zhí)行

(5.函數(shù)作為變量

(6.匿名函數(shù)
函數(shù)名 = lambda 參數(shù)列表:返回值(不需要return)
函數(shù)名(實參)

(7.遞歸(了解)

(8.yeild函數(shù)(迭代器和生成器)


3.文件操作
打開文件-操作文件-關(guān)閉文件
open()菩帝、colse() \ with open() as
read()
wirte()

打開方式:'r','rb'\ 'w','wr','a'

json文件的操作
json內(nèi)置模塊症概,load,drump
loads\drumps


4.異常捕獲

try:
需要捕獲異常的代碼
except: -- 捕獲所有的異常
出現(xiàn)異常執(zhí)行的代碼

try:
需要捕獲異常的代碼
except(異常類型1,異常類型2):
出現(xiàn)異常執(zhí)行的代碼

try:
需要捕獲異常的代碼
except 異常類型1:
代碼塊1
except 異常類型2:
代碼塊2
except:
代碼塊3

try-except-finally
"""


def func2(*nums):

    print(sum(nums))

def func1(*numbers):

    print(numbers)
    func2(*numbers)


if __name__ == '__main__':

    func1(1, 2, 3)

    number = {11, 21, 33}
    print(number, *number)

    dict1 = {'a': 12, 'b': [
        {'aa': 1, 'bb': 2},
        {'aa': 100, 'bb': 200}
    ]}
    # 這個是個列表
    list_b = dict1['b']
    # 這個是一個字典
    dict_1 = list_b[1]
    # dict1['b'].append
    # dict1['b'].remove
    # dict1['b'][]
    print(dict1['b'][1]['bb'])

1. pygame事件

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))
    # 設(shè)置窗口標(biāo)題
    pygame.display.set_caption('游戲事件')

    pygame.display.flip()

    """
    QUIT:關(guān)閉按鈕被點擊事件
    MOUSEBUTTONDOWN: 鼠標(biāo)按下事件
    MOUSEBUTTONUP: 鼠標(biāo)按下彈起
    MOUSEMOTION:鼠標(biāo)移動
    鼠標(biāo)相關(guān)事件關(guān)心事件產(chǎn)生的位置
    
    KEYDOWN: 鍵盤按下
    KEYUP: 鍵盤彈起
    """
    while True:
        # 每次循環(huán)檢測有沒有事件發(fā)生
        for event in pygame.event.get():
            # 不同類型的事件對應(yīng)的type值不一樣
            if event.type == pygame.QUIT:
                exit()

            # 鼠標(biāo)相關(guān)事件
            # pos屬性油航,獲取鼠標(biāo)事件產(chǎn)生的位置
            if event.type == pygame.MOUSEBUTTONDOWN:
                print('鼠標(biāo)按下', event.pos)

            if event.type == pygame.MOUSEBUTTONUP:
                print('鼠標(biāo)彈起', event.pos)

            if event.type == pygame.MOUSEMOTION:
                print('鼠標(biāo)移動', event.pos)

            # 鍵盤相關(guān)事件
            # key屬性糊闽,被按的按鍵對應(yīng)的值的編碼
            if event.type == pygame.KEYDOWN:
                print('鍵盤按鍵被按下',chr(event.key))

            if event.type == pygame.KEYUP:
                print('鍵盤按鈕彈起', chr(event.key))

2.鼠標(biāo)事件的應(yīng)用

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))
    # 設(shè)置窗口標(biāo)題
    pygame.display.set_caption('游戲事件')

    pygame.display.flip()

    """
    QUIT:關(guān)閉按鈕被點擊事件
    MOUSEBUTTONDOWN: 鼠標(biāo)按下事件
    MOUSEBUTTONUP: 鼠標(biāo)按下彈起
    MOUSEMOTION:鼠標(biāo)移動
    鼠標(biāo)相關(guān)事件關(guān)心事件產(chǎn)生的位置
    
    KEYDOWN: 鍵盤按下
    KEYUP: 鍵盤彈起
    """
    while True:
        # 每次循環(huán)檢測有沒有事件發(fā)生
        for event in pygame.event.get():
            # 不同類型的事件對應(yīng)的type值不一樣
            if event.type == pygame.QUIT:
                exit()

            # 鼠標(biāo)相關(guān)事件
            # pos屬性啥箭,獲取鼠標(biāo)事件產(chǎn)生的位置
            if event.type == pygame.MOUSEBUTTONDOWN:
                print('鼠標(biāo)按下', event.pos)

            if event.type == pygame.MOUSEBUTTONUP:
                print('鼠標(biāo)彈起', event.pos)

            if event.type == pygame.MOUSEMOTION:
                print('鼠標(biāo)移動', event.pos)

            # 鍵盤相關(guān)事件
            # key屬性谍珊,被按的按鍵對應(yīng)的值的編碼
            if event.type == pygame.KEYDOWN:
                print('鍵盤按鍵被按下',chr(event.key))

            if event.type == pygame.KEYUP:
                print('鍵盤按鈕彈起', chr(event.key))

3. 鼠標(biāo)事件的應(yīng)用2

# 要求:先在屏幕上顯示一張圖片,鼠標(biāo)按下移動的時候急侥,拽著圖片跟著一起動砌滞。鼠標(biāo)彈起就不動了
import pygame


# 寫一個函數(shù),判斷一個點是否在某個范圍內(nèi)
# 點(x,y)
# 范圍 rect(x,y,w,h)
def is_in_rect(pos, rect):
    x, y = pos
    rx, ry, rw, rh = rect
    if (rx <= x <= rx+rw) and (ry <= y <= ry+rh):
        return True
    return False


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))
    pygame.display.set_caption('圖片拖拽')

    # 顯示一張圖片
    image = pygame.image.load('./luffy2.png')
    image_x = 100
    image_y = 100
    screen.blit(image,(image_x, image_y))
    pygame.display.flip()

    # 用來存儲圖片是否可以移動
    is_move = False

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

            # 鼠標(biāo)按下坏怪,讓狀態(tài)變成可以移動
            if event.type == pygame.MOUSEBUTTONDOWN:
                w,h = image.get_size()
                if is_in_rect(event.pos, (image_x, image_y, w, h)):
                    is_move = True

            # 鼠標(biāo)彈起贝润,讓狀態(tài)變成不可以移動
            if event.type == pygame.MOUSEBUTTONUP:
                is_move = False


            # 鼠標(biāo)移動對應(yīng)的事件
            if event.type == pygame.MOUSEMOTION:
                if is_move:
                    screen.fill((255, 255, 255))
                    x, y = event.pos
                    image_w, image_h = image.get_size()
                    # 保證鼠標(biāo)在圖片的中心
                    image_y = y-image_h/2
                    image_x = x-image_w/2
                    screen.blit(image, (image_x, image_y))
                    pygame.display.update()



4. 動畫效果


"""
動畫原理:不斷的刷新界面上的內(nèi)容(一幀一幀的畫)
"""
import pygame
from random import randint


def static_page(screen):
    """
    頁面上的靜態(tài)內(nèi)容
    """
    # 靜態(tài)文字
    font = pygame.font.SysFont('Times', 40)
    title = font.render('Welcome', True, (0, 0, 0))
    screen.blit(title, (200, 200))

def animation_title(screen):
    """
    字體顏色發(fā)生改變
    """
    font = pygame.font.SysFont('Times', 40)
    title = font.render('Python', True, (randint(0,255), randint(0,255), randint(0,255)))
    screen.blit(title, (100, 100))


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))

    static_page(screen)

    pygame.display.flip()

    while True:
        # for里面的代碼只有事件發(fā)生后才會執(zhí)行
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        # 在下面去寫每一幀要顯示的內(nèi)容
        """程序執(zhí)行到這個位置,cup休息一段時間再執(zhí)行后面的代碼(線程在這兒阻塞指定的時間)
        單位:毫秒  (1000ms == 1s)
        """
        pygame.time.delay(60)

        # 動畫前要將原來的內(nèi)容全部清空
        screen.fill((255, 255, 255))

        static_page(screen)
        animation_title(screen)

        # 內(nèi)容展示完成后铝宵,要更新到屏幕上
        pygame.display.update()



**6.ballgame

import pygame


def draw_ball(place, color, pos):
    """
    畫球
    """
    pygame.draw.circle(place, color, pos, 20)

# 方向?qū)?yīng)的key值
Up = 273
Down = 274
Left = 276
Right = 275

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))
    pygame.display.flip()

    # 保存初始坐標(biāo)
    ball_x = 100
    ball_y = 100
    x_speed = 5
    y_speed = 0

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

            # 通過上下左右鍵控制球的方向
            if event.type == pygame.KEYDOWN:
                if event.key == Up:
                    y_speed = -5
                    x_speed = 0
                elif event.key == Down:
                    y_speed = 5
                    x_speed = 0
                elif event.key == Right:
                    x_speed = 5
                    y_speed = 0
                elif event.key == Left:
                    x_speed = -5
                    y_speed = 0


        # 刷新屏幕
        screen.fill((255, 255, 255))

        # 每次循環(huán)讓球的x和y坐標(biāo)變化
        ball_x += x_speed
        ball_y += y_speed

        # 邊界檢測
        if ball_x + 20 >= 600 or ball_x <= 20 or ball_y + 20 >= 400 or ball_y <= 20:
            print('游戲結(jié)束')
            exit()
            # ball_x = 600 -20
            # x_speed *= -1
        draw_ball(screen, (255, 0, 0), (ball_x, ball_y))

        pygame.display.update()

6. 多個球一起運動

import pygame


def draw_ball(place, color, pos):
    """
    畫球
    """
    pygame.draw.circle(place, color, pos, 20)

# 方向?qū)?yīng)的key值
Up = 273
Down = 274
Left = 276
Right = 275

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255, 255, 255))
    pygame.display.flip()

    # 保存初始坐標(biāo)
    ball_x = 100
    ball_y = 100
    x_speed = 5
    y_speed = 0

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

            # 通過上下左右鍵控制球的方向
            if event.type == pygame.KEYDOWN:
                if event.key == Up:
                    y_speed = -5
                    x_speed = 0
                elif event.key == Down:
                    y_speed = 5
                    x_speed = 0
                elif event.key == Right:
                    x_speed = 5
                    y_speed = 0
                elif event.key == Left:
                    x_speed = -5
                    y_speed = 0


        # 刷新屏幕
        screen.fill((255, 255, 255))

        # 每次循環(huán)讓球的x和y坐標(biāo)變化
        ball_x += x_speed
        ball_y += y_speed

        # 邊界檢測
        if ball_x + 20 >= 600 or ball_x <= 20 or ball_y + 20 >= 400 or ball_y <= 20:
            print('游戲結(jié)束')
            exit()
            # ball_x = 600 -20
            # x_speed *= -1
        draw_ball(screen, (255, 0, 0), (ball_x, ball_y))

        pygame.display.update()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末打掘,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌尊蚁,老刑警劉巖唯绍,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異枝誊,居然都是意外死亡况芒,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門叶撒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绝骚,“玉大人,你說我怎么就攤上這事祠够⊙雇簦” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵古瓤,是天一觀的道長止剖。 經(jīng)常有香客問我,道長落君,這世上最難降的妖魔是什么穿香? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮绎速,結(jié)果婚禮上皮获,老公的妹妹穿的比我還像新娘。我一直安慰自己纹冤,他們只是感情好洒宝,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著萌京,像睡著了一般雁歌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上知残,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天靠瞎,我揣著相機與錄音,去河邊找鬼橡庞。 笑死较坛,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的扒最。 我是一名探鬼主播丑勤,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼吧趣!你這毒婦竟也來了法竞?” 一聲冷哼從身側(cè)響起耙厚,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎岔霸,沒想到半個月后薛躬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡呆细,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年型宝,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片絮爷。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡趴酣,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出坑夯,到底是詐尸還是另有隱情岖寞,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布柜蜈,位于F島的核電站仗谆,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏淑履。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一鳖谈、第九天 我趴在偏房一處隱蔽的房頂上張望岁疼。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽驶臊。三九已至挪挤,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間关翎,已是汗流浹背扛门。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留纵寝,地道東北人论寨。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像爽茴,于是被迫代替她去往敵國和親政基。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354

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