July 30-day13-Python中Pygame

weixin_33807284發表於2018-07-30

觸碰事件

有滑鼠、鍵盤等等

import pygame

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))

    pygame.display.set_caption('遊戲事件')
    desktop.fill((255,255,255))


    pygame.display.flip()
    """
    QUIT:關閉按鈕被點選事件
    MOUSEBUTTONDOWN:滑鼠按下
    MOUSEBUTTONUP:滑鼠彈起
    MOUSEMOTION:滑鼠移動
    
    
    KEYDOWN:鍵盤按下
    KEYUP:鍵盤彈出
    """
    while True:
        # 每次迴圈檢測有沒有事件發生()
        for event in pygame.event.get():
            # 不同型別的事件對應的type值不一樣
            if event.type == pygame.QUIT:
                exit()

            # 滑鼠相關事件
            # pos屬性,獲取滑鼠事件產生的位置
            if event.type == pygame.MOUSEBUTTONDOWN:
                print('滑鼠按下',event.pos)

            if event.type == pygame.MOUSEBUTTONUP:
                print('滑鼠彈起',event.pos)

            if event.type == pygame.MOUSEMOTION:
                print('滑鼠移動',event.pos)

            # 鍵盤相關事件
            # key屬性,被按的按鍵對應的值的編碼
            if event.type == pygame.KEYDOWN:
                print('鍵盤按鈕按下',chr(event.key))

            if event.type == pygame.KEYUP:
                print('鍵盤按鈕彈起',chr(event.key))
結果:
滑鼠移動 (780, 5)
滑鼠移動 (780, 6)
滑鼠按下 (780, 6)
滑鼠彈起 (780, 6)
滑鼠移動 (779, 6)
滑鼠移動 (778, 6)
鍵盤按鈕按下 Ĕ
鍵盤按鈕彈起 Ĕ
鍵盤按鈕按下 Ē
鍵盤按鈕彈起 Ē
鍵盤按鈕按下 ē
鍵盤按鈕彈起 ē
鍵盤按鈕按下 đ
鍵盤按鈕彈起 đ

對滑鼠事件的應用

import pygame
from random import randint

def random_color():
    # 產生隨機顏色
    return randint(0,255),randint(0,255),randint(0,255)
# 畫個圓
def draw_ball(screen,pos):
    pygame.draw.circle(screen, random_color(), pos, randint(10, 20))

    # 只要螢幕上的內容有更新, 都需要呼叫下面這兩個方法
    # pygame.display.flip()
    pygame.display.update()

# 判斷指定的點是否在指定的矩形範圍中
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

def draw_button(screen,bth_color, title_color):
    # 畫個按鈕
    # 矩形框
    pygame.draw.rect(screen, bth_color, (300, 300, 100, 60))
    # 矩形框中文字
    font = pygame.font.SysFont('Times', 30)
    title = font.render('B', True, title_color)
    desktop.blit(title, (330, 330))

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))
    pygame.display.set_caption('滑鼠事件')
    desktop.fill((255,255,255))

    # 畫個按鈕
    draw_button(desktop,(0,255,0),(255,0,0))

    pygame.display.flip()

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            if is_in_rect(event.pos,(300,300,100,60)):
                draw_button(desktop,(0,100,0),(100,0,0))
                pygame.display.update()
                print('點選滑鼠')
        if event.type == pygame.MOUSEBUTTONUP:
            if is_in_rect(event.pos,(300,300,100,60)):
                draw_button(desktop,(0, 255, 0),(255, 0, 0))
                pygame.display.update()

        if event.type == pygame.MOUSEMOTION:
            desktop.fill((255,255,255))
            draw_button(desktop, (0, 255, 0), (255, 0, 0))
            draw_ball(desktop,event.pos)
結果:
點選滑鼠
13183349-41f799cc5a0d37be.png
圖片 1

滑鼠點選事件的應用(對滑鼠的拖拽)

import pygame

# 判斷一個點是否在一個範圍內
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
if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))
    pygame.display.set_caption('圖片拖拽')
    desktop.fill((255,255,255))

    # 獲取一個圖片的尺寸
    # image_size = image.get_size()
    # print(image_size)
    image = pygame.image.load('./20018.png')
    image_x = 300
    image_y = 300
    is_move = False

    # 將圖片渲染
    desktop.blit(image, (image_x,image_y))

    # 弄到螢幕上
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            # 滑鼠點選效果
            if event.type == pygame.MOUSEBUTTONDOWN:
                image_w, image_h = image.get_size()
                if is_in_rect(event.pos, (image_x, image_y, image_w,image_h)):
                    is_move = True

            # 滑鼠彈出效果
            if event.type == pygame.MOUSEBUTTONUP:
                is_move = False

            # 滑鼠移動效果
            if event.type ==pygame.MOUSEMOTION:
                if is_move:
                    desktop.fill((255,255,255))
                    x,y = event.pos
                    image_w, image_h = image.get_size()
                    image_x = x-image_w/2
                    image_y = y-image_h/2
                    desktop.blit(image, (image_x,image_y))
                    pygame.display.update()
13183349-0791f45d8a72dd42.gif
圖片2

字型動畫的效果

import pygame
from random import randint
"""
動畫原理:不斷的重新整理介面上的內容(一幀一幀的畫)
"""
def static_page(screen):
    # 靜態文字
    font = pygame.font.SysFont('Times', 40)
    title = font.render('Hello,Python',True,(255,0,0))
    screen.blit(title, (200,200))

def animation_title(screen):
    # 產生隨機顏色的字型
    font = pygame.font.SysFont('Times', 40)
    title = font.render('Python', True, random_color())
    screen.blit(title, (300, 300))

def random_color():
    # 產生隨機顏色
    return randint(0,255),randint(0,255),randint(0,255)

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('動畫效果')
    desktop.fill((255, 255, 255))

    static_page(desktop)

    pygame.display.flip()
    while True:
        # for裡面的程式碼只有事件發生後才會執行
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        # 程式執行到這個位子,CPU休息一段時間再執行後面的程式碼(執行緒在這兒阻塞指定的時間)
        # 單位:毫秒(1000ms = 1s) 由於顏色變化太快看不清,所以delay
        pygame.time.delay(60)
        # 在下面去寫每一幀顯示的內容
        desktop.fill((255,255,255))
        static_page(desktop)
        animation_title(desktop)
        pygame.display.update()
13183349-3c4e74dc2f4ad0af.gif
圖片3

鍵盤事件的應用

import pygame

def draw_ball(place,color,pos):
    #畫球
    pygame.draw.circle(place,color,pos,40)

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))
    pygame.display.set_caption('球球遊戲')
    desktop.fill((255,255,255))

    # 儲存初始座標
    ball_x = 100
    ball_y = 100
    x_speed = 0
    y_speed = 0

    # 方向對應的key值
    Up = 273
    Down = 274
    Left = 276
    Right = 275

    pygame.display.flip()
    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 == Left:
                    y_speed = 0
                    x_speed = -5
                elif event.key == Right:
                    y_speed = 0
                    x_speed = +5

        pygame.time.delay(10)
        # 重新整理螢幕
        desktop.fill((255,255,255))

        ball_x += x_speed
        ball_y += y_speed
        if ball_x+40 >= 800:
            ball_x = 800-40
            x_speed *= -1
            print('game over!')
            exit()

        if ball_x-40 <= 0:
            ball_x = 0+40
            x_speed += 5
        draw_ball(desktop,(255,0,0),(ball_x,ball_y))
        pygame.display.update()
結果:
game over!
13183349-5847f9ea5ba073ce.gif
圖片4

多個球一起動

import pygame
import random

def ran_color():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('多個球一起動')
    desktop.fill((255, 255, 255))

    """
    all_balls中儲存多個球
    每個球要儲存:半徑、圓心座標、顏色、x速度、y速度
    """
    all_balls = []
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                ball = {
                        'r' : random.randint(10,25),
                        'pos': event.pos,
                        'color': ran_color(),
                        'x_speed': random.randint(-3, 3),
                        'y_speed': random.randint(-3, 3)
                }
                all_balls.append(ball)
                # is_move =True
        desktop.fill((255,255,255))
        for ball_dict in all_balls:
            # if  is_move:
            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(desktop,ball_dict['color'],(x,y),ball_dict['r'])
            # 更新球對應的座標
            ball_dict['pos'] = x,y

        pygame.time.delay(60)
        pygame.display.update()
13183349-b5c241345a14653d.gif
圖片5

相關文章