pygame應(yīng)用

一、pygame事件

import pygame      #導(dǎo)入pygame模塊

if __name__ == '__main__':
    #初始化
    pygame.init()
   #創(chuàng)建長(zhǎng)為600盛末,高為400的窗口
    screen=pygame.display.set_mode((600,400))
    #給窗口填充顏色為白色
    screen.fill((255,255,255))
    #設(shè)置窗口標(biāo)題
    pygame.display.set_caption('游戲事件')
    #顯示以上所有內(nèi)容
    pygame.display.flip()

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

            # 鼠標(biāo)相關(guān)事件
            #鼠標(biāo)按下
            if event.type == pygame.MOUSEBUTTONDOWN:
                print('打印鼠標(biāo)按下', event.pos)
            # 鼠標(biāo)彈起
            if event.type == pygame.MOUSEBUTTONUP:
                print('鼠標(biāo)彈起', event.pos)
            # 鼠標(biāo)移動(dòng)事件
            if event.type == pygame.MOUSEMOTION:
                print('鼠標(biāo)移動(dòng)', event.pos)

            #鍵盤(pán)相關(guān)事件
            #key屬性弹惦,被按得按鍵對(duì)應(yīng)的編碼
            if event.type==pygame.KEYDOWN:
                print('鍵盤(pán)被按下',chr(event.key))
            if event.type==pygame.KEYUP:
                print('鍵盤(pán)彈起',chr(event.key))
1-1.gif

二、鼠標(biāo)鍵盤(pán)應(yīng)用

import pygame
from random import randint

def rand_color():
    """
    產(chǎn)生隨機(jī)顏色
    """
    return randint(0, 255), randint(0, 255), randint(0, 255)

def draw_ball(screen, pos):
    pygame.draw.circle(screen, rand_color(), pos, randint(10, 20))
    # 只要屏幕上的內(nèi)容有更新悄但,都需要調(diào)用下面這兩個(gè)方法中的一個(gè)
    # pygame.display.flip()
    pygame.display.update()


# 寫(xiě)一個(gè)函數(shù)棠隐,判斷指定的點(diǎn)是否在指定的矩形范圍中
def is_in_rect(point, rect):
    x, y = point
    rx, ry, rw, rh = rect
    if (rx <= x <= rx+rw) and (ry <= y <= ry+rh):
        return True
    return False


# 寫(xiě)一個(gè)函數(shù),畫(huà)一個(gè)按鈕
def draw_button(screen, bth_color, title_color):
    # 畫(huà)個(gè)按鈕
    """矩形框"""
    pygame.draw.rect(screen, bth_color, (100, 100, 100, 60))
    """文字"""
    font = pygame.font.SysFont('Times', 30)
    title = font.render('clicke', True, title_color)
    screen.blit(title, (120, 120))

# 按鈕坐標(biāo)

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    screen.fill((255,255,255))
    pygame.display.set_caption('鼠標(biāo)事件')

    # 畫(huà)個(gè)按鈕
    draw_button(screen, (0, 255, 0), (255, 0, 0))
    # """矩形框"""
    # pygame.draw.rect(screen,(0, 255, 0),(100, 100, 100, 60))
    # """文字"""
    # font = pygame.font.SysFont('Times', 30)
    # title = font.render('clicke',True,(255, 0, 0))
    # screen.blit(title, (120, 120))
    pygame.display.flip()

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                # 在指定的坐標(biāo)處畫(huà)一個(gè)球
                # draw_ball(screen, event.pos)
                if is_in_rect(event.pos, (100, 100, 100, 60)):
                    draw_button(screen, (0, 100, 0), (100, 0, 0))
                    pygame.display.update()

            if event.type == pygame.MOUSEBUTTONUP:
                if is_in_rect(event.pos, (100, 100, 100, 60)):
                    draw_button(screen, (0, 255, 0),(255, 0, 0))
                    pygame.display.update()

            if event.type == pygame.MOUSEMOTION:
                screen.fill((255, 255, 255))
                draw_button(screen, (0, 255, 0), (255, 0, 0))
                draw_ball(screen, event.pos)

效果如下:


2-1.gif

三檐嚣、鼠標(biāo)事件應(yīng)用2

要求:先在屏幕上顯示一張圖片助泽,鼠標(biāo)按下移動(dòng)的時(shí)候,拽著圖片跟著一起動(dòng)嚎京,鼠標(biāo)彈起就不動(dòng)了

import pygame

#寫(xiě)一個(gè)函數(shù)嗡贺,判斷一個(gè)點(diǎn)是否在某個(gè)范圍內(nèi)
# 點(diǎn)(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((800,800))
    screen.fill((255,255,255))
    pygame.display.set_caption('圖片拖拽')


    #顯示一張圖片
    image = pygame.image.load('./趙麗穎2.jpg')
    # image_size = image.get.size()
    # print(image_size)
    image_x=100
    image_y=100
    #顯示在屏幕上
    screen.blit(image,(image_x,image_y))

    pygame.display.flip()

    #用來(lái)儲(chǔ)存圖片是否可以移動(dòng)
    is_move=False

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

            #鼠標(biāo)按下,讓狀態(tài)變成可以移動(dòng)
            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)變成不可以移動(dòng)
            if event.type==pygame.MOUSEBUTTONUP:
                is_move=False

            #鼠標(biāo)移動(dòng)對(duì)應(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()

效果如下:

3.gif

四诫睬、動(dòng)畫(huà)效果

"""
動(dòng)畫(huà)原理:不斷刷新界面上的內(nèi)容(一幀一幀的畫(huà))

"""

import pygame
from random import randint

def static_page(screen):
    """
    頁(yè)面上的靜態(tài)顯示
    :param screen:
    :return:
    """
    #靜態(tài)文字
    font=pygame.font.SysFont('times',40)
    title=font.render('welcome',True,(0,0,0))
    screen.blit(title,(200,100))

def animation_title(screen):
    """
    字體顏色發(fā)生改變
    :param screen:
    :return:
    """

    font = pygame.font.SysFont('times', 40)
    title = font.render('python', True, (randint(0,255),randint(0,255),randint(0,255)))
    screen.blit(title, (200,200))

if __name__ == '__main__':
    pygame.init()
    screen=pygame.display.set_mode((600,400))
    screen.fill((255,255,255))
    pygame.display.set_caption('動(dòng)畫(huà)效果')

    static_page(screen)

    pygame.display.flip()



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

        #在下面去寫(xiě)每一幀要顯示的內(nèi)容
        #程序執(zhí)行到這個(gè)位置,線程在這阻塞指定的時(shí)間(毫秒)1000ms=1s
        pygame.time.delay(300)

        #動(dòng)畫(huà)前要將原來(lái)的內(nèi)容全部清空
        screen.fill((255,255,255))
        static_page(screen)
        animation_title(screen)

        #內(nèi)容展示完膜眠,要顯示更新到屏幕上
        pygame.display.update()

效果如下:


4-1.gif

五岩臣、ballgame


import pygame

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

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

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

    pygame.display.flip()

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

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

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


            # if event.type==pygame.KEYDOWN:
            #     print(event.key)

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

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

        #邊界檢測(cè)
        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()

效果如下:


5-1.gif

六、多個(gè)球動(dòng)起來(lái)

import pygame
import random

random_color=random.randint(0,255),random.randint(0,255),random.randint(0,255) #聲明一個(gè)變量同時(shí)賦多個(gè)值宵膨,相當(dāng)于一個(gè)元祖

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

    #all_balls中保存多個(gè)球
    #每個(gè)球要保存:半徑、圓心坐標(biāo)炸宵、顏色辟躏、x速度、y速度
    all_balls=[{'r':random.randint(10,20),
                'pos':(100,100),
                'color':random_color,
                'x_speed':random.randint(-3,3),
                'y_speed':random.randint(-3,3)},
               {'r':random.randint(10,20),
                'pos':(300,300),
                'color':random_color,
                'x_speed':random.randint(-3,3),
                'y_speed':random.randint(-3,3)},
               {'r':random.randint(10,20),
                'pos':(200,200),
                'color':random_color,
                'x_speed':random.randint(-3,3),
                'y_speed':random.randint(-3,3)}
               ]


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

            if event.type==pygame.MOUSEBUTTONDOWN:
                random_color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
                ball={
                    'r':random.randint(10,25),
                    'pos':event.pos,
                    'color':random_color,
                    'x_speed':random.randint(-3,3),
                    'y_speed':random.randint(-3,3)
                }
                #保存球
                all_balls.append(ball)

        #刷新界面
        screen.fill((255,255,255))

        for ball_dict in all_balls:
            #取出x和y坐標(biāo)以及他們的速度
            x,y=ball_dict['pos']
            x_speed=ball_dict['x_speed']
            y_speed=ball_dict['y_speed']

            x+=x_speed
            y+=y_speed
            pygame.draw.circle(screen,ball_dict['color'],(x,y),ball_dict['r'])

            #重新跟新球?qū)?yīng)的坐標(biāo)
            ball_dict['pos']=x,y

        pygame.display.update()

效果如下:


6.gif
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末土全,一起剝皮案震驚了整個(gè)濱河市捎琐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌裹匙,老刑警劉巖瑞凑,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異概页,居然都是意外死亡籽御,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)技掏,“玉大人铃将,你說(shuō)我怎么就攤上這事⊙剖幔” “怎么了劲阎?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)鸠真。 經(jīng)常有香客問(wèn)我悯仙,道長(zhǎng),這世上最難降的妖魔是什么吠卷? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任雁比,我火速辦了婚禮,結(jié)果婚禮上撤嫩,老公的妹妹穿的比我還像新娘偎捎。我一直安慰自己,他們只是感情好序攘,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布茴她。 她就那樣靜靜地躺著,像睡著了一般程奠。 火紅的嫁衣襯著肌膚如雪丈牢。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,482評(píng)論 1 302
  • 那天瞄沙,我揣著相機(jī)與錄音己沛,去河邊找鬼。 笑死距境,一個(gè)胖子當(dāng)著我的面吹牛申尼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播垫桂,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼师幕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了诬滩?” 一聲冷哼從身側(cè)響起霹粥,我...
    開(kāi)封第一講書(shū)人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疼鸟,沒(méi)想到半個(gè)月后后控,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡空镜,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年浩淘,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了捌朴。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡馋袜,死狀恐怖男旗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情欣鳖,我是刑警寧澤察皇,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站泽台,受9級(jí)特大地震影響什荣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜怀酷,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一稻爬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蜕依,春花似錦桅锄、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至檐束,卻和暖如春辫秧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背被丧。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工盟戏, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人甥桂。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓柿究,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親格嘁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子笛求,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

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

  • 01 pygame事件 02 鼠標(biāo)事件的運(yùn)用 03 鼠標(biāo)事件的應(yīng)用2 要求:先在屏幕上顯示一張圖片,鼠標(biāo)按下移動(dòng)的...
    跟我念一遍閱讀 356評(píng)論 0 2
  • 1.pygame事件 QUIT:關(guān)閉按鈕被點(diǎn)擊事件MOUSEBUTTONDOWN:鼠標(biāo)按下MOUSEBUTTONU...
    曉曉的忍兒閱讀 408評(píng)論 0 11
  • 01.pygame事件 02.鼠標(biāo)事件的應(yīng)用 03.鼠標(biāo)事件的應(yīng)用2 04.動(dòng)畫(huà)效果 05.ballGame 06...
    zhazhaK丶閱讀 315評(píng)論 0 3
  • 上周內(nèi)容回顧: 1.列表糕簿、字典、集合狡孔、元祖{key:value}, key唯一的懂诗,key值是不可變的 元祖:不可變...
    ____空白閱讀 289評(píng)論 0 5
  • 3月份 院優(yōu)寢一次;參加國(guó)家二級(jí)計(jì)算機(jī)考試;院躍動(dòng)杯籃球賽且集體一等獎(jiǎng),女生節(jié)海報(bào)制作優(yōu)秀工作者苗膝,參加畢業(yè)杯籃球賽...
    嬌妮妮閱讀 167評(píng)論 0 0